Best Python code snippet using avocado_python
predictions.py
Source:predictions.py
1from sklearn.metrics import confusion_matrix, classification_report2from main_func.BertTraining import batch_size3from aux_func.data_preprocess import Preprocessor4import numpy as np5from aux_func.confussion_matrix import plot_confusion_matrix6import tensorflow as tf7import os8# print(tf.version)9from aux_func.load_model import load_model10gpus = tf.config.experimental.list_physical_devices('GPU')11if gpus:12 try:13 # Currently, memory growth needs to be the same across GPUs14 for gpu in gpus:15 tf.config.experimental.set_memory_growth(gpu, True)16 except RuntimeError as e:17 # Memory growth must be set before GPUs have been initialized18 print(e)19def test_model(model_path, conjunto, patient, prueba=1, combination='mean', mode=0):20 """21 Función que prueba el modelo especificado.22 Esta funcion genera los reportes de clasificacion y matrices de confusion tanto para23 los eegs completos como para los fragmentos. Ademas si el modelo es por zonas tambien genera24 los valores para estas.25 :param model_path: ruta del modelo (La carpeta donde se almacena el modelo)26 :param conjunto: número del 0 al 4: 'test', 'train', 'val', 'full', 'test_pre_post'27 :param patient: número del -1 al 2: All, control, pre, post28 :param prueba: prueba del dataset:29 -1: "Both",30 0: "FTD",31 1: "FTI",32 2: "Resting"33 :param combination: 'mean' o 'majority_voting' para la combinación de los resultados en el34 modelo de zonas35 :param mode: 0: full y chunks, 1 full, 2 chunks36 :return: nada37 """38 # out_shape = [window_width, 64]39 model = load_model(model_path)40 conjuntos = ['test', 'train', 'val', 'full', 'test_pre_post']41 patients = ['control', 'pre', 'post', 'Pre-Post']42 pruebas = {-1: "Both",43 0: "FTD",44 1: "FTI",45 2: "Resting"}46 base_path = f'{conjuntos[conjunto]}_{patients[patient]}_{pruebas[prueba]}'47 zones = False48 if 'Zone' in model_path:49 base_path = f'{base_path}_{combination}'50 zones = True51 print(f'{base_path}')52 channels = []53 if model.input_shape[2] == 25:54 channels = [9, 10, 11, 12, 13, 19, 20, 21, 22, 23, 29, 30, 31, 32, 33, 39, 40, 41, 42, 43, 49, 50, 51, 52, 53]55 out_shape = list(model.input_shape[1:])56 test_post = False57 if conjunto == 4:58 test_post = True59 prepro = Preprocessor(batch_size,60 model.input_shape[1],61 64,62 prueba=prueba,63 limpio=0,64 paciente=patient,65 channels=channels,66 transpose=True,67 output_shape=out_shape,68 test_post=test_post,69 shuffle=False)70 try:71 os.mkdir(f'{model_path}/{base_path}')72 except Exception:73 pass74 if mode != 2:75 try:76 os.mkdir(f'{model_path}/{base_path}/full_eeg')77 except Exception:78 pass79 if conjunto == 0 or conjunto == 4:80 data = prepro.test_set81 if conjunto == 1:82 data = prepro.train_set83 if conjunto == 2:84 data = prepro.val_set85 if conjunto == 3:86 data = prepro.dataset87 y_pred = []88 y_pred_zones = [[] for _ in range(8)]89 for x_data, y_data in zip(data[0], data[1]):90 test_dataset = prepro.tf_from_generator([x_data], [y_data])91 pred = model.predict(test_dataset, verbose=1)92 if zones:93 pred, zone_pred = pred94 for i, zone in enumerate(np.swapaxes(zone_pred, 0, 1)):95 y_pred_zones[i].append(np.argmax(np.asarray(np.mean(zone, axis=0))))96 try:97 os.mkdir(f'{model_path}/{base_path}/chunks/zones')98 os.mkdir(f'{model_path}/{base_path}/full_eeg/zones')99 except Exception:100 pass101 if combination == 'majority_voting':102 max_pred_total = np.bincount(np.array(y_pred_zones)[:, -1]).argmax()103 else:104 max_pred_total = np.mean(np.array(y_pred_zones), axis=1).argmax()105 y_pred.append(max_pred_total)106 else:107 y_pred.append(np.mean(pred, axis=0))108 # FULL EEGS FIRST109 if not zones or combination == 'mean':110 y_pred = np.argmax(np.asarray(y_pred), axis=1)111 cf_matrix = confusion_matrix(data[1], y_pred)112 with open(f'{model_path}/{base_path}/full_eeg/classification_report.txt',113 'w') as f:114 print(classification_report(data[1], y_pred, labels=[0, 1], target_names=["No Parkinson", "Parkinson"]), file=f)115 print(cf_matrix)116 plot_confusion_matrix(cm=cf_matrix,117 normalize=False,118 target_names=["No Parkinson", "Parkinson"],119 title="Matriz de confusión",120 save=f'{model_path}/{base_path}/full_eeg/test_eeg.png')121 if y_pred_zones[0]:122 for i, y_pred in enumerate(y_pred_zones):123 cf_matrix = confusion_matrix(data[1], y_pred)124 print(cf_matrix)125 plot_confusion_matrix(cm=cf_matrix,126 normalize=False,127 target_names=["No Parkinson", "Parkinson"],128 title="Matriz de confusión",129 save=f'{model_path}/{base_path}/full_eeg/zones/test_confussion_zone_{i + 1}_matrix.png')130 # CHUNKS NOW131 if mode != 1:132 try:133 os.mkdir(f'{model_path}/{base_path}/chunks')134 except Exception:135 pass136 full, train, test, val = prepro.classification_generator_dataset()137 dataset, train_dataset, test_dataset, val_dataset = prepro.classification_tensorflow_dataset()138 if conjunto == 0 or conjunto == 4:139 _, y_data = zip(*list(test))140 data_dataset = test_dataset141 if conjunto == 1:142 _, y_data = zip(*list(train))143 data_dataset = train_dataset144 if conjunto == 2:145 _, y_data = zip(*list(val))146 data_dataset = val_dataset147 if conjunto == 3:148 _, y_data = zip(*list(full))149 data_dataset = dataset150 y_data = list(y_data)151 print("Chunks")152 y_pred = model.predict(data_dataset, verbose=1)153 y_pred_zones = []154 if len(y_pred) == 2:155 y_pred, y_pred_zones = y_pred156 y_pred_zones = np.argmax(np.swapaxes(y_pred_zones, 0, 1), axis=2)157 y_pred = np.argmax(y_pred, axis=1)158 cf_matrix = confusion_matrix(y_data, y_pred)159 with open(f'{model_path}/{base_path}/chunks/classification_report.txt',160 'w') as f:161 print(classification_report(y_data, y_pred, labels=[0, 1], target_names=["No Parkinson", "Parkinson"]), file=f)162 print(cf_matrix)163 plot_confusion_matrix(cm=cf_matrix,164 normalize=False,165 target_names=["No Parkinson", "Parkinson"],166 title="Matriz de confusión",167 save=f'{model_path}/{base_path}/chunks/test_eeg.png')168 if y_pred_zones != []:169 for i, y_pred in enumerate(y_pred_zones):170 cf_matrix = confusion_matrix(y_data, y_pred)171 print(cf_matrix)172 plot_confusion_matrix(cm=cf_matrix,173 normalize=False,174 target_names=["No Parkinson", "Parkinson"],175 title="Matriz de confusión",176 save=f'{model_path}/{base_path}/chunks/zones/test_confussion_zone_{i + 1}_matrix.png')177if __name__ == "__main__":178 model_paths = [#"C:/Users/Ceiec01/OneDrive - UFV/PFG/Codigo/checkpoints/BERT-ControlesPre-CanalesReducidos",179 #"C:/Users/Ceiec01/OneDrive - UFV/PFG/Codigo/checkpoints/BERT-HigherDropout-64",180 "C:/Users/Ceiec01/OneDrive - UFV/PFG/Codigo/checkpoints/BERT-Zones-Final"181 ]182 for model_path in model_paths:183 for conjunto in range(3):184 print(f'{model_path} - {conjunto}')185 test_model(model_path, conjunto, 1)186 print(f'{model_path} - post')...
test_simple.py
Source:test_simple.py
...8 s = pd.Series([1, 2, 3, 4, 5], index=[1, 2, 3, 4, 5])9 obtained = s.context(3, around=2)10 expected = pd.Series([1, 2, 3, 4, 5], index=[1, 2, 3, 4, 5])11 pd.testing.assert_series_equal(obtained, expected)12def test_pre_post():13 s = pd.Series([1, 2, 3, 4, 5], index=[1, 2, 3, 4, 5])14 obtained = s.context(3, pre=2, post=1)15 expected = pd.Series([1, 2, 3, 4], index=[1, 2, 3, 4])...
test_tn.py
Source:test_tn.py
1from lcpy import TreeNode, build_root2def test_pre_post():3 l = [1,2,3,4,5,6,7]4 root = build_root(l)5 # print(root.post)6 assert root.pre == [1,2,4,5,3,6,7]...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!