用决策树和随机森林分析sklearn中的boston数据集的代码
时间: 2023-05-16 19:05:01 浏览: 89
以下是使用决策树和随机森林分析sklearn中的boston数据集的代码:
```
from sklearn.datasets import load_boston
from sklearn.tree import DecisionTreeRegressor
from sklearn.ensemble import RandomForestRegressor
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error
# 加载数据集
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)
# 使用决策树进行回归
dt = DecisionTreeRegressor(random_state=42)
dt.fit(X_train, y_train)
dt_pred = dt.predict(X_test)
dt_mse = mean_squared_error(y_test, dt_pred)
print("决策树的均方误差为:", dt_mse)
# 使用随机森林进行回归
rf = RandomForestRegressor(n_estimators=100, random_state=42)
rf.fit(X_train, y_train)
rf_pred = rf.predict(X_test)
rf_mse = mean_squared_error(y_test, rf_pred)
print("随机森林的均方误差为:", rf_mse)
```
希望这个回答能够帮到你!
阅读全文