我认为使用 LSTM 可以使用任意长度的序列作为输入,但每个时间步的形状都是固定的,但我遇到了异常行为。
以下代码给出了我预期的错误,因为输入形状与 LSTM 模型上定义的形状不同:
import numpy as np
from keras.models import Sequential
from keras.layers import Dense, LSTM
model = Sequential()
model.add(LSTM(50, input_shape=(None, 15), return_sequences=True))
model.add(Dense(1, activation='linear'))
N_start = 16
inputs = np.zeros((1000, 50, N_start))
model.predict(inputs)
错误是:
ValueError: Input 0 of layer "sequential" is incompatible with the layer: expected shape=(None, None, 15), found shape=(None, 50, 16)
但是,如果我使用以下代码,模型甚至可以在不同的形状下工作:
import numpy as np
from keras.models import Sequential
from keras.layers import Dense, LSTM
model = Sequential()
model.add(LSTM(50, input_shape=(None, 15), return_sequences=True))
model.add(Dense(1, activation='linear'))
N_start = 14
inputs = np.zeros((1000, 50, N_start))
add = np.ones((1000, 50, 1))
for i in range(10):
inputs = np.concatenate((inputs,add), axis = 2)
print(np.shape(inputs))
model.predict(inputs)
输出是
(1000, 50, 15) 2023-05-17 10:46:19.392818: I tensorflow/compiler/xla/stream_executor/cuda/cuda_dnn.cc:428] Loaded cuDNN version 8401 32/32 [==============================] - 2s 6ms/step (1000, 50, 16) 32/32 [==============================] - 0s 6ms/step (1000, 50, 17) 32/32 [==============================] - 0s 6ms/step
我不明白为什么它适用于最后一个维度不同于 15 的输入。