How to use test_gendata method in avocado

Best Python code snippet using avocado_python

ResNet152.py

Source:ResNet152.py Github

copy

Full Screen

1import tensorflow as tf2from keras.applications.densenet import DenseNet1213from keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPool2D,GlobalAveragePooling2D4from keras.models import Sequential,Model,load_model5from tensorflow.python.client import device_lib6import numpy as np7from keras.models import Model8from keras.layers import Dense9from keras.applications import ResNet15210from sklearn.metrics import classification_report11import itertools12from keras_preprocessing.image import ImageDataGenerator13from sklearn.metrics import roc_curve, auc, roc_auc_score14import matplotlib.pyplot as plt15from keras import models16from keras import layers17from keras import optimizers18from keras.models import Model,load_model,Sequential19from keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPooling2D,GlobalAveragePooling2D,BatchNormalization,Activation20##### Pre Processing21from keras_preprocessing.image import ImageDataGenerator22train_gendata = []23valid_gendata = []24test_gendata = []25train_datagen2 = ImageDataGenerator(26 rescale=1. / 255,27 zoom_range=0.2,28 validation_split = 0.2)29model_path = "E://CN240//model//model5-{epoch:02d}-{val_accuracy:.4f}.h5"30train_gen = train_datagen2.flow_from_directory(31directory='C://Users//Admin//Desktop//Newtrain',32target_size=(224, 224),33shuffle = True,34color_mode="rgb",35batch_size=4,36class_mode="categorical",37subset = 'training')38train_gendata.append(train_gen)39 40valid_gen = train_datagen2.flow_from_directory(41directory='C://Users//Admin//Desktop//Newtrain',42target_size=(224, 224),43color_mode="rgb",44batch_size=4,45class_mode="categorical",46subset='validation')47valid_gendata.append(valid_gen)48 49test_gen = train_datagen2.flow_from_directory(50directory='C://Users//Admin//Desktop//testdata',51target_size=(224, 224),52color_mode="rgb",53batch_size=1,54class_mode=None)55test_gendata.append(test_gen)56##### Create ResNet152 Model57model = ResNet152(weights='imagenet',58 include_top=False,59 input_shape=(224, 224, 3))60x = model.output61x = GlobalAveragePooling2D()(x)62x = Dense(1024, activation='relu')(x)63x = Dropout(0.55)(x)64x = Dense(512, activation='relu')(x)65x = Dropout(0.55)(x)66predictions = Dense(3, activation= 'softmax')(x)67model_2 = Model(inputs = model.input, outputs = predictions)68model_2.compile(optimizer= 'adam', loss='categorical_crossentropy', metrics=['accuracy'])69##### Train Model70batch_size = 1671 72generator = train_gendata[0]73 74valid = valid_gendata[0]75test = test_gendata[0]76filepath="E://CN240//model_from_fold//model5-{epoch:02d}-{val_accuracy:.4f}.h5"77checkpoint = ModelCheckpoint(filepath, monitor= 'val_accuracy', verbose=1, save_best_only=False, mode='max')78callbacks_list = [checkpoint]79history = model_2.fit(80 generator,81 steps_per_epoch=generator.n/batch_size,82 epochs=30,83 validation_data=valid,84 validation_steps=valid.n/batch_size,85 shuffle=True,86 verbose=1,87 callbacks = callbacks_list)88 89model_2.evaluate_generator(generator=valid,steps=valid.n)90test_gendata[0].reset()91 92import json93from keras.models import model_from_json, load_model94with open('E://CN240//model//model5_architecture.json', 'w') as f:95 f.write(model_2.to_json())96print("Saved model to disk")97##### Ploting Model-Loss Graph98# list all data in history99print(history.history.keys())100# summarize history for accuracy101plt.plot(history.history['accuracy'])102plt.plot(history.history['val_accuracy'])103plt.title('Model Accuracy')104plt.ylabel('Accuracy')105plt.xlabel('Epoch')106plt.legend(['Train', 'Test'], loc='upper left')107plt.show()108# summarize history for loss109plt.plot(history.history['loss'])110plt.plot(history.history['val_loss'])111plt.title('Model Loss')112plt.ylabel('Loss')113plt.xlabel('Epoch')114plt.legend(['Train', 'Test'], loc='upper left')115plt.show()116##### Printing Report117x_labels = test.classes118y_labels = predicted_class_indices119print(classification_report(y_labels, x_labels))120##### Ploting Confusion Matrix121def plot_confusion_matrix(cm, classes, 122 normalize=False,123 title = 'Confusion Matrix',124 cmap=plt.cm.Blues):125 126 plt.imshow(cm, interpolation = 'nearest', cmap=cmap)127 plt.title(title)128 plt.colorbar()129 tick_marks = np.arange(len(classes))130 plt.xticks(tick_marks, classes, rotation = 45)131 plt.yticks(tick_marks, classes)132 133 if normalize:134 cm = cm.astype('float') / cm.sum(axis=1) [:, np.newaxis]135 print("Normalized Confusion Matrix")136 else:137 print("Confusion Matrix without normalization")138 139 print(cm)140 141 thresh = cm.max() / 2.142 143 for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):144 plt.text(j,i, cm[i,j],145 horizontalalignment ="center",146 color = "white" if cm[i,j] > thresh else "black")147 plt.tight_layout()148 plt.ylabel('True label')149 plt.xlabel('Predicted label')150cm = confusion_matrix(x_labels, y_labels)151cm_plot_labels = ['Glaucoma','Normal','Others']...

