[英]predicting class of perticular image after training CNN using keras
Training训练
import keras
import numpy as np
import matplotlib.pyplot as plt
from keras.preprocessing.image import ImageDataGenerator
datagen= ImageDataGenerator(rotation_range=40,width_shift_range=0.2
,height_shift_range=0.2,zoom_range=0.2,rescale=1./255.)
type(datagen)
from keras.models import Sequential
from keras.layers import Conv2D,MaxPool2D,Flatten,Dense,Activation
from keras.activations import relu , softmax
from keras.losses import categorical_crossentropy
from keras.optimizers import SGD,RMSprop
from keras.callbacks import TensorBoard
model=Sequential()
model.add(Conv2D(32,(3,3),input_shape=(150,150,3),activation="relu"))
model.add(MaxPool2D(pool_size=(2,2)))
model.add(Conv2D(32,(3,3),activation="relu"))
model.add(MaxPool2D(pool_size=(2,2)))
model.add(Conv2D(64,(3,3),activation="relu"))
model.add(MaxPool2D(pool_size=(2,2)))
model.add(Flatten())
model.add(Dense(1024,activation="relu"))
model.add(Dense(512,activation="relu"))
model.add(Dense(512,activation="relu"))
model.add(Dense(512,activation="relu"))
model.add(Dense(512,activation="relu"))
model.add(Dense(512,activation="relu"))
model.add(Dense(5,activation="softmax"))
model.compile(loss="categorical_crossentropy" , optimizer=SGD(),metrics=["acc"])
train_gen=datagen.flow_from_directory("/home/vishu//Desktop/basics/dataset",target_size=
(150,150),batch_size=100)
tb=TensorBoard(log_dir=".")
model_history=model.fit_generator(train_gen,epochs=2)
Prediction预言
import cv2
CATEGORIES = ['1','2','3','4','5']
def prepare(filepath):
IMG_SIZE = 150
img_array = cv2.imread(filepath, cv2.IMREAD_COLOR)
new_array = cv2.resize(img_array, (IMG_SIZE, IMG_SIZE))
return new_array.reshape(-1, IMG_SIZE, IMG_SIZE, 3)
prediction = model.predict_classes([prepare('/home/vishu/Desktop/basics/dataset/d2.jpeg')])
print(prediction)
after using this it always gives me output 4使用它后,它总是给我输出 4
how should I predict the correct class of image?我应该如何预测正确的图像类别?
here I am taking input images from folders I have created 5 folders for 5 classes then how should I predict the class of an image?在这里,我从文件夹中获取输入图像,我为 5 个类创建了 5 个文件夹,那么我应该如何预测图像的类?
您忘记了在 ImageDataGenerator 中进行的重新缩放(除以 255),这需要使用新的测试数据来完成,因此您必须在prepare
功能中执行此操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.