无法短语Keras预测输出



我正在尝试使用keras创建一个图像分类项目。但我一直在理解训练模型的输出。我有三节课,我想找到最可能的一节课。

这是列车代码:

# Importing all necessary libraries
from keras.preprocessing.image import ImageDataGenerator
from keras.models import Sequential
from keras.layers import Conv2D, MaxPooling2D
from keras.layers import Activation, Dropout, Flatten, Dense
from keras import backend as K

img_width, img_height = 250, 250
train_data_dir = 'Data/Wheat/Train'
validation_data_dir = 'Data/Wheat/Test'
nb_train_samples =2545
nb_validation_samples = 737
epochs = 10
batch_size = 16
if K.image_data_format() == 'channels_first':
input_shape = (3, img_width, img_height)
else:
input_shape = (img_width, img_height, 3)
model = Sequential()
model.add(Conv2D(32, (2, 2), input_shape=input_shape))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Conv2D(32, (2, 2)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Conv2D(64, (2, 2)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Flatten())
model.add(Dense(64))
model.add(Activation('relu'))
model.add(Dropout(0.5))
model.add(Dense(1))
model.add(Activation('sigmoid'))
model.compile(loss='binary_crossentropy',
optimizer='rmsprop',
metrics=['accuracy'])
from PIL import ImageFile
ImageFile.LOAD_TRUNCATED_IMAGES = True

train_datagen = ImageDataGenerator(
rescale=1. / 255,
shear_range=0.2,
zoom_range=0.2,
horizontal_flip=True)
test_datagen = ImageDataGenerator(rescale=1. / 255)
train_generator = train_datagen.flow_from_directory(
train_data_dir,
target_size=(img_width, img_height),
batch_size=batch_size,
class_mode='binary')
validation_generator = test_datagen.flow_from_directory(
validation_data_dir,
target_size=(img_width, img_height),
batch_size=batch_size,
class_mode='binary')
model.fit_generator(
train_generator,
steps_per_epoch=nb_train_samples // batch_size,
epochs=epochs,
validation_data=validation_generator,
validation_steps=nb_validation_samples // batch_size)
model.save('Data/Wheat_model.h5')

我的预测代码是:

from keras.models import load_model
from keras.preprocessing.image import load_img
from keras.preprocessing.image import img_to_array
from keras.applications.vgg16 import preprocess_input
from keras.applications.vgg16 import decode_predictions
from keras.applications.vgg16 import VGG16
import numpy as np
from keras.models import load_model
model = load_model('/content/Data/Wheat_model.h5')
image = load_img('/content/Data/Wheat/1/001.jpg', target_size=(250, 250))
img = np.array(image)
img = img / 255.0
img = img.reshape(1,250,250,3)
label = model.predict(img)
print("Predicted Class: ", label)

我得到了下面的输出和我试图预测的所有图像。

Predicted Class:  [[1.]]

这个1是什么意思??我只想要预测的课。

您需要修改您的代码。你说你有3个类,所以你的模型的顶层应该是

model.add(Dense(3))
model.add(Activation('softmax'))

在生成器中,将class_mode更改为

class_mode='categorical'

将您的模型编译代码更改为

from tensorflow.keras.optimizers import Adam
model.compile(Adam(learning_rate=.001), loss='categorical_crossentropy', metrics=['accuracy']) 

现在,当你在一张图像上建模、预测时,预测将产生3个概率输出,每个类一个。你需要找到一个具有最高概率的

# classes is a list of the 3 classes
classes=list(train_generator.class_indices.keys())
pred=model.predict(img)
print ('the shape of prediction is ', pred.shape)
# this dataset has 3 classes so model.predict will return a list of 3 probability values
# we want to find the index of the column that has the highest probability
index=np.argmax(pred[0])
# to get the actual Name of the class use 
klass=classes[index]
# lets get the value of the highest probability
probability=pred[0][index]*100
# print out the class, and the probability 
print(f'the image is predicted as being {klass} with a probability of {probability:6.2f} %')

这样就可以了。

最新更新