【问题标题】:Keras LSTM layers input shapeKeras LSTM 层输入形状
【发布时间】:2018-02-27 01:52:15
【问题描述】:

我正在尝试将具有 20 个特征的序列提供给 LSTM 网络,如代码所示。但是我收到一个错误,即我的 Input0 与 LSTM 输入不兼容。不知道如何更改我的层结构以适应数据。

def build_model(features, aux1=None, aux2=None):
# create model
features[0] = np.asarray(features[0])
main_input = Input(shape=features[0].shape, dtype='float32', name='main_input')
main_out   = LSTM(40, activation='relu')
aux1_input = Input(shape=(len(aux1[0]),),   dtype='float32', name='aux1_input')
aux1_out   = Dense(len(aux1[0]))(aux1_input)
aux2_input = Input(shape=(len(aux2[0]),),   dtype='float32', name='aux2_input')
aux2_out   = Dense(len(aux2[0]))(aux2_input)
x = concatenate([aux1_out, main_out, aux2_out])
x = Dense(64, activation='relu')(x)
x = Dropout(0.5)(x)
output = Dense(1, activation='sigmoid', name='main_output')(x)
model = Model(inputs=[aux1_input, aux2_input, main_input], outputs= [output])
return model

特征变量是一个形状数组 (1456, 20) 我有 1456 天,每天我有 20 个变量。

【问题讨论】:

  • 请显示错误信息。您的序列有 20 个特征?但是你的序列的长度是多少? (多少时间步?)
  • ValueError: Input 0 is in compatible with layer lstm_1: expected ndim=3, found ndim=2 is the exact error

标签: python-3.x deep-learning keras lstm


【解决方案1】:

你的 main_input 应该是 (samples, timesteps, features) 然后你应该像这样定义 main_input:

main_input = Input(shape=(timesteps,))  # for stateless RNN (your one)

main_input = Input(batch_shape=(batch_size, timesteps,)) 用于有状态 RNN(不是您在示例中使用的那个)

如果您的 features[0] 是一个包含各种特征的一维数组(1 个时间步长),那么您还必须像这样重塑 features[0]

features[0] = np.reshape(features[0], (1, features[0].shape))

然后对features[1]features[2]等进行操作

或者更好地一次重塑所有样本:

features = np.reshape(features, (features.shape[0], 1, features.shape[1]))

【讨论】:

  • 我把主输入改成 main_input = Input(batch_shape=(batch_size, 20,), dtype='float32', name='main_input') main_out = LSTM(40, activation='relu' )(main_input) 但我仍然有错误(输入 0 与层 lstm_1 不兼容:预期 ndim=3,发现 ndim=2)
  • @Oğu 你确定你的 x.shape 和 y.shape 有 3 个维度(样本、时间步长、特征)吗?否则你必须重塑数据
【解决方案2】:

LSTM 层设计用于处理“序列”。

你说你的序列有 20 个特征,但它有多少个时间步长?您是指 20 个时间步长吗?

LSTM 层需要输入形状,例如 (BatchSize, TimeSteps, Features)

如果您在每个20 time steps 中都有1 feature,您必须将数据调整为:

inputData = someData.reshape(NumberOfSequences, 20, 1)

Input 张量应该是这个形状:

main_input = Input((20,1), ...) #yes, it ignores the batch size

【讨论】:

  • 如果我有 5 个时间步,我将如何修改我的输入(在这种情况下为“特征”)?
  • 将其重塑为(NumberOfSequences, 5, 20) --- 假设有 20 个特征沿着 5 个时间步长变化。 --- --- 我注意到的一件事是您使用features[0].shape 作为输入形状。如果features[0]的形状已经正确,则应该使用features[0].shape[1:],因为第一个数字是NumberOfSequences,在定义层时不会传递。
猜你喜欢
  • 2019-01-22
  • 2019-01-20
  • 1970-01-01
  • 2019-09-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-18
相关资源
最近更新 更多