python实现cart分类树与回归树代码
时间: 2023-09-30 18:10:37 浏览: 119
分类树(CART)的Python实现:
```python
from sklearn.tree import DecisionTreeClassifier
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
# 加载数据集
iris = load_iris()
X_train, X_test, y_train, y_test = train_test_split(iris.data, iris.target, test_size=0.3, random_state=42)
# 创建分类树
clf = DecisionTreeClassifier()
# 拟合模型
clf.fit(X_train, y_train)
# 预测
y_pred = clf.predict(X_test)
# 计算准确率
accuracy = clf.score(X_test, y_test)
print("Accuracy:", accuracy)
```
回归树(CART)的Python实现:
```python
from sklearn.tree import DecisionTreeRegressor
from sklearn.datasets import load_boston
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.3, random_state=42)
# 创建回归树
reg = DecisionTreeRegressor()
# 拟合模型
reg.fit(X_train, y_train)
# 预测
y_pred = reg.predict(X_test)
# 计算 R²
r_squared = reg.score(X_test, y_test)
print("R-squared:", r_squared)
```
阅读全文