简体   繁体   中英

How to make a prediction on this trained model?

I am new to machine learning and I found this transfer learning model online, may seem like a trivial question but how do I make predictions with a single image on it? I'm not very familiar with the code as of now but my trained model seems to work fine(I'm using google colab).

import pandas as pd
import numpy as np
import os
import keras
import matplotlib.pyplot as plt
from keras.layers import Dense,GlobalAveragePooling2D
from keras.applications import MobileNet
from keras.preprocessing import image
from keras.applications.mobilenet import preprocess_input
from keras.preprocessing.image import ImageDataGenerator
from keras.models import Model
from keras.optimizers import Adam

base_model=MobileNet(weights='imagenet',include_top=False) #imports the mobilenet model and discards the last 1000 neuron layer.

x=base_model.output
x=GlobalAveragePooling2D()(x)
x=Dense(1024,activation='relu')(x) #we add dense layers so that the model can learn more complex functions and classify for better results.
x=Dense(1024,activation='relu')(x) #dense layer 2
x=Dense(512,activation='relu')(x) #dense layer 3
preds=Dense(4,activation='softmax')(x) #final layer with softmax activation

model=Model(inputs=base_model.input,outputs=preds)
#specify the inputs
#specify the outputs
#now a model has been created based on our architecture

for layer in model.layers[:20]:
    layer.trainable=False
for layer in model.layers[20:]:
    layer.trainable=True

from zipfile import ZipFile
file_name = 'thecar.zip'

with ZipFile(file_name, 'r') as zip:
  zip.extractall()
  print('Done')

train_datagen=ImageDataGenerator(preprocessing_function=preprocess_input) #included in our dependencies

train_generator=train_datagen.flow_from_directory('thecar', # this is where you specify the path to the main data folder
                                                 target_size=(224,224),
                                                 color_mode='rgb',
                                                 batch_size=5,
                                                 class_mode='categorical',
                                                 shuffle=True)


model.compile(optimizer='Adam',loss='categorical_crossentropy',metrics=['accuracy'])
# Adam optimizer
# loss function will be categorical cross entropy
# evaluation metric will be accuracy

step_size_train=train_generator.n//train_generator.batch_size
model.fit_generator(generator=train_generator,
                   steps_per_epoch=step_size_train,
                   epochs=5)

As you trained your model on a mini-batch of 5 you have to take that into account when making the predictions on a single image. You just have to change the image to the following shape: [1, image_width, image_height, number_of_channels] which is done by using np.expand_dims() .

import numpy as np
from keras.preprocessing import image


img = image.load_img(PATH_TO_IMAGE, target_size = (224, 224))
img = image.img_to_array(img)
img = np.expand_dims(img, axis = 0)

model.predict(img)

This may be a bit of an extension to your question. If you still have your model available then of course you do not have to load it, Further if you only have 1 image you can just define the path to the single image. In the code below I covered the case where you saved your model and are now using it to predict on one or more images. Place one or more images that you want to predict in a directory. Then execute code below

import tensorflow as tf
from tensorflow import keras
from tensorflow.keras.models import  load_model
import numpy as np
import cv2
import os
model_location =r'c:\temp\people\Mobilenet-99.00.h5' # location of the saved model
model=load_model(model_location) # load the saved model
image_location=r'c:\temp\people\storage' # directory storing the images that you want to predict
file_list=os.listdir(image_location)  # list of files
for f in file_list: # iterate through the files in the directory list
    f_path=os.path.join(image_location, f)  # create the path to the image file
    img=cv2.imread(f_path)    # read in the image - note cv2 reads in images in BGR format
    img=cv2.cvtColor(img, cv2.COLOR_BGR2RGB) # model was trained on RGB images so convert to RGB
    img=cv2.resize(img, (128,128)) # model was trained on images of size 128  X 128 X 3 so resize the images
    img=img/127.5-1 # model was trained with pixel value scalled between -1 to +1 so convert the pixel range    
    img=np.expand_dims(img, axis=0) # model predict expects the input to have dimension (batch_size, width, height, bands)
    #print (img.shape)  # uncomment to see effect of expanding dimension
    prediction =model.predict (img, batch_size=1, verbose=0) # make predictions    
    pred=np.argmax(prediction)# find the index of the column with the highest probability
    print ('for file ', f_path, ' the index of the predicted class is ', pred, ' with a probability of ', prediction[0][pred]  )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM