首页 > 解决方案 > 为什么给定输入的 Keras 中的简单 CNN 网络会出错

问题描述

我在 Keras 中定义了一个简单的两层卷积网络。当只输入一个样本输入来检查每个卷积层的张量大小和值时,为什么会出现这个错误?

Error when checking input: expected input_1 to have 4 dimensions, but got array with shape (1, 4, 4)

下面是简单的代码:


    from keras.layers import Input, Dense, Conv2D, MaxPooling2D, UpSampling2D
    from keras.models import Model
    from keras import backend as K
    import numpy as np

    input_img = Input(shape=(4, 4, 1))  
    # adapt this if using channels_first image data format

    x = Conv2D(2, (2, 2), activation='relu')(input_img)
    y = Conv2D(3, (2, 2), activation='relu')(x)
    model = Model(input_img, y)
    # cnv_ml_1 = Model(input_img, x)

    data = np.array([[[5, 12, 1, 8], [2, 10, 3, 6], [4, 7, 9, 1], [5, 7, 5, 6]]])
    # data = data.reshape(4, 4, 1)
    # print(data)
    print(model.predict(data))
    print(model.summary())

标签: pythontensorflowkeras

解决方案


您需要添加batch_size数据。在示例中,当您重塑数据时,您忘记定义batch_size. 这是解决此问题的简单解决方案:

import numpy as np
from tensorflow.python.keras import Model, Input
from tensorflow.python.keras.layers import Conv2D

input_img = Input(shape=(4, 4, 1))
# adapt this if using channels_first image data format

x = Conv2D(2, (2, 2), activation='relu', data_format='channels_last')(input_img)
y = Conv2D(3, (2, 2), activation='relu', data_format='channels_last')(x)
model = Model(input_img, y)
cnv_ml_1 = Model(input_img, x)

data = np.array([[[5, 12, 1, 8], [2, 10, 3, 6], [4, 7, 9, 1], [5, 7, 5, 6]]])
data = data.reshape(1, 4, 4, 1) # assume batch size is 1
print(data)
print(model.predict(data))
print(model.summary())

推荐阅读