在Squential列表里边可以有选择性的写input_shape参数,下面介绍介绍几种写法,任选其一即可,选择自己习惯的常用。
- (1) 当我们选择在第一层声明input_shape时,有以下几种写法
- 这种写法会让模型从一开始就有网络参数,并随着网络深度的增加,后面会自动地随机初始化对应shape地权重
## 写法1
model = Sequential()
model.add(Dense(32, input_shape=(500,)))
## 写法2
model = Sequential()
model.add(Dense(32, input_dim=500))
## 写法3
model = Sequential()
model.add(Dense(32, batch_input_shape=(None, 500)))
## 写法4
model = Squential([
Dense(32,input_shape//input_dim//batch_input_shape=(500,)//500//(None,500))
])
- (2) 当我们选择在第一层不声明input_shape时,有以下几种写法
- In that case the model gets built the first time you call
fit
(or other
training and evaluation methods) - 模型会通过fit函数或者其他训练或者评估地过程来构建网络,言外之意就是就要给了数据,我就可以构建网络了
model = Sequential()
model.add(Dense(32))
model.add(Dense(32))
model.weights # empty[]
model.compile(optimizer=optimizer, loss=loss)
# This builds the model for the first time:
model.fit(x, y, batch_size=32, epochs=10)
# Alternative way,we just give data to model
data = tf.ones(shape=(3,3))
out = model(data) # 调用Model类地call函数进行前向传播
model.weights # not empty[weights values]
# Another way :通过调用build函数进行手工构建build(batch_input_shape)
model = Sequential()
model.add(Dense(32))
model.add(Dense(32))
model.build((None, 500)) # None表示batch_size,可以表示为任意地维度,等待接收。
model.weights # returns list of length 4
写在后面
了解神经网络地输入的shape非常重要,如果不了解清楚我们的data的shape和神经网络的shape是否相配,会导致网络的混乱。还有很重要一点要搞清楚参数是否包含batch_size的大小!
要注意两个参数的不同:
①input_shape:不包含batch_size
②batch_input_shape:包含batch_size,在一般情况下,都写成None。当然,在非常具体的情况下可以写为具体的数字。