Keras函数式API中LSTM输入shape设置及维度不匹配报错解决方案
报错原因
LSTM层要求输入为三维张量,格式为(样本数, 时间步长, 特征数),你当前输入的训练集是二维张量(样本数, 特征数),缺少时间步长维度,同时Input层形状配置、堆叠LSTM的参数设置也存在错误。
修复步骤
1. 调整数据集维度
你需要给x_train和x_test新增时间步长维度,可根据你的数据逻辑选择以下两种方案:
# 方案1:将1144作为单时间步的全部特征,新增维度后形状为(样本数, 1, 1144) x_train = x_train.reshape(x_train.shape[0], 1, x_train.shape[1]) x_test = x_test.reshape(x_test.shape[0], 1, x_test.shape[1]) # 方案2:对应你代码中定义的vector_size=572,将1144拆为2个时间步,每个时间步572维,形状为(样本数, 2, 572) x_train = x_train.reshape(x_train.shape[0], 2, 572) x_test = x_test.reshape(x_test.shape[0], 2, 572)
2. 修正模型代码
修正Input层配置,同时堆叠LSTM时前一层需添加return_sequences=True参数,保证输出三维张量给下一层LSTM使用,以下为修正后的完整代码(以方案2的维度为例):
from tensorflow.keras.layers import Input, LSTM, Dropout, Dense, Activation from tensorflow.keras.models import Model from tensorflow.keras.callbacks import EarlyStopping event_num = 65 droprate = 0.3 vector_size = 572 def build_lstm_model(): # Input层仅需传入单个样本的形状,不需要写总样本数 train_input = Input(shape=(2, 572), name='Inputlayer') # 前一层LSTM添加return_sequences=True,输出三维张量 train_in = LSTM(512, return_sequences=True)(train_input) train_in = Dropout(droprate)(train_in) train_in = LSTM(256)(train_in) train_in = Dropout(droprate)(train_in) # LSTM输出已为二维张量,无需Flatten层 train_in = Dense(event_num)(train_in) out = Activation('softmax')(train_in) model = Model(inputs=train_input, outputs=out) model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy']) return model lstm_model = build_lstm_model() early_stopping = EarlyStopping(patience=3, restore_best_weights=True) lstm_model.fit(x_train, y_train_one_hot, batch_size=128, epochs=10, validation_data=(x_test, y_test_one_hot), callbacks=[early_stopping])
注意事项
- 时间步长的设置需要匹配你的数据逻辑,如果1144是n个时间步的特征拼接,就拆分为对应的n个时间步即可
- 最后一个LSTM层不需要添加
return_sequences=True,输出的二维张量可直接接入全连接层做分类
内容的提问来源于stack exchange,提问作者Waqar Kaleem Khan
相关产品推荐
相关产品推荐

