[英]Keras model.predict Error when checking input: expected conv2d_input to have 4 dimensions, but got array with shape (128, 56)
I used a DirectoryIterator
to read images from a directory and train my model. 我使用
DirectoryIterator
从DirectoryIterator
中读取图像并训练我的模型。 I want to be able to verify that it works so I tried using model.predict
on a numpy array that contains an image but I get the following error 我想能够验证它是否有效,所以我尝试在包含图像的numpy数组上使用
model.predict
,但出现以下错误
ValueError: Error when checking input: expected conv2d_input to have 4
dimensions, but got array with shape (128, 56)
I'm not sure what kind of shape or attributes the DirectoryIteratory
from flow_from_directory
has so I'm not sure what kind of input model.predict
is expecting. 我不确定
flow_from_directory
的DirectoryIteratory
具有什么样的形状或属性,所以我不确定期望的输入model.predict
是哪种。 This is what my code looks like 这就是我的代码
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)
From your code snippet it seems that you're using this blog post. 从您的代码片段来看,您似乎正在使用此博客文章。 So your ConvNet's first layer is a convolutional layer, expecting the input shape to be
(150, 150)
. 因此,您的ConvNet的第一层是卷积层,期望输入形状为
(150, 150)
。 Let's look at your error message: 让我们看看您的错误消息:
ValueError : Error when checking input: expected conv2d_input to have 4 dimensions, but got array with shape (128, 56)
ValueError :检查输入时出错:预期conv2d_input具有4个维,但数组的形状为(128,56)
The error says two things: 该错误说明两件事:
So first, your numpy array shape should be in the shape of (150, 150)
(because of your ConvNet's input shape), and you should expand the dimensions of your image to have 4 dimensions. 因此,首先,您的numpy数组形状应为
(150, 150)
形状(由于ConvNet的输入形状),并且应将图像的尺寸扩展为4个尺寸。 For example (assuming your numpy array to be x
): 例如(假设您的numpy数组是
x
):
x = x.reshape(1,150,150,3).astype('float')
x /= 255
pred = model.predict(x)
If you're reading the image from your hard disk, you could use the following code: 如果要从硬盘读取图像,则可以使用以下代码:
img = keras.preprocessing.image('image.jpg', target_size=(150,150))
x = keras.preprocessing.image.img_to_array(img)
x = x.reshape(1,150,150,3).astype('float')
x /= 255
pred = model.predict(x)
Hope it helps. 希望能帮助到你。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.