如何使用在Keras中训练好的模型来预测输入图像?

53

我训练了一个模型来对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]]


4
еҰӮжһңжӮЁдҪҝз”ЁдәҶmodel.save()пјҢеҲҷдёҚеҝ…дҪҝз”Ёmodel.compile()гҖӮhttps://keras.io/getting-started/faq/#how-can-i-save-a-keras-model - Borealis
5个回答

42

如果有人仍然在努力预测图像,这里是优化后的代码,用于加载保存的模型并进行预测:

# Modify 'test1.jpg' and 'test2.jpg' to the images you want to predict on

from keras.models import load_model
from keras.preprocessing import image
import numpy as np

# dimensions of our images
img_width, img_height = 320, 240

# load the model we saved
model = load_model('model.h5')
model.compile(loss='binary_crossentropy',
              optimizer='rmsprop',
              metrics=['accuracy'])

# predicting images
img = image.load_img('test1.jpg', target_size=(img_width, img_height))
x = image.img_to_array(img)
x = np.expand_dims(x, axis=0)

images = np.vstack([x])
classes = model.predict_classes(images, batch_size=10)
print classes

# predicting multiple images at once
img = image.load_img('test2.jpg', target_size=(img_width, img_height))
y = image.img_to_array(img)
y = np.expand_dims(y, axis=0)

# pass the list of multiple images np.vstack()
images = np.vstack([x, y])
classes = model.predict_classes(images, batch_size=10)

# print the classes, the images belong to
print classes
print classes[0]
print classes[0][0]

5
我收到一条信息:'Model'对象没有属性'predict_classes'。请改用predict方法。 - Serġan
1
谢谢这个。这对我有用,但我有几个问题。1. 在这里,“y = np.expand_dims(y, axis=0)”这一行是在做什么?也许更深入地说,我能够在这种二进制方法中分类为0或1...但我不知道/在哪里设置了二进制分类结果(我的意思是,我可以告诉1是狗,0不是狗,但为什么不是1是猫,0不是猫?)。希望这个问题有些直观的意义。 - Rivers31334
1
嗨,在使用您的代码后,它显示为[[1]][[1][1]][1]1。如何将其转换为结果? - James
你是不是想打印(classes)? :) - hesam rajaei
为什么在预测中需要batch_size=10 - alex3465
显示剩余2条评论

22
您可以使用model.predict()来预测单个图像的类别,具体方法如下[doc]:
# load_model_sample.py
from keras.models import load_model
from keras.preprocessing import image
import matplotlib.pyplot as plt
import numpy as np
import os


def load_image(img_path, show=False):

    img = image.load_img(img_path, target_size=(150, 150))
    img_tensor = image.img_to_array(img)                    # (height, width, channels)
    img_tensor = np.expand_dims(img_tensor, axis=0)         # (1, height, width, channels), add a dimension because the model expects this shape: (batch_size, height, width, channels)
    img_tensor /= 255.                                      # imshow expects values in the range [0, 1]

    if show:
        plt.imshow(img_tensor[0])                           
        plt.axis('off')
        plt.show()

    return img_tensor


if __name__ == "__main__":

    # load model
    model = load_model("model_aug.h5")

    # image path
    img_path = '/media/data/dogscats/test1/3867.jpg'    # dog
    #img_path = '/media/data/dogscats/test1/19.jpg'      # cat

    # load a single image
    new_image = load_image(img_path)

    # check prediction
    pred = model.predict(new_image)
在这个例子中,一个图像被加载为一个形状为 (1, height, width, channels)numpy 数组。然后,我们将其加载到模型中并预测它的类别,返回一个实值在范围 [0, 1] 内(在本例中进行二元分类)。

19

keras predict_classes(文档) 输出一个numpy数组,包含了模型预测的类别。在你的模型中,这个数组中最大元素所对应的神经元索引就是最后一层(softmax层)的激活度最高的神经元索引。如果[[0]]是输出结果,那么你的模型预测测试数据属于第0个类别。(通常情况下,你会传入多张图片,输出结果将会像这样:[[0], [1], [1], [0]]

对于二分类问题,你需要将实际标签(例如'cancer', 'not cancer')转换为二进制编码(0表示'cancer',1表示'not cancer')。然后你可以将输出结果[[0]]解释为属于'cancer'这个类别。


1
img = np.reshape(img,[1,320,240,3]) 中,实际上你将变量 img 转换成了一个包含 1 张 320x240 的图像的数组。因此,如果要传递多个图像,你需要使用数组,类似于这样:images = [] for image_name in image_list: img = cv2.imread(image_name) img = cv2.resize(img,(320,240)) images.append(img) images = np.asarray(images)然后将 images 传递给 model.predict_classes - DNK
我好像明白了,谢谢! - ritiek
@mkto 我不是很确定,但我认为我在错误地加载图像。当我使用Keras内置的 load_imgimg_to_array 函数时,它可以正常工作。我添加了我的解决方案。请查看我在这个问题下给出的另一个答案。 - ritiek
@PreetomSahaArko 这里是完整的代码 https://github.com/ritiek/deep-learning-practise/blob/master/keras/image_prediction.ipynb 但它可能已经过时了。 - ritiek
1
@DNK 我该如何将我的标签(猫,狗,非猫,非狗)转换为二进制编码? - Ryan Fasching
显示剩余5条评论

14

那是因为您正在获取与类相关联的数字值。例如,如果您有两个类别猫和狗,Keras 将分别将它们关联数字 0 和 1。要获取您的类别及其相关联的数字值之间的映射,您可以使用

>>> classes = train_generator.class_indices    
>>> print(classes)
    {'cats': 0, 'dogs': 1}

现在你知道了类别和索引之间的映射关系。那么现在你可以这样做:

如果 classes[0][0] == 1: prediction = 'dog' 否则: prediction = 'cat'


2
很好的内容!但我认为你想说的是 train_generator.class_indices - ritiek

1
转发 @ritiek 的示例,我也是机器学习的初学者,也许这种格式能够帮助看到名称而不仅仅是类别编号。
images = np.vstack([x, y])

prediction = model.predict(images)

print(prediction)

i = 1

for things in prediction:  
    if(things == 0):
        print('%d.It is cancer'%(i))
    else:
        print('%d.Not cancer'%(i))
    i = i + 1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接