【问题标题】:number of input channels does not match corresponding dimension of filter in Keras输入通道数与 Keras 中过滤器的相应维度不匹配
【发布时间】:2017-08-27 21:33:31
【问题描述】:

我正在使用keras搭建基于Resnet50的模型,如下代码所示

input_crop = Input(shape=(3, 224, 224))

# extract feature from image crop
resnet = ResNet50(include_top=False, weights='imagenet')
for layer in resnet.layers:  # set resnet as non-trainable
    layer.trainable = False

crop_encoded = resnet(input_crop)  

但是,我遇到了一个错误

'ValueError: 输入通道数不匹配对应 过滤器尺寸,224 != 3'

我该如何解决?

【问题讨论】:

  • 您使用的是什么后端,您的 keras.json 文件的内容是什么?

标签: machine-learning neural-network keras deep-learning conv-neural-network


【解决方案1】:

由于 Theano 和 TensorFlow backends 用于 Keras 的图像格式不同,因此经常会产生此类错误。在您的情况下,图像显然是 channels_first 格式 (Theano),而您很可能使用的是 TensorFlow 后端,它需要 channels_last 格式的图像。

Keras 中的 MNIST CNN example 提供了一种很好的方法来使您的代码免受此类问题的影响,即同时适用于 Theano 和 TensorFlow 后端 - 这是针对您的数据的一种调整:

from keras import backend as K

img_rows, img_cols = 224, 224

if K.image_data_format() == 'channels_first':
    input_crop = input_crop.reshape(input_crop.shape[0], 3, img_rows, img_cols)
    input_shape = (3, img_rows, img_cols)
else:
    input_crop = input_crop.reshape(input_crop.shape[0], img_rows, img_cols, 3)
    input_shape = (img_rows, img_cols, 3)

input_crop = Input(shape=input_shape)

【讨论】:

  • 根据您的回答,input_crop 是什么,即使我将其定义为 input_crop = Input(shape=(3, img_width, img_height)),也会得到 AttributeError: 'Tensor' object has no attribute 'reshape'
  • @Laxmikant 检查链接的 MNIST 示例; input_cropx_trainx_test 那里)由 mnist.load_data Keras 函数返回 - 它是 Numpy 数组而不是张量
猜你喜欢
  • 2018-10-09
  • 2018-10-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-20
  • 2020-04-28
  • 1970-01-01
相关资源
最近更新 更多