I am trying to use a pretained CNN (VGG16) but I keep getting the following error:
ValueError: Error when checking input: expected input_2 to have shape (224, 224, 3) but got array with shape (244, 244, 3)
Here is my full code:
import numpy as np
import keras
from keras import backend as K
from keras.models import Sequential
from keras.layers import Activation
from keras.layers.core import Dense, Flatten
from keras.optimizers import Adam
from keras.metrics import categorical_crossentropy
from keras.preprocessing.image import ImageDataGenerator
from keras.layers.normalization import BatchNormalization
from keras.layers.convolutional import *
train_path = "/DATA/train"
valid_path = "/DATA/valid"
test_path = "/DATA/test"
#creating the training, testing, and validation sets
trainBatches = ImageDataGenerator().flow_from_directory(train_path, target_size=(244,244), classes=['classU', 'classH'], batch_size=20)
valBatches = ImageDataGenerator().flow_from_directory(valid_path, target_size=(244,244), classes=['classU', 'classH'], batch_size=2)
testBatches = ImageDataGenerator().flow_from_directory(test_path, target_size=(244,244), classes=['classU', 'classH'], batch_size=2)
#loading the model & removing the top layer
model = Sequential()
for layer in vgg16_model.layers[:-1]:
model.add(layer)
#Fixing the weights
for layer in model.layers:
layer.trainable = False
#adding the new classier
model.add(Dense(2, activation = 'softmax'))
model.compile(Adam(lr=0.0001), loss='categorical_crossentropy', metrics=['accuracy'])
model.fit_generator(trainBatches, steps_per_epoch=89, validation_data=valBatches, validation_steps=11, epochs=5, verbose=2)
But I don't know what I am getting the error. I thought ImageDataGenerator() will take care of the data/batches generation with the correct dimensions. What I am missing?
The VGG model in this case expects images to be of (224, 224)
whereas your image generator targets are (244, 244)
hence your input shapes get a mismatch. You should adjust the target size to the expected shape. The documentation details the expected inputs and it also has an option include_top
that will remove the last layer for you so you don't have to do it manually.