【发布时间】:2021-10-28 14:02:27
【问题描述】:
我正在尝试拟合 随机森林回归模型。这是我遵循的步骤(请参阅 下面的代码与 cmets):
- 在拟合模型之前,我已经分为训练和测试
- 我已将结果转换为数组
- 我已将它们重新整形为 2D 数组,因为回归器希望它们使用整形函数
我收到以下错误(似乎有一个一维数组,即使我在一开始就对其进行了重构):
ValueError: Expected 2D array, got 1D array instead:
array=[183. 27. 520. ... 23. 28. 34.].
Reshape your data either using array.reshape(-1, 1) if your data has a single feature or
array.reshape(1, -1) if it contains a single sample.
这是我使用的代码:
#train & test split
X = order_final.loc[:, ~order_final.columns.isin(['lag','observed'])]
y = order_final['lag']
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
#convert X,y train and X test into arrays
X_train = X_train.to_numpy()
y_train = y_train.to_numpy()
X_test = X_test.to_numpy()
#make them 2D-arrays
X_train.reshape(-1,1)
y_train.reshape(-1,1)
X_test.reshape(-1,1)
# Fitting Random Forest Regression to the dataset
# import the regressor
from sklearn.ensemble import RandomForestRegressor
# create regressor object
RF = RandomForestRegressor(n_estimators = 100, random_state = 0)
# fit the regressor with x and y data
RF.fit(X_train, y_train)
#Prediction of test set
y_pred = RF.predict(X_test)
# View accuracy score
RF.score(y_test, y_pred)
这是我的阵列的形状(对我来说看起来不错,但是......):
print(X_train.shape)
print(y_train.shape)
print(X_test.shape)
print(y_test.shape)
print(y_pred.shape)
(7326, 10) (7326,) (1832, 10) (1832 年,) (1832 年,)
有人可以帮助我并指出错误在哪里吗?提前致谢!
斯特凡诺
【问题讨论】:
-
哪一行出错了?
-
您好,感谢您的回答。这是行:---> 30 RF.score(y_test, y_pred)
标签: python arrays machine-learning scikit-learn random-forest