使用波士顿房价数据决策树
时间: 2024-02-21 07:54:36 浏览: 67
以下是使用波士顿房价数据进行决策树的示例:
```python
# 引入所需的库和模块
from sklearn.datasets import load_boston
from sklearn.model_selection import train_test_split, GridSearchCV
from sklearn.tree import DecisionTreeRegressor
# 获取波士顿房价数据
boston = load_boston()
X = boston.data
y = boston.target
# 切分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# 实例化决策树模型对象
model = DecisionTreeRegressor()
# 使用网格搜索交叉验证寻找最优超参数max_depth
param_grid = {'max_depth': [3, 5, 7, 9]}
grid_search = GridSearchCV(model, param_grid, cv=5)
grid_search.fit(X_train, y_train)
# 打印最优超参数
print("Best parameter: ", grid_search.best_params_)
# 打印最优得分
print("Best score: ", grid_search.best_score_)
# 使用最优超参数重新实例化模型对象,并重新训练模型
best_model = DecisionTreeRegressor(max_depth=grid_search.best_params_['max_depth'])
best_model.fit(X_train, y_train)
```
阅读全文