def predict_class(img_path): # prepare image for classification using keras utility functions image = load_img(img_path, target_size=target_size) image_arr = img_to_array(image) # convert from PIL Image to NumPy array image_arr /= 255 # to be able to pass it through the network and use batches, we want it with shape (1, 224, 224, 3) image_arr = np.expand_dims(image_arr, axis=0) # print(image.shape) # build the VGG16 network model = applications.VGG16(include_top=False, weights='imagenet') # get the bottleneck prediction from the pre-trained VGG16 model bottleneck_features = model.predict(image_arr) # build top model model = create_top_model("softmax", bottleneck_features.shape[1:]) model.load_weights("res/_top_model_weights.h5") predicted = model.predict(bottleneck_features) # predicted_onehot = to_categorical(predicted, num_classes=num_classes) return np.asarray(predicted[0]) # float32
batch_size=batch_size, class_mode='categorical', shuffle=False) # data is ordered num_val_samples = len(val_generator.filenames) # load vgg features val_data = np.load('res/vgg_val_features.npy') val_labels = val_generator.classes val_labels_onehot = to_categorical(val_labels, num_classes=num_classes) # ---------- CREATE AND TRAIN MODEL ---------- # create the top model to be trained model = create_top_model("softmax", train_data.shape[1:]) model.compile(optimizer="rmsprop", loss="categorical_crossentropy", metrics=["accuracy"]) # only save the best weights. if the accuracy doesnt improve in 2 epochs, stop. checkpoint_callback = ModelCheckpoint( "res/top_model_weights.h5", # store weights with this file name monitor='val_accuracy', verbose=1, save_best_only=True, mode='max') early_stop_callback = EarlyStopping( monitor='val_accuracy', patience=2, # max number of epochs to wait mode='max')
'../../../dataset/split_data/test/', target_size=target_size, batch_size=batch_size, class_mode='categorical', # specify categorical shuffle=False) # data is ordered # load vgg features test_data = np.load('res/vgg_test_features.npy') test_labels = test_generator.classes # actual class number test_labels_onehot = to_categorical( test_labels, num_classes=num_classes) # class number in onehot # ---------- TEST MODEL ---------- model = create_top_model("softmax", test_data.shape[1:]) model.load_weights("res/_top_model_weights.h5") model.compile(optimizer="rmsprop", loss="categorical_crossentropy", metrics=["accuracy"]) predicted = model.predict_classes(test_data) # ---------- DISPLAY INFORMATION DEPENDING ON COMMAND LINE FLAGS ---------- if args.acc: loss, acc = model.evaluate(test_data, test_labels_onehot, batch_size=batch_size, verbose=1)
from keras.preprocessing.image import load_img, img_to_array from helper import create_top_model, class_labels, target_size, num_classes import numpy as np from keras import applications import operator import matplotlib.pyplot as plt from keras.utils.np_utils import to_categorical import os # iterate through all testing images data_path = 'imgs/test' csv_header = ['img','c0','c1','c2','c3','c4','c5','c6','c7','c8','c9'] all_entries = [] model = applications.VGG16(include_top=False, weights='imagenet') model_top = create_top_model("softmax", (7,7,512)) model_top.load_weights("res/top_model_weights_final.h5") def predict_class(img_path): image = load_img(img_path, target_size=target_size) image_arr = img_to_array(image) # convert from PIL Image to NumPy array image_arr /= 255 image_arr = np.expand_dims(image_arr, axis=0) predicted = model_top.predict(bottleneck_features) # predicted_onehot = to_categorical(predicted, num_classes=num_classes) return np.asarray(predicted[0]) # float32 for i, file in enumerate(os.listdir(data_path)): file_name = os.fsdecode(file)
image_arr = img_to_array( image) # convert from PIL Image to NumPy array image_arr /= 255 # to be able to pass it through the network and use batches, we want it with shape (1, 224, 224, 3) image_arr = np.expand_dims(image_arr, axis=0) # print(image.shape) # build the VGG16 network model = applications.VGG16(include_top=False, weights='imagenet') # get the bottleneck prediction from the pre-trained VGG16 model bottleneck_features = model.predict(image_arr) # build top model model = create_top_model("softmax", bottleneck_features.shape[1:]) model.load_weights("res/top_model_weights.h5") predicted = model.predict(bottleneck_features) decoded_predictions = dict(zip(class_labels, predicted[0])) decoded_predictions = sorted(decoded_predictions.items(), key=operator.itemgetter(1), reverse=True) print() x_coor = 5 y_coor = 10 count = 1 for key, value in decoded_predictions[:5]: