【问题标题】:Keras convolution shape has dimensions out of order (Error when checking model input)Keras 卷积形状的尺寸无序(检查模型输入时出错)
【发布时间】:2017-01-17 23:28:25
【问题描述】:

我已经检查了所有类似的帖子,但我的错误没有通过建议的修复得到修复。提前感谢您的帮助!

我在 Keras 中使用 tensorflow 后端,我的图像尺寸为 1185 x 676。大部分代码来自 Keras 示例之一。

我收到ValueError: Negative dimension size caused by subtracting 2 from 1 for 'MaxPool' (op: 'MaxPool') with input shapes: [?,1,1183,32]. 当我切换到 dim_ordering="th" 时,这个错误消失了,考虑到我使用的是 tensorflow,而不是 theano,这很奇怪。

到目前为止的代码:

img_width, img_height = 1185, 676

train_data_dir = 'data/train'
validation_data_dir = 'data/validation'
nb_train_samples = 32
nb_validation_samples = 8
nb_epoch = 3

model = Sequential()
model.add(Convolution2D(32, 3, 3, input_shape=(3, img_width, img_height)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2), dim_ordering="tf"))

以防万一数据生成是问题的一部分:

model.compile(loss='binary_crossentropy',
              optimizer='rmsprop',
              metrics=['accuracy'])

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,
        batch_size=4,
        target_size=(img_width, img_height),
        class_mode='binary')

validation_generator = test_datagen.flow_from_directory(
        validation_data_dir,
        batch_size=4,
        target_size=(img_width, img_height),
        class_mode='binary')

model.fit_generator(
        train_generator,
        samples_per_epoch=nb_train_samples,
        nb_epoch=nb_epoch,
        validation_data=validation_generator,
        nb_val_samples=nb_validation_samples)

【问题讨论】:

  • 更新:看起来尺寸不能被池大小整除。现在我收到ValueError: Negative dimension size caused by subtracting 3 from 1 for 'Conv2D' (op: 'Conv2D') with input shapes: [?,1,1185,676], [3,3,676,32].
  • 更新:修复了池大小。现在,在拟合期间:ValueError: Error when checking model input: expected convolution2d_input_1 to have shape (None, 3, 1185, 676) but got array with shape (2, 1185, 676, 3)
  • 您的输入形状与 image_ordering = "tf" 不一致,为什么要强制仅在一层中排序图像?
  • 啊!!!我不敢相信我没有早点看到——这正是问题所在。谢谢!

标签: python-2.7 machine-learning tensorflow deep-learning keras


【解决方案1】:

您的代码中混合了图像尺寸顺序。解决此问题的多种方法。

一种方法是添加

from keras import backend as K
K.set_image_dim_ordering('tf')

在代码的开头。

其他方法总结in this answer

【讨论】:

  • 谢谢!我会投票支持你的回应,但我还没有足够的声誉来投票。
  • 没问题,只要有帮助。
猜你喜欢
  • 1970-01-01
  • 2020-06-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-15
  • 1970-01-01
  • 2018-01-24
  • 1970-01-01
相关资源
最近更新 更多