使用sklearn实现基于梯度下降树实现波士顿房价预测
时间: 2024-05-12 08:18:28 浏览: 7
对于使用scikit-learn实现基于梯度下降树的波士顿房价预测,可以使用GradientBoostingRegressor类来完成该任务。以下是示例代码:
```python
from sklearn.datasets import load_boston
from sklearn.ensemble import GradientBoostingRegressor
from sklearn.metrics import mean_squared_error
from sklearn.model_selection import train_test_split
# 加载数据集
boston = load_boston()
# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(boston.data, boston.target, test_size=0.2, random_state=42)
# 定义梯度下降树回归器
gbr = GradientBoostingRegressor(n_estimators=100, learning_rate=0.1, max_depth=3, random_state=42)
# 训练模型
gbr.fit(X_train, y_train)
# 预测测试集
y_pred = gbr.predict(X_test)
# 评估模型
mse = mean_squared_error(y_test, y_pred)
print("Mean Squared Error: {:.3f}".format(mse))
```
在该示例中,使用了GradientBoostingRegressor类来定义梯度下降树回归器,并设置了相关超参数(例如,n_estimators,learning_rate和max_depth)。然后,使用fit方法对模型进行训练,并使用predict方法预测测试集。最后,使用mean_squared_error函数计算预测值和实际值之间的均方误差(MSE)来评估模型性能。