使用 Python 的面板数据随机森林

Random Forest on Panel Data using Python

所以我遇到了一些麻烦 运行 面板数据的随机森林回归。

目前的数据是这样的:

我想进行随机森林回归,根据我拥有的变量预测每个 ID 随着时间的推移的 KwH。我使用以下代码将我的数据分成训练和测试样本:

from sklearn.model_selection import train_test_split
X = df[['hour', 'day', 'month', 'dayofweek', 'apparentTemperature',
       'summary', 'household_size', 'work_from_home', 'num_rooms',
       'int_in_renew', 'int_in_gen', 'conc_abt_cc', 'feel_abt_lifestyle',
       'smrt_meter_help', 'avg_gender', 'avg_age', 'house_type', 'sum_insul',
       'total_lb', 'total_fridges', 'bigg_apps', 'small_apps',
       'look_at_meter']]
y = df[['KwH']]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3)

然后我希望训练我的模型并针对测试样本对其进行测试,但是我不确定如何执行此操作。我试过这段代码:

from sklearn.ensemble import RandomForestRegressor
rfc = RandomForestRegressor(n_estimators=200)
rfc.fit(X_train, y_train)

但是我收到以下错误消息:

A column-vector y was passed when a 1d array was expected. Please change the shape of y to (n_samples,), for example using ravel().

我不确定错误的根本原因是我的数据排列方式还是我处理随机森林的方式,所以如果对此有任何帮助,然后根据测试样本测试数据,我们将不胜感激。

提前致谢。

只需将 y = df[['KwH']] 切换为 y = df['KwH']y = df.KwH 即可解决此问题。

这是因为 scikit-learn 不希望 y 成为数据框,而选择带有双 [[...]] 的列恰恰是返回数据框。