Keras LSTM层输入形状

时间:2017-09-18 13:39:04

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

我正在尝试将具有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个变量。

2 个答案:

答案 0 :(得分:3)

LSTM图层设计用于"序列"。

你说你的序列有20个功能,但它有多少时间步长?你的意思是20个步骤吗?

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

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

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

Input张量应该采用这种形式:

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

答案 1 :(得分:2)

你的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维数组(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]))