我正在进行时间序列预测项目。我的任务是从1月到11月获得数据时预测12月的销售额。我将数据分为训练和测试集。我已经应用Randomforestregression对测试集进行预测。但是,我不知道如何使用该模型来预测12月的销售额。你能让我知道怎么做吗?预先谢谢你。
答案 0 :(得分:0)
如果您已经完成清理数据的工作,并且已经将它们拆分为training
和testing
数据集。您只需将它们通过我创建的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
我发表了不言自明的评论。如果您在理解代码方面遇到困难,请随时在注释中进行讨论。