首页 > 解决方案 > LSTM 多特征回归数据准备

问题描述

我正在建模一个包含多个特征和一个目标值的 LSTM 模型。这是一个回归问题。我怀疑我为 LSTM 准备的数据是错误的;主要是因为模型只学习目标值的平均值。

我编写的以下代码用于为 LSTM 准备数据:

# df is a pandas data frame that contains the feature columns (f1 to f5) and the target value named 'target'
# all columns of the df are time series data (including the 'target')
# seq_length is the sequence length 
def prepare_data_multiple_feature(df):
    X = []
    y = []

    for x in range(len(df)):
        start_id = x
        end_id = x + seq_length
        one_data_point = []
        if end_id + 1 <= len(df):
            # prepare X
            for col in ['f1', 'f2', 'f3', 'f4', 'f5']:
                one_data_point.append(np.array(df[col].values[start_id:end_id]))
            X.append(np.array(one_data_point))
            # prepare y
            y.append(np.array(df['target'].values[end_id ])) 

    assert len(y) == len(X)
    return X, y

然后,我将数据重塑如下:

X, y = prepare_data_multiple_feature(df)
X = X.reshape((len(X), seq_length, 5)) #5 is the number of features, i.e., f1 to f5

我的数据准备方法和数据重塑正确吗?

标签: time-serieslstm

解决方案


正如@isp-zax 提到的,请提供一个reprex,以便我们可以重现结果并查看问题所在。

顺便说一句,您可以使用for col in df.columns而不是列出所有列名和(次要优化)应该执行第一个循环for x in range(len(df) - seq_length),否则最后您会seq_length - 1多次执行循环而不实际处理任何数据。此外,df.values[a, b]不会包含索引处的元素,b因此如果您想在您X的最后一行包含“窗口”end_id可以等于len(df),即您可以执行您的内部条件(准备和追加)if end_id <= len(df):

除此之外,我认为如果您同时跨列和行切片数据帧,而不使用one_data_point,即选择seq_length没有(最后一个)目标列的行,那么阅读起来会更简单,只需执行以下操作:

df.values[start_id, end_id, :-1]

推荐阅读