用python实现CART分类树
时间: 2023-09-22 08:05:07 浏览: 82
以下是python实现CART分类树的示例代码:
```python
import pandas as pd
from sklearn.tree import DecisionTreeClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
# 加载数据集
data = pd.read_csv('data.csv')
X = data.iloc[:, :-1]
y = data.iloc[:, -1]
# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
# 训练CART分类树
clf = DecisionTreeClassifier()
clf.fit(X_train, y_train)
# 预测测试集
y_pred = clf.predict(X_test)
# 评估模型
accuracy = accuracy_score(y_test, y_pred)
print('Accuracy:', accuracy)
```
其中,data.csv是存储数据集的文件名,X是数据集的特征,y是数据集的标签。train_test_split用于划分训练集和测试集,test_size表示测试集占总数据集的比例,random_state用于控制随机数生成器的种子,保证每次划分的结果一致。DecisionTreeClassifier用于训练CART分类树模型。accuracy_score用于计算模型的准确率。
阅读全文