Keras中CNN输入维度报错

Keras中CNN输入维度报错

2018/6/3

想要写分类器对图片进行分类,用到了CNN。然而,在运行程序时,一直报错:

ValueError: Negative dimension size caused by subtracting 5 from 1 for ‘conv2d_1/convolution’ (op: ‘Conv2D’) with input shapes: [?,1,28,28], [5,5,28,30].

这部分提到的代码是这样的,这是我的分类器的输入层:

model.add(Conv2D(30,(5, 5), input_shape=(1, 28, 28), activation='relu',padding="valid"))

问题出在input_shape上,报错的大意就是我的输入的维度是错误的。

百思不得其解,在Stackoverflow上找到了答案:

Keras的图片处理文档中给出:

dim_ordering: One of {“th”, “tf”}. “tf” mode means that the images should have shape (samples, height, width, channels), “th” mode means that the images should have shape (samples, channels, height, width). It defaults to the image_dim_ordering value found in your Keras config file at ~/.keras/keras.json. If you never set it, then it will be “tf”.

翻译过来意思就是:关于图片的维度顺序有两种类型,分别是“th”和”tf“,它们的差别如下:

图片维序类型为 th 时(dim_ordering='th'): 输入数据格式为[samples][channels][rows][cols];
# 图片维序类型为 tf 时(dim_ordering='tf'): 输入数据格式为[samples][rows][cols][channels];

在Keras里默认的是“tf”顺序,如果想要改为“th”顺序,需要手动在前面加上如下代码:

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

现在回头看我的输入维度顺序,显然是用了th的格式,

model.add(Conv2D(30,(5, 5), input_shape=(1, 28, 28), activation='relu',padding="valid"))

所以,程序一定会报错。
于是在建立模型前加入了前面提到的代码。

至此,该问题解决。

猜你喜欢

转载自blog.csdn.net/weixin_39986952/article/details/80556092
今日推荐