Full Screen

Full Screen

test.py

Source:test.py Github

copy

Full Screen

1import hashlib2import certifi3import urllib4import os5from pymongo import MongoClient6from pymongo.errors import ConnectionFailure7from PIL import Image8import unittest9from main import decode10from main import validate_password11from main import genData12class Testing(unittest.TestCase):13 def test_validate_password(self):14 self.assertEqual(validate_password(''), 0)15 self.assertEqual(validate_password('Abc123'), 0)16 self.assertEqual(validate_password('Abc123Abc123Abc123Abc123'), 0)17 self.assertEqual(validate_password('AAAAAAAA'), 1)18 self.assertEqual(validate_password('AAAAbbbbc'), 1)19 self.assertEqual(validate_password('123456789'), 2)20 self.assertEqual(validate_password('AAAA12345'), 2)21 self.assertEqual(validate_password('aaaa12345'), 3)22 self.assertEqual(validate_password('5we13aaaa12345'), 3)23 self.assertEqual(validate_password('AAAaaaa12345'), -1)24 self.assertEqual(validate_password('kjs36adfjIS230Rcv5D'), -1)25 26 def test_decode(self):27 script_dir = os.path.dirname(__file__)28 rel_path = '../../test.png'29 abs_img_path = os.path.join(script_dir, rel_path)30 image_to_decode = Image.open(abs_img_path)31 self.assertEqual(decode(image_to_decode, ''), False)32 self.assertEqual(decode(image_to_decode, 'osdfjlj32'), False)33 self.assertEqual(decode(image_to_decode, 'Abcd1234'), False)34 35 password = hashlib.sha256('Abcd1234'.encode()).hexdigest()36 self.assertEqual(decode(image_to_decode, password), 'xyz')37 38 def test_genData(self):39 self.assertEqual(genData("1234"), ['00110001', '00110010', '00110011', '00110100'])40 self.assertEqual(genData("abcd"), ['01100001', '01100010', '01100011', '01100100'])41 self.assertEqual(genData("QWER"), ['01010001', '01010111', '01000101', '01010010'])42 self.assertEqual(genData("!@#$"), ['00100001', '01000000', '00100011', '00100100'])43 self.assertEqual(genData("[];',./"), ['01011011', '01011101', '00111011', '00100111', '00101100', '00101110', '00101111'])44 def test_isConnected(self):45 conn = MongoClient(46 "mongodb+srv://LijuanZhuge:" + urllib.parse.quote(47 "US-65&sR@P5A#@F") + "@cluster0.botulzy.mongodb.net/?retryWrites=true&w=majority", tlsCAFile=certifi.where())48 try:49 conn.finalproject.command('ismaster')50 except ConnectionFailure:51 print("Server not available")52if __name__ == '__main__':...

Full Screen

Full Screen

test_gendata.py

Source:test_gendata.py Github

copy

Full Screen

2from pydantic import parse_file_as3from validate_cloud_optimized_geotiff import validate4from loopy.run_image import run_image5from loopy.sample import Sample6def test_gendata():7 out = Path("testout")8 run_image(9 Path("sample.tif"),10 out,11 scale=0.497e-6,12 channels=",".join(["Lipofuscin", "DAPI", "GFAP", "NeuN", "OLIG2", "TMEM119"]),13 )14 out = out / "sample"15 assert (out / "sample_1.tif").exists()16 assert (out / "sample_2.tif").exists()17 assert not validate((out / "sample_1.tif").as_posix(), full_check=True)[0] # No errors18 assert not validate((out / "sample_2.tif").as_posix(), full_check=True)[0]...

Full Screen

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run avocado automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful