python写一段决策树分类模型的代码,并且输出测试误差和训练误差
时间: 2024-02-07 08:01:54 浏览: 88
好的,以下是一份简单的决策树分类模型代码:
```python
from sklearn.tree import DecisionTreeClassifier
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
# 加载数据
iris = load_iris()
data = iris.data
target = iris.target
# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(data, target, test_size=0.3)
# 创建决策树分类器
clf = DecisionTreeClassifier()
# 训练模型
clf.fit(X_train, y_train)
# 预测测试集
y_pred = clf.predict(X_test)
# 计算测试误差和训练误差
test_error = 1 - accuracy_score(y_test, y_pred)
train_error = 1 - clf.score(X_train, y_train)
# 输出测试误差和训练误差
print("测试误差:", test_error)
print("训练误差:", train_error)
```
这份代码使用了sklearn库中的DecisionTreeClassifier类,加载了iris数据集作为训练数据,划分了训练集和测试集,训练了模型,预测了测试集,最后计算了测试误差和训练误差并输出。
阅读全文