python - 为什么给定输入的 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())
解决方案
您需要添加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())
推荐阅读
- node.js - 使用 Bull.js 通过在重复规则中提供时间来安排可重复的作业
- gradle - 如有必要,在自动部署时更新 gradle 版本
- javascript - 如何使用打字稿定义文件中的枚举?
- apache-spark - 激发有效分布配对以比较群组
- c# - Xamarin.Forms 中的 Objective-C 绑定
- excel - 自动登录不会输入凭据 - 提示错误
- python - Django - 可以在失败时重试任何数据库操作?
- python - 在图像上绘制霍夫变换线
- ruby-on-rails - 如何解析 json response.body 以将键的值存储在 ruby on rails 中?
- python - 在 selenium python 中处理多个窗口