【问题标题】:How to make prediction from the last datapoint of test set如何从测试集的最后一个数据点进行预测
【发布时间】:2019-06-14 22:41:16
【问题描述】:

我正在进行一个时间序列预测项目。我的任务是在拥有 1 月至 11 月的数据时预测 12 月的销售额。我将数据分成训练集和测试集。我已经应用了随机森林回归来预测测试集。但是,我不知道如何使用该模型来预测 12 月份的销售额。你能告诉我怎么做吗?提前谢谢你。

【问题讨论】:

  • 你用的是什么库? Python 没有Randomforestregression 但你还没有添加实际的库标签
  • 我使用 sklearn.ensemble 来导入 RandomForestRegressor。你能告诉我如何使用我建立的模型来预测 12 月份的销售额吗?谢谢。
  • 这不是我的建议。我说你没有添加正确的标签来引起可以提供帮助的人的注意
  • RandomForestRegressor 没有任何标签
  • 当然可以,但是我添加了一个scikit-learn。正如我在最初的评论中所说 - 什么“图书馆”

标签: python scikit-learn time-series random-forest


【解决方案1】:

如果您已经完成了对数据的清理,并且已经将它们拆分为 trainingtesting 数据集。您可以简单地将它们放入我创建的 pipline 函数中。这个generic function 将任何算法和数据作为输入并制作模型,执行交叉验证并为testing 数据集生成预测。

from sklearn.ensemble import RandomForestRegressor
from sklearn.metrics import mean_squared_error
import pandas as pd
import plotly.plotly as ply
import cufflinks as cf

cf.go_offline()


#Define target and ID columns:
target = 'sales'
IDcol = ['months']
predictors = [x for x in training.columns if x not in [target]+IDcol]

alg = RandomForestRegressor(n_estimators=200,max_depth=5, min_samples_leaf=100,n_jobs=4)
test = modelfitting(alg, training, testing, predictors, target)
coef5 = pd.Series(alg.feature_importances_, predictors).sort_values(ascending=False)
coef5.iplot(kind='bar', title='Feature Importances')

for_plot = test
for_plot = for_plot[['sales prediction']]
for_plot.iplot()


def modelfitting(alg, training, testing, predictors, target):
    # Fit the algorithm on the data
    alg.fit(training[predictors], training[target])

    # Predict training set:
    dtrain_predictions = alg.predict(training[predictors])

    # Perform cross-validation:
    cv_score = cross_val_score(alg, training[predictors], training[target], cv=20, scoring='neg_mean_squared_error')
    cv_score = np.sqrt(np.abs(cv_score))

    # Print model report:
    print "\nModel Report"
    print "RMSE : %.4g" % np.sqrt(metrics.mean_squared_error(training[target].values, dtrain_predictions))
    print "CV Score : Mean - %.4g | Std - %.4g | Min - %.4g | Max - %.4g" % (
    np.mean(cv_score), np.std(cv_score), np.min(cv_score), np.max(cv_score))

    # Predict on testing data:
    testing["sales prediction"] = alg.predict(testing[predictors])

    return testing

我已经放入了不言自明的 cmets。如果您在理解代码方面遇到困难,请随时在 cmets 中讨论。

【讨论】:

  • 嗨,我的问题是,当我们只有 1 月到 11 月的数据时,我们必须预测 12 月的数据。我们如何使用经过训练的模型来预测时间序列中的未来值(而不是预测(X_test) 并与 Y_test 进行比较?
  • 所以,只要你已经训练好模型,如上面的函数所示,你可以简单地传递你的test数据集来进行预测。该模型将使用testing["prediction"] = alg.predict(testing[predictors]) 进行预测。即使你再过几个月,比如 12 月到 2 月。它将根据训练好的模型对测试数据集进行预测
  • 对不起,我还是不明白。我没有 12 月的训练数据。比方说。我的数据框从一月到十一月只有 2 列(月份和销售额)。我不知道如何从模型预测十二月。
  • 好吧,从一月到十一月只有 2 列的数据框是我代码中的训练变量;而只有一个日期“Dec”的另一个数据框是我代码中的测试变量。一旦你训练“拟合”训练数据集,模型就可以预测测试数据集中的“销售额”。
  • 非常感谢
猜你喜欢
  • 2021-05-31
  • 2020-03-06
  • 2020-12-07
  • 2019-12-25
  • 2019-04-02
  • 2020-08-29
  • 2020-11-07
  • 1970-01-01
  • 2016-08-20
相关资源
最近更新 更多