tensorflow - 密集层 Keras 中的输出维度
问题描述
我有以下模型的样本
from tensorflow.keras import models
from tensorflow.keras import layers
sample_model = models.Sequential()
sample_model.add(layers.Dense(32, input_shape=(4,)))
sample_model.add(layers.Dense(16, input_shape = (44,)))
sample_model.compile(loss="binary_crossentropy",
optimizer="adam", metrics = ["accuracy"])
模型IP:
sam_x = np.random.rand(10,4)
sam_y = np.array([0,1,1,0,1,0,0,1,0,1,])
sample_model.fit(sam_x,sam_y)
混淆是fit
应该抛出一个错误,shape mismatch
因为expected_input_shape
for the2nd Dense Layer
是给定的,(None,44)
但是output
for the 1st Dense Layer
(这是 的输入2nd Dense Layer
)将是 shape (None,32)
。但它运行成功。
我不明白为什么没有错误。任何澄清都会有所帮助
解决方案
input_shape
关键字参数仅对 a 的第一层有效Sequential
。其他层的输入形状将来自它们的前一层。
这种行为在以下文档中有所暗示tf.keras.layers.InputShape
:
当使用带有 Keras Sequential 模型的 InputLayer 时,可以通过将 input_shape 参数移动到 InputLayer 之后的第一层来跳过它。
并在顺序模型指南中。
可以通过查看Sequential.add
方法的来源来确认该行为:
if not self._layers:
if isinstance(layer, input_layer.InputLayer):
# Case where the user passes an Input or InputLayer layer via `add`.
set_inputs = True
else:
batch_shape, dtype = training_utils.get_input_shape_and_dtype(layer)
if batch_shape:
# Instantiate an input layer.
x = input_layer.Input(
batch_shape=batch_shape, dtype=dtype, name=layer.name + '_input')
# This will build the current layer
# and create the node connecting the current layer
# to the input layer we just created.
layer(x)
set_inputs = True
如果模型中还没有层,则将使用Input
从模型的第一层派生的形状添加到模型中。仅当模型中尚不存在任何层时才执行此操作。
该形状要么是完全已知的(如果input_shape
已传递到模型的第一层),要么在模型构建后将是完全已知的(例如,调用model.build(input_shape)
)。
推荐阅读
- python-3.x - AWS:Lambda函数无法使用EC2实例的私有API调用rest api
- record - 为什么记录规则没有按预期运行 Odoo 10?
- node.js - 在 TypeScript 中使用共享项目
- excel - 在 Google 表格中每行只计算一次字符串的出现次数
- javascript - 所选选项值的 jquery 验证警报
- http - X-frame-options 和 Allow-access-control-origin 标头的组合
- angular - 运行混合角度应用程序时出错
- javascript - ecmascript6 扩展运算符对于 javascript 对象没有按预期工作
- sql - 是否可以通过 REST API 从 Metabase MBQL / SQL 查询中获取原始数据?
- php - aes-128-cbc 的 openssl_decrypt 不起作用