Chr*_*ris 5 python datetime prediction scikit-learn
我有一个 df ,我需要预测未来 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
Run Code Online (Sandbox Code Playgroud)
具体来说,对于2004-11-20第 1 行中的日期,我需要Y未来 7 天的每一天的预测值,而不仅仅是当前日期(变量Y),并且考虑到要预测从 开始的第 5 天,2004-11-20我将不会获得数据未来 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...
Run Code Online (Sandbox Code Playgroud)
我们必须估算或删除使用移位时产生的 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)
Run Code Online (Sandbox Code Playgroud)
现在我们可以实例化 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
Run Code Online (Sandbox Code Playgroud)
这些对我来说在 sklearn 版本上运行得很好0.20.1。当然,现在我得到了一个糟糕的分数结果,但是模型确实进行了训练,并且预测方法确实返回了每个 Y 列的预测,并且得分方法返回了一个分数。
| 归档时间: |
|
| 查看次数: |
2307 次 |
| 最近记录: |