ValueError:检查输入时出错:预期input_2具有形状(224,224,3),但数组具有形状(244,244,3)

时间:2018-11-17 20:14:04

标签: python keras deep-learning conv-neural-network transfer-learning

我正在尝试使用自带的CNN(VGG16),但始终出现以下错误:

ValueError: Error when checking input: expected input_2 to have shape (224, 224, 3) but got array with shape (244, 244, 3)

这是我的完整代码:

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)

但是我不知道我得到了什么错误。我认为ImageDataGenerator()将以正确的尺寸处理数据/批处理。我缺少什么?

1 个答案:

答案 0 :(得分:0)

在这种情况下,VGG模型期望图像为(224, 224),而您的图像生成器目标为(244, 244),因此您的输入形状不匹配。您应该将目标尺寸调整为预期的形状。 documentation详细说明了预期的输入,并且还有一个选项include_top,它将为您删除最后一层,因此您不必手动进行操作。