ValueError: Error when checking input: expected conv2d_1_input to have 4 dimensions, but got array with shape

时间:2022-12-29 19:42:52

在进行mnist识别时,https://www.charleychai.com/blogs/2018/ai/NN/lenet.html中,

X_train = X_train.reshape(-1, 28, 28, 1)
X_test = X_test.reshape(-1, 28, 28, 1)

为什么要设置最后一维为1呢?

可以查看Conv2D中对input_shape的说明,https://keras.io/layers/convolutional/

Input shape

4D tensor with shape: (batch, channels, rows, cols) if data_format is "channels_first" or 4D tensor with shape: (batch, rows, cols, channels) if data_format is "channels_last".

对于代码中,-1是指batch,共有多少个样本,28分别指rows和cols,最后一个是指通道数,由于不是RGB,所以是1。