简体   繁体   中英

How to predict with single images in keras

**i have used the below code for generating data **

train_gen = image.ImageDataGenerator(
rescale = 1.0/255,              # rescaling image from 0-255 to 0-1
rotation_range = 40,            # 40 degree of random rotation
zoom_range = 0.3,             # not using zoom as zooming might make  classification difficult
horizontal_flip = True,
vertical_flip=True
)
val_gen = image.ImageDataGenerator(rescale=1.0/255)  #just rescaling on test data

batch_size = 32
train_generator = train_gen.flow_from_directory(
train_directory,                 # training data directory
target_size = (100, 100),        # target size of the images which will be fed into the model
batch_size = batch_size,         # no. of images send for 1 epoch to the model
class_mode = "categorical",      # as there are 131 classes 
)
val_generator = val_gen.flow_from_directory(
test_directory,                  # test data directory
target_size = (100, 100),
batch_size = batch_size,
class_mode = "categorical",
)

**and trained the model using below code and got 97% accuracy on validation data **

model.fit_generator(train_generator,epochs = 7,validation_data= val_generator,verbose=2)

*after training when i predict for 1 img the prediction is totally wrong. can any 1 help me with this problem** code used to predict is below

import numpy as np
from tensorflow.keras.applications.resnet50 import preprocess_input, decode_predictions
from tensorflow.keras.preprocessing import image
img_path = 'fruits/Test/Watermelon/125_100.jpg'
img = image.load_img(img_path, target_size=(100, 100))
x = image.img_to_array(img)
x = np.expand_dims(x, axis=0)
x = preprocess_input(x)
model.predict(x)[0].argmax(axis=1)

plz help me with a working predict function..... link to the whole code enter link description here

That one image that you add, should be of the same distribution as of your training set. It also depends whether the image you used for prediction contains the watermelon in which part of the image. If you have not overfit validation set, I'd recommend to get the picture you want to predict in 100*100(square image) and the image to be in the center. Getting the image in center will help in improving predictions.

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