def average_out_pred(r=2): model_name = 'ti-unet' path = os.path.join( folder_base, f'net_weight/{data}/{model_name}_d1_k{k}_n80/w_{1}.h5') model_i = load_model_quick(path) neural_net_i = NeuralNet(model_i, w_ext=10, norm_x=True) y_pred_lst = [] r = 2 for epoch_i in range(epoch - r, epoch + r + 1): # epochs neural_net_i.load(path.rsplit('/', 1)[0], epoch_i) # Load try: y_pred_i = neural_net_i.predict(img_x) except Exception as e: print(e) continue y_pred_lst.append(y_pred_i[..., 1]) y_pred_avg = np.mean(y_pred_lst, axis=0) return y_pred_avg
def __init__(self): # data self.data() # Load model(s) model_name = 'unet' # ['simple', 'ti-unet', 'unet']: folder = f'C:/Users/admin/Data/ghent_altar/net_weight/{model_name}_d1_k9_n80' epoch = 1 path = f'C:/Users/admin/Data/ghent_altar/net_weight/{model_name}_d1_k9_n80/w_{epoch}.h5' from scripts.scripts_performance.main_performance import load_model_quick model = load_model_quick(path) neural_net = NeuralNet(model, w_ext=10, norm_x=True) model.summary() for epoch in range(1, 10 + 1): print('epoch', epoch) neural_net.load(folder, epoch) # Predict y_pred = neural_net.predict(self.img_x) if 0: plt.imshow(y_pred[..., 0]) plt.show() for val_name in self.val: print(val_name) y_true_val = self.val[val_name] data_i = _eval_func_single(y_true_val, y_pred) print(data_i) # TODO best performing (ti-unet: 4) neural_net.load(folder, 4) y_pred = neural_net.predict(self.img_x) from performance.testing import get_y_pred_thresh y_pred_thresh = get_y_pred_thresh(y_pred, data_i['thresh']) concurrent([ self.img_x[..., :3], self.img_y[..., 0], y_pred[..., 0], y_pred_thresh[..., 0] ]) y_pred
def get_n_model_regular(self, i_fold=None, k=None, epoch=None): n_in = 9 model_tiunet = ti_unet(n_in, filters=k, w=self.w_patch, ext_in=10 // 2, batch_norm=True, wrong_batch_norm=True) """ TODO wrong tiunet """ n = NeuralNet(model_tiunet, w_ext=10) info = f'10lamb_kfold/ti_unet_k{k}_kfold{i_fold}' folder = os.path.join('/scratch/lameeus/data/ghent_altar/net_weight', info) n.load(folder=folder, epoch=epoch) return n
def get_model(): if self.ti: model = self.get_tiunet_preenc(k=self.k, lr=self.lr_opt) else: model = self.get_unet_preenc(k=self.k, lr=self.lr_opt) if self.fixed_enc == 2: n_temp = NeuralNet(model) folder_weights = '/scratch/lameeus/data/ghent_altar/net_weight' folder1 = f'10lamb_kfold_pretrained{"_encfixed"}{info_batchnorm}' folder2 = f'{info_model}_d{self.depth}_k{self.k}_ifold{i_fold}' n_temp.load(os.path.join(folder_weights, folder1, folder2), 100) del (n_temp) return model
def get_n_model(self, i_fold=None, k=None, epoch=None): n_in = 9 model_tiunet = ti_unet(n_in, filters=k, w=self.w_patch, ext_in=10 // 2, batch_norm=True) n = NeuralNet(model_tiunet, w_ext=10) info_batchnorm = '_batchnorm' info_fixed = '_encfixed' if self.fixed_enc == 1 else '_prefixed' if self.fixed_enc == 2 else '' info_model = 'tiunet' info = f'10lamb_kfold_pretrained{info_fixed}{info_batchnorm}/{info_model}_d{1}_k{k}_ifold{i_fold}' folder = os.path.join('/scratch/lameeus/data/ghent_altar/net_weight', info) n.load(folder=folder, epoch=epoch) return n
def train_segm(self): from figures_paper.overlay import semi_transparant if self.fixed_enc == -2: def get_n_model_regular(i_fold=None, k=None, epoch=None): n_in = 9 model_tiunet = ti_unet(n_in, filters=k, w=self.w_patch, ext_in=10 // 2, batch_norm=True, wrong_batch_norm=True) compile_segm(model_tiunet, 1e-4) """ TODO wrong tiunet """ n = NeuralNet(model_tiunet, w_ext=10) info = f'10lamb_kfold/ti_unet_k{k}_kfold{i_fold}' folder = os.path.join( '/scratch/lameeus/data/ghent_altar/net_weight', info) n.load(folder=folder, epoch=epoch) return n n_segm = get_n_model_regular(i_fold=self.i_fold, k=self.k, epoch=40) elif self.fixed_enc == -1: # No init model_segm = self.get_tiunet_preenc(k=self.k, lr=self.lr_opt) n_segm = NeuralNet(model_segm, w_ext=self.w_ext_in_ti) elif self.fixed_enc in [0, 1, 2]: # Load model model_segm = self.get_tiunet_preenc(k=self.k, lr=self.lr_opt) n_segm = NeuralNet(model_segm, w_ext=self.w_ext_in_ti) # Train on set folder_weights = '/scratch/lameeus/data/ghent_altar/net_weight' if self.fixed_enc == 0: folder1 = '10lamb_kfold_pretrained_batchnorm' elif self.fixed_enc == 1: folder1 = '10lamb_kfold_pretrained_encfixed_batchnorm' elif self.fixed_enc == 2: folder1 = '10lamb_kfold_pretrained_prefixed_batchnorm' folder2 = f'{"tiunet"}_d{self.depth}_k{self.k}_ifold{self.i_fold}' n_segm.load(os.path.join(folder_weights, folder1, folder2), 100) elif self.fixed_enc == 3: model_segm = self.get_tiunet_preenc(k=self.k, lr=self.lr_opt, set_info=f'_{self.set_nr}', epoch_start=100) n_segm = NeuralNet(model_segm, w_ext=self.w_ext_in_ti) else: NotImplementedError() def foo(n_segm, b=0): y_pred = n_segm.predict(self.img_x) thresh_single = optimal_test_thresh_equal_distribution( self.img_y_te, y_pred) # data_single_i = {'k': self.k, # 'i_fold': i_fold, # 'epoch': epoch} print(foo_performance(self.img_y_te, y_pred, thresh_single)) img_clean = self.img_x[..., :3] concurrent([ img_clean, y_pred[..., 1], y_pred[..., 1] >= thresh_single, semi_transparant(img_clean, y_pred[..., 1] >= thresh_single) ]) if b: from data.datatools import imsave folder = '/home/lameeus/data/ghent_altar/output/hierarchy/' info_epoch = f'_epoch{n_segm.epoch}' if n_segm.epoch > 0 else '' filename = folder + f'13_small/pred_transfer_kfoldenc{self.fixed_enc}_ifold{self.i_fold}_avg{info_epoch}.png' imsave(filename, y_pred[..., 1]) def set_encoder_state(model, trainable=False): assert len(model.layers) == 14 for layer in model.layers[:7]: layer.trainable = trainable compile_segm(model) n_segm.epoch = 0 # Without pretraining foo(n_segm) # epochs set_encoder_state(n_segm.model, trainable=False) for _ in range(10): n_segm.train(self.flow_tr_10, epochs=1, verbose=2) foo(n_segm, 0) if 0: set_encoder_state(n_segm.model, trainable=True) for _ in range(1): n_segm.train(self.flow_tr_set_10, epochs=10, verbose=2) foo(n_segm, 0) set_encoder_state(n_segm.model, trainable=True) for _ in range(10): n_segm.train(self.flow_tr_set, epochs=1, verbose=2) foo(n_segm, 0)
class Main(object): def __init__(self, k=None, seed=None): if k is not None: self.k = k self.seed = seed self.model() self.train() def model(self, b_optimal_lr=False): features_out = 3 if data_name == '19botrightcrack3' else 2 if model_name == 'ti-unet': model = ti_unet( 9, filters=self.k, w=w_patch, ext_in=w_ext_in // 2, batch_norm=True, max_depth=d, features_out=features_out, ) elif model_name == 'unet': # model = ti_unet(9, filters=self.k, w=w_patch, ext_in=w_ext_in // 2, batch_norm=True, # max_depth=d) print('NO BATCH NORM? (not implemented)') model = unet(9, filters=self.k, w=w_patch, ext_in=w_ext_in // 2, max_depth=d, n_per_block=1) else: raise ValueError(model_name) model.summary() compile_segm(model, lr=lr) if b_optimal_lr: from neuralNetwork.optimization import find_learning_rate global flow_tr find_learning_rate(model, flow_tr) self.neural_net = NeuralNet(model, w_ext=w_ext_in) if data_name[:5] == '1319_': # pre Load model! # TODO which epoch to start from, I guess 10 should have an impact epoch_start = 50 # probably better (learned something) self.neural_net.load( f'C:/Users/admin/Data/ghent_altar/net_weight/1319/{model_name}_d{d}_k{self.k}', epoch=epoch_start) def train(self, epochs=epochs, steps_per_epoch=100): global flow_tr info = f'{data_name}/{model_name}_d{d}_k{self.k}' try: if n_per_class is not None: info = '_'.join([info, f'n{n_per_class}']) except NameError: pass # If n_per_class does not exist, don't add it if self.seed is not None: info += f'_s{self.seed}' self.neural_net.train( flow_tr, # validation=flow_va, epochs=epochs, steps_per_epoch=steps_per_epoch, info=info) # Solve Memory problems? del self.neural_net def eval(self): pass
class Main(object): k = 8 n_per_class = 80 d = 1 epochs = 100 if d == 1: w_ext_in = 10 elif d == 2: w_ext_in = 26 w_patch = 10 if 0: lr = 1e-3 steps_per_epoch = 100 else: lr = 1e-4 steps_per_epoch = 1000 def __init__(self, k=None, n_per_class=None): if k is not None: self.k = k if n_per_class is not None: self.n_per_class = n_per_class # Get net self.model_train = self.main_net(set_net) from methods.basic import NeuralNet self.neural_net = NeuralNet(self.model_train, w_ext=self.w_ext_in) # Get data train_data = self.main_data(set_data) n_val_datas = len(self.val_datas) lst_data = [[] for _ in range(n_val_datas + 1)] for _ in range(self.epochs): # Train self.main_train(train_data) # Evaluate data_lst = self.main_eval(train_data) for i, data_i in enumerate(data_lst): data_i.update({'epoch': self.neural_net.epoch}) lst_data[i].append(data_i) for i in range(n_val_datas + 1): df = pd.DataFrame(lst_data[i]) print(df) if i == 0: data_name = 'val' else: data_name = self.val_datas[i - 1]['name'] model_name = f'{set_net["name"]}_data{data_name}_d{self.d}_k{self.k}_n{self.n_per_class}' pandas_save( f'C:/Users/admin/OneDrive - ugentbe/data/dataframes/{model_name}.csv', df, append=True) if 0: if 0: self.neural_net.load( 'C:/Users/admin/Data/ghent_altar/net_weight/tiunet_d1_k10_n80', 4) self.main_eval(train_data, b_plot=True) print("Finished init") def main_net(self, set_n): from methods.examples import compile_segm from neuralNetwork.architectures import ti_unet, convNet, unet n_name = set_n['name'].lower() if n_name == 'ti-unet': model = ti_unet(9, filters=self.k, w=self.w_patch, ext_in=self.w_ext_in // 2, batch_norm=True, max_depth=self.d) elif n_name == 'simple': model = convNet(9, self.k, w_in=self.w_patch + self.w_ext_in, n_convs=5, batch_norm=False, padding='valid') assert model.output_shape[-3:] == (self.w_patch, self.w_patch, 2) elif n_name == 'unet': print('NO BATCH NORM? (not implemented)') model = unet(9, filters=self.k, w=self.w_patch, ext_in=self.w_ext_in // 2, max_depth=self.d, n_per_block=1) else: raise ValueError(n_name) # raise NotImplementedError('Unet is not well implemented: * Double, batchnorm? f per layer etc?') model.summary() compile_segm( model, lr=self.lr) # instead of 10e-3, 10e-4 is probs more stable. return model def main_data(self, set_data): if set_data['name'] == 'zach_sh': from datasets.default_trainingsets import get_13botleftshuang train_data = get_13botleftshuang(mod, n_per_class=self.n_per_class) else: raise NotImplementedError() from data.preprocessing import rescale0to1 train_data.x = rescale0to1(train_data.x) from datasets.default_trainingsets import xy_from_df, panel13withoutRightBot from datasets.examples import get_13zach _, img_y = xy_from_df(get_13zach(), mod) img_y_top2, _ = panel13withoutRightBot(img_y) img_y_test = np.logical_or(img_y_top2, train_data.get_y_test()) self.val_datas = [{ 'name': '13_top2', 'y': img_y_top2 }, { 'name': '13_test', 'y': img_y_test }] return train_data def main_train(self, train_data, steps_per_epoch=None): if steps_per_epoch is None: steps_per_epoch = self.steps_per_epoch from main_general import get_training_data from preprocessing.image import get_flow # TODO train x_train, y_train, x_val, y_val = get_training_data(train_data) # Generator flow_tr = get_flow(x_train, y_train, w_patch=self.w_patch, w_ext_in=self.w_ext_in) flow_va = get_flow(x_val, y_val, w_patch=self.w_patch, w_ext_in=self.w_ext_in) epochs = 1 self.neural_net.train( flow_tr, validation=flow_va, epochs=epochs, steps_per_epoch=steps_per_epoch, info=f'{set_net["name"]}_d{self.d}_k{self.k}_n{self.n_per_class}') def main_eval( self, train_data, b_plot=False, ): x = train_data.get_x_test() y_pred = self.neural_net.predict(x) if b_plot: concurrent([x[..., :3], y_pred[..., 1]], ['input', 'prediction']) val_datas = [{'y': train_data.get_y_test()}] + self.val_datas return _eval_func(y_pred, val_datas, b_plot=b_plot)