我找不到我想要的信息,所以我在这里发布我的问题。我刚刚开始学习机器学习。我使用scikit-learn库对时间序列数据进行了我的第一次多元回归。我的代码如下所示
X = df[feature_cols]
y = df[['scheduled_amount']]
index= y.reset_index().drop('scheduled_amount', axis=1)
linreg = LinearRegression()
tscv = TimeSeriesSplit(max_train_size=None, n_splits=11)
li=[]
for train_index, test_index in tscv.split(X):
train = index.iloc[train_index]
train_start, train_end = train.iloc[0,0], train.iloc[-1,0]
test = index.iloc[test_index]
test_start, test_end = test.iloc[0,0], test.iloc[-1,0]
X_train, X_test = X[train_start:train_end], X[test_start:test_end]
y_train, y_test = y[train_start:train_end], y[test_start:test_end]
linreg.fit(X_train, y_train)
y_predict = linreg.predict(X_test)
print('RSS:' + str(linreg.score(X_test, y_test)))
y_test['predictec_amount'] = y_predict
y_test.plot()
需要注意的是,我的数据是时间序列数据,我希望在拟合模型时保留数据框中的日期时间索引。我使用了TimeSeriesSplit进行交叉验证。我仍然不太理解交叉验证。首先,时间序列数据集是否需要交叉验证?其次,我应该使用最后的线性系数,还是应该使用所有系数的平均值来进行未来的预测?
回答:
是的,时间序列数据集确实需要进行交叉验证。基本原因是你需要确保你的模型不会过度拟合当前的测试数据,并且能够捕捉到过去的季节性变化,这样你就可以对模型在未来表现有信心。这种方法也用于选择模型的超参数(例如,Ridge回归中的alpha)。
为了进行未来的预测,你应该使用全部数据和最佳超参数重新拟合你的回归模型,或者,如@Marcus V.在评论中提到的,可能最好只用最新的数据进行训练。