CART分类树和回归树的python代码
时间: 2024-01-14 19:02:56 浏览: 89
CART(Classification and Regression Trees)分类树和回归树的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)
# 训练分类树模型
clf = DecisionTreeClassifier()
clf.fit(X_train, y_train)
# 预测
y_pred = clf.predict(X_test)
# 输出准确率
print("Accuracy:", clf.score(X_test, y_test))
```
回归树代码:
``` 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)
# 训练回归树模型
reg = DecisionTreeRegressor()
reg.fit(X_train, y_train)
# 预测
y_pred = reg.predict(X_test)
# 输出MSE
from sklearn.metrics import mean_squared_error
print("MSE:", mean_squared_error(y_test, y_pred))
```
阅读全文