【问题标题】:How to predict correctly in sklearn RandomForestRegressor?如何在 sklearn RandomForestRegressor 中正确预测?
【发布时间】:2020-04-15 00:58:56
【问题描述】:

我正在为我的学校项目开发一个大数据项目。我的数据集如下所示: https://github.com/gindeleo/climate/blob/master/GlobalTemperatures.csv

我正在尝试预测“LandAverageTemperature”的下一个值。

首先,我已将 csv 导入 pandas 并将其命名为“df1”的 DataFrame。

在我第一次尝试 sklearn 时出错后,我将“dt”列从字符串转换为 datetime64,然后添加了一个名为“year”的列,该列仅显示日期值中的年份。-它可能是错误的-

df1["year"] = pd.DatetimeIndex(df1['dt']).year

在所有这些之后,我为回归准备了我的数据并调用了 RandomForestReggressor:

landAvg = df1[["LandAverageTemperature"]]
year = df1[["year"]]

from sklearn.ensemble import RandomForestRegressor

rf_reg=RandomForestRegressor(n_estimators=10,random_state=0)
rf_reg.fit(year,landAvg.values.ravel())
print("Random forest:",rf_reg.predict(landAvg))

我运行了代码,我看到了这个结果:

Random forest: [9.26558115 9.26558115 9.26558115 ... 9.26558115 9.26558115 9.26558115]

我没有收到任何错误,但我认为结果不正确-结果与您看到的完全相同-。此外,当我想获得下一个 10 年的预测时,我不知道该怎么做。我用这段代码只得到 1 个结果。你能帮我改进我的代码并得到正确的结果吗? 在此先感谢您的帮助。

【问题讨论】:

  • 这能回答你的问题吗? Forecasting future occurrences with Random Forest
  • @CeliusStingher 在某种程度上。我从答案中理解了 rf 的架构和逻辑,但我仍然无法弄清楚如何将它应用到我的代码中。-可能是因为我缺乏英语。-

标签: python pandas bigdata random-forest sklearn-pandas


【解决方案1】:

仅使用年份来预测温度是不够的。您也需要使用月份数据。这是初学者的工作示例:

import pandas as pd
from sklearn.ensemble import RandomForestRegressor
df = pd.read_csv('https://raw.githubusercontent.com/gindeleo/climate/master/GlobalTemperatures.csv', usecols=['dt','LandAverageTemperature'], parse_dates=['dt'])
df = df.dropna()
df["year"] = df['dt'].dt.year
df["month"] = df['dt'].dt.month
X = df[["month", "year"]]
y = df["LandAverageTemperature"]
rf_reg=RandomForestRegressor(n_estimators=10,random_state=0)
rf_reg.fit(X, y)
y_pred = rf_reg.predict(X)
df_result = pd.DataFrame({'year': X['year'], 'month': X['month'], 'true': y, 'pred': y_pred})
print('True values and predictions')
print(df_result)
print('Feature importances', list(zip(X.columns, rf_reg.feature_importances_)))

这是输出:

True values and predictions
      year  month    true     pred
0     1750      1   3.034   2.2944
1     1750      2   3.083   2.4222
2     1750      3   5.626   5.6434
3     1750      4   8.490   8.3419
4     1750      5  11.573  11.7569
...    ...    ...     ...      ...
3187  2015      8  14.755  14.8004
3188  2015      9  12.999  13.0392
3189  2015     10  10.801  10.7068
3190  2015     11   7.433   7.1173
3191  2015     12   5.518   5.1634

[3180 rows x 4 columns]
Feature importances [('month', 0.9543059863177156), ('year', 0.045694013682284394)]

【讨论】:

  • 我知道在 cmets 中说谢谢不是这里推荐的事情,但我不能感谢你。希望你有一个愉快的一天。
猜你喜欢
  • 2018-03-23
  • 2019-08-12
  • 1970-01-01
  • 2015-04-20
  • 2020-10-08
  • 2020-07-11
  • 2019-11-05
  • 2020-06-26
  • 2019-07-17
相关资源
最近更新 更多