为什么对于给定的输入,在Keras中的简单CNN网络出现错误

时间:2019-01-08 23:39:25

标签: python tensorflow keras

我在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())

1 个答案:

答案 0 :(得分:0)

您需要在数据中添加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())