gpt4 book ai didi

python - 多重预测

转载 作者:太空宇宙 更新时间:2023-11-03 11:38:58 24 4
gpt4 key购买 nike

我有一个 df,我需要在其中预测 future 7 天内每一天的因变量(数字)。 train 数据如下:

df.head()
Date X1 X2 X3 Y
2004-11-20 453.0 654 989 716 # row 1
2004-11-21 716.0 878 886 605
2004-11-22 605.0 433 775 555
2004-11-23 555.0 453 564 680
2004-11-24 680.0 645 734 713

具体来说,对于第 1 行中的日期 2004-11-20,我需要一个 Y future 7 天的每一天的预测值,而不仅仅是今天(变量 Y),并考虑到预测从 2004-11-20 开始的第 5 天,我不会获得接下来 4 天开始的数据在 2004-11-20

我一直在考虑再创建 7 个变量("Y+1day""Y+2day"等等),但我需要为每一天创建一个训练 df,因为机器学习技术只返回一个变量作为输出。有没有更简单的方法?

我正在使用 skikit-learn 库进行建模。

最佳答案

您完全可以训练一个模型来预测 sklearn 中的多个输出。而且 pandas 非常灵活。在下面的示例中,我将您的日期列转换为日期时间索引,然后使用 shift 实用程序获取更多 Y 值。

import io
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split

# Read from stackoverflow artifacts
s = """Date X1 X2 X3 Y
2004-11-20 453.0 654 989 716
2004-11-21 716.0 878 886 605
2004-11-22 605.0 433 775 555
2004-11-23 555.0 453 564 680
2004-11-24 680.0 645 734 713"""
text = io.StringIO(s)
df = pd.read_csv(text, sep='\\s+')

# Datetime index
df["Date"] = pd.to_datetime(df["Date"], format="%Y/%m/%d")
df = df.set_index("Date")

# Shifting for Y@Day+N
df['Y1'] = df.shift(1)['Y'] # One day later
df['Y2'] = df.shift(2)['Y'] # Two...

我们必须估算或删除使用 shift 时产生的 NaN。在大型数据集中,这希望只会导致时间范围边缘的估算或丢弃数据。例如,如果您想要转移 7 天,您的数据集将损失 7 天,具体取决于您的数据结构以及您需要转移的方式。

df.dropna(inplace=True) # Drop two rows

train, test = train_test_split(df)
# Get two training rows
trainX = train.drop(["Y", "Y1", "Y2"], axis=1)
trainY = train.drop(["X1", "X2", "X3"], axis=1)

# Get the test row
X = test.drop(["Y", "Y1", "Y2"], axis=1)
Y = test.drop(["X1", "X2", "X3"], axis=1)

现在我们可以从 sklearn 中实例化一个分类器并进行预测。

from sklearn.linear_model import LinearRegression

clf = LinearRegression()
model = clf.fit(trainX, trainY)
model.predict(X) # Array of three numbers
model.score(X, Y) # Predictably abysmal score

使用 sklearn 版本 0.20.1,这些对我来说都运行良好。现在我当然得到了一个糟糕的分数结果,但是模型确实训练了,并且预测方法确实返回了每个 Y 列的预测,并且分数方法返回了一个分数。

关于python - 多重预测,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53808047/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com