首页 > 解决方案 > 对 LSTM 形状的质疑

问题描述

我看到很多人对 LSTM 有同样的问题,所以我想提出这个问题,介绍一个通用示例,然后介绍我自己的。

预期的输入形状由(样本、时间步长、特征)组成。这是我第一次陷入困境,因为许多示例仅提供以下两个输入:

model.add(LSTM(32, input_shape=(TIMESTEPS, FEATURES), activation='relu', return_sequences = True))

如果我是对的,当省略第三个参数时,你只是没有指定样本的数量。

所以,想象一下我有以下结构作为输入:

import numpy as np    
np.zeros((BATCHES, TIMESTEPS, FEATURES))

把它放在数字中,我们可以有:

np.zeros((2, 3, 5))

[[[0. 0. 0. 0. 0.]
  [0. 0. 0. 0. 0.]
  [0. 0. 0. 0. 0.]]

 [[0. 0. 0. 0. 0.]
  [0. 0. 0. 0. 0.]
  [0. 0. 0. 0. 0.]]]

这正是我的情况。我有一个 0 层input_shape=(480, 16),它model.predict()正在接受一个形状 (1, 480, 16) 的输入,在使用batch = np.zeros((90, 480, 16)). 具有形状 (1, 480, 16) 的预测输入的单个小批量等于,model.predict(batch[[i]])但我期望返回一个长度等于 480 的数组 1D,相反,我收到[[0. 1. ... 0. 0.]]的是:< 480。

这个数组的值现在无关紧要,但他的形状应该预测每个时间步的值。

我的问题在哪里?提前致谢

更新: 我的案例的整个模型声明是:

model = Sequential()
model.add(LSTM(32, input_shape=(480, 16), activation='relu', return_sequences = True)))
model.add(Dense(16))
model.compile(loss='mse', optimizer=Adam(lr=0.1))
return model

输入类似于以下声明:

batch = np.zeros((90, 480, 16)) # this is filled after
input_to_predict = batch[[i]] # where i is in the range > 0  and < 90
model.predict(input_to_predict)

标签: pythontensorflowkeraslstm

解决方案


上面的示例返回 shape (1, 480, 16)。当您设置 时return_sequences=True,Keras 将返回时间步长维度(您的“中间”维度),因此如果您的输入有 480 个时间步长,它将输出 480 个时间步长。最后一个维度将是最后一层中的单元数。

import numpy as np
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import *

model = Sequential()
model.add(LSTM(32, input_shape=(480, 16), return_sequences = True))
model.add(Dense(16))
model.compile(loss='mse', optimizer='adam')


batch = np.zeros((90, 480, 16))
input_to_predict = batch[[0]]
model.predict(input_to_predict).shape
array([[[0., 0., 0., ..., 0., 0., 0.],
        [0., 0., 0., ..., 0., 0., 0.],
        [0., 0., 0., ..., 0., 0., 0.],
        ...,
        [0., 0., 0., ..., 0., 0., 0.],
        [0., 0., 0., ..., 0., 0., 0.],
        [0., 0., 0., ..., 0., 0., 0.]]], dtype=float32)
(1, 480, 16)

如果您设置return_sequences=False,它不会返回时间步长维度:

import numpy as np
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import *

model = Sequential()
model.add(LSTM(32, input_shape=(480, 16), return_sequences = False))
model.add(Dense(16))
model.compile(loss='mse', optimizer='adam')


batch = np.zeros((90, 480, 16))
input_to_predict = batch[[0]]
model.predict(input_to_predict).shape
(1, 16)

推荐阅读