Keras ValueError:输入0与图层conv2d_1不兼容:预期ndim = 4,发现ndim = 5

Luc*_*ky 15 python deep-learning conv-neural-network keras tensorflow

我检查了所有解决方案,但我仍面临同样的错误.我的训练图像形状是(26721,32,32,1),我相信它是4维,但我不知道为什么错误显示它是5维.

 model = Sequential()

 model.add(Convolution2D(16, 5, 5, border_mode='same', input_shape= input_shape ))
Run Code Online (Sandbox Code Playgroud)

所以这就是我定义model.fit_generator的方法

(26721, 32, 32, 1)

有人可以帮我这个吗?

Dan*_*ler 24

问题是input_shape.

它实际上应该只包含3个维度.内部keras将添加批量维度4.

由于您可能使用input_shape了4个维度(包括批处理),因此keras正在添加第5个维度.

你应该用input_shape=(32,32,1).

  • 不,那个号码是免费的。例如,Keras 会在 `model.summry()` 中将该维度显示为 `None`。 (2认同)
  • 我的训练数据维度是数组:`(26721, 32, 32)` 并且有效。维度是`(6680,32,32)`。现在我明确定义了图像大小 (32,32,1) ,然后它给了我错误 `ValueError: Error when checks input: expected conv2d_9_input to have 4维,but got array with shape (6680, 32, 32)`。我也在帖子中编辑了 model_fit.generator,你能检查一下吗? (2认同)
  • 现在问题在于您的数据.你的数据缺少`channel`维度:`x_validation = x_validation.reshape(6680,32,32,1)` (2认同)
  • 非常感谢您的帮助 (2认同)

小智 5

问题在于input_shape. 尝试添加额外的维度/通道,让 keras 知道您正在处理灰度图像,即 -->1

input_shape= (56,56,1). 可能如果您使用的是普通的深度学习模型,那么它不会引发问题,但对于 Convnet 来说却是。


小智 5

为了重塑数据,我们需要添加第四维,即从(6000,28,28)(6000,28,28,1)

我的代码是:

img_rows=x_train[0].shape[0]
img_cols=x_test[0].shape[1]

X_train=x_train.reshape(x_train.shape[0],img_rows,img_cols,1)

X_test=x_test.reshape(x_test.shape[0],img_rows,img_cols,1)


Input_shape=(img_rows,img_cols,**).  *->  I forgot to put 1 here.
Run Code Online (Sandbox Code Playgroud)

我遇到了同样的问题

Input 0 is incompatible with layer conv2d_4 : except ndim=4 ,found ndim=3

我通过简单地在输入形状中放置值来解决这个问题

Input_shape=(img_rows,img_cols,1)#store the shape of single image.
Run Code Online (Sandbox Code Playgroud)

有了这个问题就解决了