这表明所有训练示例都具有固定的序列长度,即timesteps
。
这不是很正确,因为该尺寸可以是None
,即可变长度。在一个批处理中,您必须具有相同数量的时间步长(通常在这里看到0填充和掩码)。但是在批次之间没有这种限制。在推断期间,您可以有任何长度。
创建随机时间长度批次的训练数据的示例代码。
from keras.models import Sequential
from keras.layers import LSTM, Dense, TimeDistributed
from keras.utils import to_categorical
import numpy as np
model = Sequential()
model.add(LSTM(32, return_sequences=True, input_shape=(None, 5)))
model.add(LSTM(8, return_sequences=True))
model.add(TimeDistributed(Dense(2, activation='sigmoid')))
print(model.summary(90))
model.compile(loss='categorical_crossentropy',
optimizer='adam')
def train_generator():
while True:
sequence_length = np.random.randint(10, 100)
x_train = np.random.random((1000, sequence_length, 5))
# y_train will depend on past 5 timesteps of x
y_train = x_train[:, :, 0]
for i in range(1, 5):
y_train[:, i:] += x_train[:, :-i, i]
y_train = to_categorical(y_train > 2.5)
yield x_train, y_train
model.fit_generator(train_generator(), steps_per_epoch=30, epochs=10, verbose=1)
这就是它的打印内容。请注意,输出形状(None, None, x)
指示可变的批次大小和可变的时间步长大小。
__________________________________________________________________________________________
Layer (type) Output Shape Param #
==========================================================================================
lstm_1 (LSTM) (None, None, 32) 4864
__________________________________________________________________________________________
lstm_2 (LSTM) (None, None, 8) 1312
__________________________________________________________________________________________
time_distributed_1 (TimeDistributed) (None, None, 2) 18
==========================================================================================
Total params: 6,194
Trainable params: 6,194
Non-trainable params: 0
__________________________________________________________________________________________
Epoch 1/10
30/30 [==============================] - 6s 201ms/step - loss: 0.6913
Epoch 2/10
30/30 [==============================] - 4s 137ms/step - loss: 0.6738
...
Epoch 9/10
30/30 [==============================] - 4s 136ms/step - loss: 0.1643
Epoch 10/10
30/30 [==============================] - 4s 142ms/step - loss: 0.1441
Masking
图层设置为可忽略