Keras中图像维度介绍

报错问题:

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,32].

问题分析:

定位:x_train = x_train.reshape(x_train.shape[0],1, 28,28).astype('float32')

分析:input_shape()输入维度错误,tensorflow默认为channels_last数据格式[samples][rows][cols][channels]

解决方法:

方法1:backend=theano

第一步:如想要输入数据格式为(channels,rows,cols),则文件开始位置添加下列模块

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

第二步:更改代码

x_train = x_train.reshape(x_train.shape[0],1,28,28).astype('float32')

方法2:backend=tensorflow

第一步:如想要输入数据格式为(rows,cols,channels),则文件开始位置添加下列模块

from keras import backend as K
K.image_data_format() == "channels_last"

第二步:更改代码

x_train = x_train.reshape(x_train.shape[0], 28,28,1).astype('float32')

总结:

最新Keras版本中图片格式如下:

进入keras路径 C:\Users\Mr.King\.keras(红色为你自己的用户名),查看keras.json文件,我的如下,这说明它默认维度类型为tf,即输入数据格式为[samples][rows][cols][channels];

{
    "floatx": "float32",
    "epsilon": 1e-07,
    "backend": "tensorflow",
    "image_data_format": "channels_last"
}

keras中图片维度类型分为'tf'和'th' :

backend为tensorflow时,keras.json中image_data_format为channels_last;

backend为theano时,keras.json中image_data_format为channels_first;

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

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