随机森林回归的python代码
时间: 2023-11-12 09:11:12 浏览: 83
以下是使用sklearn库实现随机森林回归的Python代码示例:
```python
from sklearn.ensemble import RandomForestRegressor
from sklearn.metrics import mean_squared_error
from sklearn.datasets import load_boston
from sklearn.model_selection import train_test_split
# 加载波士顿房价数据集
boston = load_boston()
X, y = boston.data, boston.target
# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# 创建随机森林回归模型并拟合数据
rf = RandomForestRegressor(n_estimators=100, random_state=42)
rf.fit(X_train, y_train)
# 用训练好的模型进行预测
y_pred = rf.predict(X_test)
# 计算均方误差
mse = mean_squared_error(y_test, y_pred)
print("均方误差:", mse)
```
在这个示例中,我们使用了sklearn库中的`RandomForestRegressor`类来创建随机森林回归模型。我们使用波士顿房价数据集来训练和测试模型。在拟合数据后,我们使用模型对测试集进行预测,并计算均方误差来评估模型的性能。
阅读全文
相关推荐


















