通过指定维度,您可以确保模型接收固定长度的输入。
从技术上讲,您可以将None 放在您想要的任何输入维度上。形状将在运行时推断。
您只需要确保指定层参数(input_dim、output_dim)、kernel_size(用于 conv 层)、units(用于 FC 层)。
如果您使用Input 并指定将通过网络传递的张量形状,则可以计算形状。
例如以下模型是完全有效的:
from tensorflow.keras import layers
from tensorflow.keras import models
ip = layers.Input((10))
emb = layers.Embedding(10, 2)(ip)
flat = layers.Flatten()(emb)
out = layers.Dense(5)(flat)
model = models.Model(ip, out)
model.summary()
Model: "model"
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
input_2 (InputLayer) [(None, 10)] 0
_________________________________________________________________
embedding (Embedding) (None, 10, 2) 20
_________________________________________________________________
flatten (Flatten) (None, 20) 0
_________________________________________________________________
dense (Dense) (None, 5) 105
=================================================================
Total params: 125
Trainable params: 125
Non-trainable params: 0
这里,我没有指定 input_length,但它是从Input 层推断出来的。
问题在于 Sequential API,如果您没有在输入层和嵌入层中指定输入形状,则无法使用正确的参数集构建模型。
例如,
from tensorflow.keras import layers
from tensorflow.keras import models
model = models.Sequential()
model.add(layers.Embedding(10, 2, input_length = 10)) # will be an error if I don't specify input_length here as there is no way to know the shape of the next layers without knowing the length
model.add(layers.Flatten())
model.add(layers.Dense(5))
model.summary()
本例中必须指定input_length,否则模型会报错。