time-series - 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
我的数据准备方法和数据重塑正确吗?
解决方案
正如@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]
推荐阅读
- html - 为什么我的图像没有与网格列的底部对齐?
- python - Django Rest 模型配置不当:
- java - 如何将随机数从 Java 类传递到 html 文件
- ruby-on-rails - Rails 2,将一列数据移动到新表并删除该列
- airflow - 在谷歌云 Composer 上升级气流图像版本
- javascript - 使用 ajax 将选项附加到多选并保留所选值
- firebase - bigquery 中没有来自 Firebase 分析的日内事件数据
- regex - 由于与另一个匹配项相似的搜索条件,正则表达式拆分不正确
- python - 如何合并具有交集的集合(连通分量算法)?
- reactjs - 单击按钮后页面未重新呈现