Reputation: 85
I used a DirectoryIterator
to read images from a directory and train my model. 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
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. 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)
Upvotes: 0
Views: 1873
Reputation: 714
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)
. 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)
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. For example (assuming your numpy array to be 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.
Upvotes: 1