【问题标题】:ValueError: Error when checking input: expected input_2 to have shape (224, 224, 3) but got array with shape (244, 244, 3)ValueError:检查输入时出错:预期 input_2 的形状为 (224, 224, 3) 但得到的数组的形状为 (244, 244, 3)
【发布时间】:2019-04-20 15:54:58
【问题描述】:

我正在尝试使用预保留的 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() 将处理具有正确尺寸的数据/批次生成。我错过了什么?

【问题讨论】:

  • 您给 imagedatagenerator 提供了错误的大小,因为 224 与 244 不同。

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


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2020-01-11
    • 2021-02-12
    • 2019-11-21
    • 1970-01-01
    • 1970-01-01
    • 2019-09-03
    • 2022-06-15
    • 1970-01-01
    • 2020-05-12
    相关资源
    最近更新 更多