检查模型输入时出错:预期卷积2d_input_1有4个维度,但得到的形状为数组(32,32,3)

use*_*212 42 deep-learning keras keras-layer

我想从以下层开始训练深度网络:

model = Sequential()
model.add(Conv2D(32, 3, 3, input_shape=(32, 32, 3)))
Run Code Online (Sandbox Code Playgroud)

运用

history = model.fit_generator(get_training_data(),
                samples_per_epoch=1, nb_epoch=1,nb_val_samples=5,
                verbose=1,validation_data=get_validation_data()
Run Code Online (Sandbox Code Playgroud)

使用以下生成器:

def get_training_data(self):
     while 1:
        for i in range(1,5):
            image = self.X_train[i]
            label = self.Y_train[i]
            yield (image,label)
Run Code Online (Sandbox Code Playgroud)

(验证生成器看起来类似).

在培训期间,我收到错误:

Error when checking model input: expected convolution2d_input_1 to have 4 
dimensions, but got array with shape (32, 32, 3)
Run Code Online (Sandbox Code Playgroud)

怎么可能,第一层

 model.add(Conv2D(32, 3, 3, input_shape=(32, 32, 3)))
Run Code Online (Sandbox Code Playgroud)

gin*_*nge 39

您定义的输入形状是单个样本的形状.模型本身需要一些样本数组作为输入(即使它是一个长度为1的数组).

你的输出真的应该是4-d,第一维用于枚举样本.即对于单个图像,您应该返回(1,32,32,3)的形状.

你可以找到更多的信息在这里下的"Convolution2D" /"输入型"

  • 使用`image = np.expand_dims(image,axis = 0))`来添加额外的维度 (21认同)
  • 更改输入大小会导致错误更改为"输入0与图层conv2d_1不兼容:预期ndim = 4,找到ndim = 5".有人帮忙吗? (19认同)

Ish*_*sal 6

就像添加一维一样简单,所以我正在阅读 Siraj Rawal 在 CNN 代码部署教程中讲授的教程,它在他的终端上运行,但相同的代码在我的终端上不起作用,所以我做了一些研究关于它并解决了,我不知道这是否适合你们所有人。在这里,我想出了解决方案;

未解决的代码行会给您带来问题:

if K.image_data_format() == 'channels_first':
    x_train = x_train.reshape(x_train.shape[0], 1, img_rows, img_cols)
    x_test = x_test.reshape(x_test.shape[0], 1, img_rows, img_cols)
    print(x_train.shape)
    input_shape = (1, img_rows, img_cols)
else:
    x_train = x_train.reshape(x_train.shape[0], img_rows, img_cols)
    x_test = x_test.reshape(x_test.shape[0], img_rows, img_cols)
    input_shape = (img_rows, img_cols, 1)
Run Code Online (Sandbox Code Playgroud)

解决代码:

if K.image_data_format() == 'channels_first':
    x_train = x_train.reshape(x_train.shape[0], 1, img_rows, img_cols)
    x_test = x_test.reshape(x_test.shape[0], 1, img_rows, img_cols)
    print(x_train.shape)
    input_shape = (1, img_rows, img_cols)
else:
    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, 1)
Run Code Online (Sandbox Code Playgroud)

如果这对您有用,请在此处分享反馈。