我为网络会话的生存预测创建了一个CNN-LSTM模型,我的训练数据如下所示:
print(x_train.shape)(288, 3, 393)
其中包含(样本数, 时间步长, 特征数),我的模型如下:
model = Sequential()model.add(TimeDistributed(Conv1D(128, 5, activation='relu'), input_shape=(x_train.shape[1], x_train.shape[2])))model.add(TimeDistributed(MaxPooling1D()))model.add(TimeDistributed(Flatten()))model.add(LSTM(64, stateful=True, return_sequences=True))model.add(LSTM(16, stateful=True))model.add(Dense(1, activation='sigmoid'))model.compile(optimizer=Adam(lr=0.001), loss='binary_crossentropy', metrics=['accuracy'])
然而,TimeDistributed
层需要至少3个维度,我应该如何转换数据以使其工作?
非常感谢!
回答:
你的数据已经是3D格式,这正是你需要的,用于输入Conv1D或LSTM。如果你的目标是2D,请记住在最后一个LSTM单元中设置return_sequences=False。
在LSTM之前使用Flatten是一个错误,因为你破坏了3D维度
还要注意池化操作,以免减少负时间维度(我在上面的卷积中使用了’same’填充以避免这种情况)
以下是一个二分类任务的示例
n_sample, time_step, n_features = 288, 3, 393X = np.random.uniform(0,1, (n_sample, time_step, n_features))y = np.random.randint(0,2, n_sample)model = Sequential()model.add(Conv1D(128, 5, padding='same', activation='relu', input_shape=(time_step, n_features)))model.add(MaxPooling1D())model.add(LSTM(64, return_sequences=True))model.add(LSTM(16, return_sequences=False))model.add(Dense(1, activation='sigmoid'))model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])model.fit(X,y, epochs=3)