batch_size=32, class_mode='binary') model.fit( training_set, steps_per_epoch=70, epochs=1, validation_data=test_set, validation_steps=10) # In[15]: #Saving and loading the model model.save('face_recog_mobilenet.h5') from keras.models import load_model classifier = load_model('face_recog_mobilenet.h5') # In[26]: #Predicting Random Images using face recognization model import os import cv2 import numpy as np from os import listdir from os.path import isfile, join
model = MobileNet(input_shape=(128, 128, 3), include_top=False, pooling='avg') x = model.output x = Dense(512, activation="relu")(x) predict = Dense(1, activation="sigmoid")(x) model = Model(inputs=model.input, outputs=predict) adam = Adam(lr=0.0001) model.compile(optimizer=adam, loss="binary_crossentropy", metrics=["accuracy"]) model.summary() history = model.fit(data_train, epochs=10, validation_data=data_test, verbose=1) model.save("/Clasificador.h5") def visualizar_img_test(path, modelo): img = cv2.imread(path) img_1 = cv2.resize(img, (128, 128)) img = (img_1 / 255) img = np.expand_dims(img, axis=0) predict = modelo.predict(img) if predict[0][0] < 0.7: plt.title(str(100 - predict[0][0] * 100) + "% MASCARILLA") plt.imshow(img_1.astype("uint8")) plt.show() else: plt.title(str(predict[0][0] * 100) + "% NO TIENE MASCARILLA") plt.imshow(img_1.astype("uint8"))
model_path = os.path.join(save_dir, model_name) weight_path = os.path.join(save_dir, weight_name) x_train, y_train, x_test, y_test = image_crop.read_data() x_train_resized = image_crop.resize_imgs(x_train) y = to_categorical(y_train, num_classes=34) model = MobileNet(include_top=True, weights=None, classes=34, pooling='max', input_shape=(150, 150, 3)) checkpoint = ModelCheckpoint(filepath=os.path.join( save_dir, 'MobileNet_weight.{epoch:02d}-{loss:.2f}.hdf5'), verbose=1) opt = RMSprop(lr=2e-5) model.compile(optimizer=opt, loss=losses.categorical_crossentropy, metrics=[metrics.categorical_accuracy]) model.fit(x_train_resized, y, epochs=10, batch_size=36, callbacks=[checkpoint]) model.save(model_path) model.save_weights(weight_path)
model.summary() type(model) x = model.layers[-6].output predictions = Dense(29,activation='softmax')(x) model = Model(inputs = model.input, outputs=predictions) model.summary() for layer in model.layers[:-23]: layer.trainable = False model.compile(Adam(lr = 0.001),loss = 'categorical_crossentropy',metrics = ['accuracy']) model.fit_generator(train_batches, steps_per_epoch = 3627, validation_data = valid_batches, validation_steps = 723, epochs = 10, verbose = 2) model.save('sign_language.h5') ####### model build and saved upto here from keras.models import load_model class SignLanguageModel(): Signs = ["A", "B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z", "del", "nothing", "space"] def __init__(self): # load model from JSON file self.model = load_model("sign_language.h5")
target_size=(img_rows, img_cols), class_mode='categorical') validation_generator = validation_datagen.flow_from_directory( validation_data_dir, target_size=(img_rows, img_cols), class_mode='categorical') lr = 0.001 ep = 2 ol = train_generator.num_classes model = MobileNet(weights='imagenet', include_top=False, input_shape=(img_rows, img_cols, 3)) model.save('MobileNet.h5') for l in model.layers: l.trainable = False top_model = model.output top_model = Flatten()(top_model) top_model = Dense(512, activation='relu')(top_model) top_model = Dense(1024, activation='relu')(top_model) top_model = Dense(ol, activation='softmax')(top_model) nmodel = Model(inputs=model.input, outputs=top_model) nmodel.compile(loss='categorical_crossentropy', optimizer='adam',
from keras.callbacks import Callback from keras.models import Sequential mobilenet_input_shape = (1080, 1920, 3) """ Build a microclassifier (mobilenet -> microclassifier) """ # Load pre-trained mobilenet and set all layers to not be trainable print("Loading weights from 224x224 MobileNet...", end=" ", flush=True) mobilenet_base_model = MobileNet(input_shape=(224, 224, 3), include_top=False, weights='imagenet', input_tensor=None, pooling=None) print("Done.") print("Initializing {}x{} MobileNet...".format(*mobilenet_input_shape), end=" ", flush=True) mobilenet_reshaped_model = MobileNet(input_shape=mobilenet_input_shape, include_top=False, weights=None, input_tensor=None, pooling=None) print("Copying weights from 224x224 MobileNet...", end=" ", flush=True) for reshaped_layer, layer in zip(mobilenet_reshaped_model.layers, mobilenet_base_model.layers): reshaped_layer.set_weights(layer.get_weights()) print("Setting all MobileNet layers to be non-trainable...", flush=True) for layer in mobilenet_reshaped_model.layers: layer.trainable = False print("Done", flush=True) mobilenet_reshaped_model.save("mobilenet.h5")