如何使用 Keras 中训练有素的模型预测输入图像?
我才刚开始接触 Keras 和机器学习。
我训练了一个模型来对 2 个类别的图像进行分类,并使用 model.save()
保存了它。以下是我使用的代码:
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
# dimensions of our images.
img_width, img_height = 320, 240
train_data_dir = 'data/train'
validation_data_dir = 'data/validation'
nb_train_samples = 200 #total
nb_validation_samples = 10 # total
epochs = 6
batch_size = 10
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, (3, 3), input_shape=input_shape))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Conv2D(32, (3, 3)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Conv2D(64, (3, 3)))
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'])
# this is the augmentation configuration we will use for training
train_datagen = ImageDataGenerator(
rescale=1. / 255,
shear_range=0.2,
zoom_range=0.2,
horizontal_flip=True)
# this is the augmentation configuration we will use for testing:
# only rescaling
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=5)
model.save('model.h5')
训练成功,准确率为 0.98,相当不错。为了在新图像上加载和测试该模型,我使用了下面的代码:
from keras.models import load_model
import cv2
import numpy as np
model = load_model('model.h5')
model.compile(loss='binary_crossentropy',
optimizer='rmsprop',
metrics=['accuracy'])
img = cv2.imread('test.jpg')
img = cv2.resize(img,(320,240))
img = np.reshape(img,[1,320,240,3])
classes = model.predict_classes(img)
print classes
它的输出结果是
[[0]]
为什么它不给出类的实际名称,为什么是"[[0]]"?
在此先表示感谢。
35
3
如果有人还在为预测图像而苦恼,下面是加载已保存模型并进行预测的优化代码:
keras predict_classes (docs) 输出一个类预测的 numpy 数组。在你的模型中,它是最后(softmax)层中激活度最高的神经元的索引。[[0]]
表示你的模型预测测试数据是 0 类(通常你会传入多个图像,结果会像
[[0],1,1,[0]]`)。您必须将实际标签(例如,"'癌症','不是癌症')转换为二进制编码("0 "表示'癌症',"1 "表示'不是癌症'),以便进行二进制分类。然后,您将把输出为
[[0]]
的序列解释为具有类别标签'癌症'
。您可以使用
model.predict()
来预测单张图像的类别,如下所示 [doc]:在此示例中,图像以形状为"(1, height, width, channels) "的
numpy
数组加载。然后,我们将其加载到模型中,并预测其类别,预测结果以 [0, 1] 范围内的实数值返回(本例中为二元分类)。