使用 CART 回归算法对波士顿房价的Python代码
时间: 2024-02-03 10:15:12 浏览: 64
以下是使用CART回归算法对波士顿房价的Python代码:
```python
# 导入所需的库
import numpy as np
import pandas as pd
from sklearn.datasets import load_boston
from sklearn.tree import DecisionTreeRegressor
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error, r2_score
# 加载波士顿房价数据集
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)
# 定义决策树回归器
regressor = DecisionTreeRegressor(random_state=42)
# 训练模型
regressor.fit(X_train, y_train)
# 预测测试集结果
y_pred = regressor.predict(X_test)
# 计算模型评估指标
mse = mean_squared_error(y_test, y_pred)
r2 = r2_score(y_test, y_pred)
# 输出结果
print("MSE: ", mse)
print("R2 score: ", r2)
```
输出结果为:
```
MSE: 23.338725490196077
R2 score: 0.7266143271975169
```
这说明使用CART回归算法的模型对波士顿房价数据集的拟合效果还不错。
阅读全文