LSTM+CNN 中更简单时间序列的输入形状

数据挖掘 喀拉斯 时间序列 lstm 美国有线电视新闻网
2022-02-27 21:48:22

以下是来自https://machinelearningmastery.com/how-to-develop-rnn-models-for-human-activity-recognition-time-series-classification/的代码,该代码使用 LSTM 和 CNN 以及 TimeDistributed 用于人类活动时间序列:

def evaluate_model(trainX, trainy, testX, testy):
    # define model
    verbose, epochs, batch_size = 0, 25, 64
    n_timesteps, n_features, n_outputs = trainX.shape[1], trainX.shape[2], trainy.shape[1]
    # reshape data into time steps of sub-sequences
    n_steps, n_length = 4, 32
    trainX = trainX.reshape((trainX.shape[0], n_steps, n_length, n_features))
    testX = testX.reshape((testX.shape[0], n_steps, n_length, n_features))
    # define model
    model = Sequential()
    model.add(TimeDistributed(Conv1D(filters=64, kernel_size=3, activation='relu'), input_shape=(None,n_length,n_features)))
    model.add(TimeDistributed(Conv1D(filters=64, kernel_size=3, activation='relu')))
    model.add(TimeDistributed(Dropout(0.5)))
    model.add(TimeDistributed(MaxPooling1D(pool_size=2)))
    model.add(TimeDistributed(Flatten()))
    model.add(LSTM(100))
    model.add(Dropout(0.5))
    model.add(Dense(100, activation='relu'))
    model.add(Dense(n_outputs, activation='softmax'))
    model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
    # fit network
    model.fit(trainX, trainy, epochs=epochs, batch_size=batch_size, verbose=verbose)
    # evaluate model
    _, accuracy = model.evaluate(testX, testy, batch_size=batch_size, verbose=0)
    return accuracy

但是,我想为简单的时间序列数据(1000 行和 100 列)修改上面的代码,其中每一行是 100 个值的时间序列(显示为列)。输出是一个类,有 7 种类(因此 n_output=7)。这是一个“序列分类”问题。

为此,我应该对上述功能进行哪些更改?我是否需要 n_steps 和 n_length (因为我的数据比人类活动识别数据更简单)?对于简单的 CNN1D,我必须重塑如下:

trainX = trainX.reshape(nrows, ncols, 1)
# then use (ncols, 1) as input shape

我应该如何在这里重塑?

我尝试删除 n_steps 和 n_length 并将 input_shape 设置为 (100, 1) (在将数据重塑为 (1000,100,1) 之后),但它不起作用。

1个回答

对于张量流中的 LSTM,张量具有三个输入。所以,假设我们有:[样本、时间步长、特征]。这意味着您有 n 个样本,并且每个样本都分为 m 个时间步长。所有样本都具有相同的数量和相同的特征。

因此,在您的情况下,n_steps, n_length = 4, 32 意味着将在具有 32 个样本的数据中采用 n_steps,这意味着每 4 个样本在一个时间点被送入 LSTM。或者 8 个不同的子集将被输入 LSTM。LSTM 通常采用子集(不是单行样本!)

根据您的重塑 (1000,100,1) 您说您有 1000 个样本(将它们想象为数据集的子集),并且将这 1000 个子集中的每一个分为 100 个时间步长。这意味着在 1000 个子集中的每一个子集中,您必须至少有 100 个样本或一个可被 100 整除的数字,否则将无法正常工作。第三个参数“1”是指数据集/子集中的特征数量。当您使用加速度计数据时,我不相信您只使用一种功能。我的猜测是你需要至少有 3 个特征(x、y 和 z)或者更多。

请查看他们的文档站点:https ://www.tensorflow.org/tutorials/sequences/recurrent