Keras卷积2D输入:检查模型输入时出错:预期convolution2d_input_1具有形状

8
我正在学习使用Keras创建图像分类器的教程,链接如下:https://blog.keras.io/building-powerful-image-classification-models-using-very-little-data.html。训练模型后,我将其保存到文件中,并在下面的测试脚本中重新加载到模型中。
当我使用一张以前从未见过的图片对模型进行评估时,出现以下异常:
错误:
Traceback (most recent call last):
  File "test_classifier.py", line 48, in <module>
    score = model.evaluate(x, y, batch_size=16)
  File "/Library/Python/2.7/site-packages/keras/models.py", line 655, in evaluate
    sample_weight=sample_weight)
  File "/Library/Python/2.7/site-packages/keras/engine/training.py", line 1131, in evaluate
    batch_size=batch_size)
  File "/Library/Python/2.7/site-packages/keras/engine/training.py", line 959, in _standardize_user_data
exception_prefix='model input')
  File "/Library/Python/2.7/site-packages/keras/engine/training.py", line 108, in standardize_input_data
str(array.shape))
Exception: Error when checking model input: expected convolution2d_input_1 to have shape (None, 3, 150, 150) but got array with shape (1, 3, 150, 198)`

问题出在我训练的模型上还是在我调用评估方法时有问题?

代码:

    from keras.preprocessing.image import ImageDataGenerator
    from keras.models import Sequential
    from keras.layers import Convolution2D, MaxPooling2D
    from keras.layers import Activation, Dropout, Flatten, Dense
    from keras.preprocessing.image import ImageDataGenerator, array_to_img, img_to_array, load_img

    import numpy as np
    img_width, img_height = 150, 150
    train_data_dir = 'data/train'
    validation_data_dir = 'data/validation'
    nb_train_samples = 2000
    nb_validation_samples = 800
    nb_epoch = 5
    model = Sequential()
    model.add(Convolution2D(32, 3, 3, input_shape=(3, img_width, img_height)))
    model.add(Activation('relu'))
    model.add(MaxPooling2D(pool_size=(2, 2)))
    model.add(Convolution2D(32, 3, 3))
    model.add(Activation('relu'))
    model.add(MaxPooling2D(pool_size=(2, 2)))
    model.add(Convolution2D(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'])
    model.load_weights('first_try.h5')
    img = load_img('data/test2/ferrari.jpeg')
    x = img_to_array(img)  # this is a Numpy array with shape (3, 150, 150)
    x = x.reshape( (1,) + x.shape )  # this is a Numpy array with shape (1, 3, 150, 150)
    y = np.array([0])
    score = model.evaluate(x, y, batch_size=16)`

你已经做了注释:x = img_to_array(img) # 这是一个形状为 (3, 150, 150) 的Numpy数组 x = x.reshape( (1,) + x.shape ) # 这是一个形状为 (1, 3, 150, 150) 的Numpy数组但是错误信息说的不一样。这并不是一个完整的答案,但是为了调试,请尝试在评估模型之前输出你的输入形状。 - user6684101
谢谢。这很有帮助。我已经将图像编辑为150 x 150,但是预览自动调整了高度以与宽度比例相适应;因此,这就是198的来源。 - JessicaOwensby
3个回答

5

这个问题是由于测试图片的尺寸不正确导致的。对我来说,

train_datagen.flow_from_directory(
        'C:\\Users\\...\\train',  # this is the target directory
        target_size=(150, 150),  # all images will be resized to 150x150
        batch_size=32,
        class_mode='binary')

之前出现了一些问题,测试图片无法正常工作。因此我使用了一个matlab命令来调整所有的测试图片大小,结果很好。


1
问题有两个方面:
  1. 测试图像的尺寸不正确,应该是150 x 150,而不是150 x 198。

  2. 我必须将密集层从model.add(Dense(10))更改为model.add(Dense(1))

我还不理解如何让模型给出预测结果,但至少现在,模型评估已经运行了。


您可以接受自己的答案作为已解决来展示问题已经得到解决。 - Håken Lid

0
我遇到了同样的问题,然后使用了这个函数: 将目标文件夹中的所有图像(.jpg和.png)都重新调整大小到指定的高度和宽度,并除以255。此外,还需要增加一个额外的维度(所需的输入形状)。
from scipy import misc
import os

def readImagesAsNumpyArrays(targetPath, i_height, i_width):
    files = os.listdir(targetPath)
    npList = list()
    for file in files:
        if ".jpg" or ".png" in str(file):
            path = os.path.join(targetPath, file)
            img = misc.imread(path)
            img = misc.imresize(img, (i_height, i_width))
            img = img * (1. / 255)
            img = img[None, :, :,: ]
            npList.append(img)
    return npList

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