【问题标题】:How can I use LSTM for tabular data?如何将 LSTM 用于表格数据?
【发布时间】:2023-02-25 01:54:18
【问题描述】:

我正在研究用于网络入侵检测的 LSTM 模型。我的数据集是一个包含 48 个特征和 8 个标签的表格,每行代表网络流量的一个实例,标签表示该实例是良性 (0) 还是一种攻击类型 (1-7)。我创建了一个用于流量分类的 LSTM 模型,如下所示:

model = keras.Sequential()
model.add(keras.layers.Input(shape=(None, 48)))
model.add(keras.layers.LSTM(256, activation='relu', return_sequences=True))
model.add(keras.layers.LSTM(256, activation='relu', return_sequences=True))
model.add(keras.layers.LSTM(128, activation='relu', return_sequences=False))
model.add(keras.layers.Dense(100, activation='relu'))
model.add(keras.layers.Dense(80, activation='relu'))
model.add(keras.layers.Dense(8, activation='softmax'))
model.compile(loss='sparse_categorical_crossentropy', optimizer='adam', metrics=['mae', 'accuracy'])

但是,当我尝试拟合模型时,出现错误:

ValueError: Exception encountered when calling layer 'sequential_2' (type Sequential).
    Input 0 of layer "lstm_4" is incompatible with the layer: expected ndim=3, found ndim=2. Full shape received: (None, 48)

在此之前,我收到警告:

WARNING:tensorflow:Model was constructed with shape (None, None, 48) for input KerasTensor(type_spec=TensorSpec(shape=(None, None, 48), dtype=tf.float32, name='input_3'), name='input_3', description="created by layer 'input_3'"), but it was called on an input with incompatible shape (None, 48).

我想我必须对数据的形状做些什么,但我不知道具体是什么。非常感谢您的帮助。

【问题讨论】:

  • 错误消息指示第一个 LSTM 层的输入形状不正确。 LSTM 层预期的 3 维形状输入(批量大小、时间步长、输入暗淡),而不是 2 维形状输入(批量大小、输入暗淡)。
  • 非常感谢,我明白了,但我不知道如何重塑我的数据,使其符合 LSTM 层的预期形状
  • 发布加载数据的代码?

标签: python tensorflow machine-learning keras lstm


【解决方案1】:

您提到您的数据有 48 个特征,每一行都是一个时间步长。假设你想构建一个模型,一次只拟合一个时间步长的模型,那么你的网络的输入形状,(batch_size, n_timesteps, n_features) 将是(None, 1, 48)。 (请注意,根据您使用 LSTM 的意图,您可能希望增加 n_timesteps,这可以通过对数据进行窗口化来实现)

假设您的输入表是形状为 (n_rows, 48) 的数组 - 我可以从警告消息中看出这一点,您需要重塑数据。如果您的数据是一个 numpy 数组 x,那么您可以使用 np.expand_dims 重塑您的数据:

x_reshaped = np.expand_dims(x, axis=1)

np.expand_dimsaxis=1 向位置 1 处的数据添加一个轴,因此生成的数据形状从 (n_rows, 48) 变为 (n_rows, 1, 48)。然后你可以毫无错误地调用model.fit(x_reshaped, y)

【讨论】:

    猜你喜欢
    • 2021-05-27
    • 2019-04-28
    • 1970-01-01
    • 2019-10-03
    • 1970-01-01
    • 2021-10-07
    • 2017-06-27
    • 2020-09-06
    • 2020-11-01
    相关资源
    最近更新 更多