利用CART决策树对iris数据集进行分类。训练数据集占原数据集的90%,剩余的为测试数据集。画出决策树模型后评估模型准确率。
时间: 2023-12-29 19:03:04 浏览: 55
CART_iris.rar_CART算法_cart tree_cart分类_决策树分类_多类识别
5星 · 资源好评率100%
好的,我会为您解答这个问题。
首先,我们需要加载iris数据集并将其分为训练集和测试集:
```python
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.1)
```
接下来,我们可以使用CART决策树来训练模型:
```python
from sklearn.tree import DecisionTreeClassifier
model = DecisionTreeClassifier()
model.fit(X_train, y_train)
```
然后,我们可以使用测试集来评估模型的准确率:
```python
from sklearn.metrics import accuracy_score
y_pred = model.predict(X_test)
accuracy = accuracy_score(y_test, y_pred)
print("Accuracy:", accuracy)
```
最后,我们可以使用Graphviz来可视化决策树:
```python
from sklearn.tree import export_graphviz
import graphviz
dot_data = export_graphviz(model, out_file=None, feature_names=iris.feature_names, class_names=iris.target_names)
graph = graphviz.Source(dot_data)
graph.render("iris")
```
这将生成一个名为“iris”的PDF文件,其中包含决策树的可视化。
完整代码如下:
```python
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import accuracy_score
from sklearn.tree import export_graphviz
import graphviz
iris = load_iris()
X_train, X_test, y_train, y_test = train_test_split(iris.data, iris.target, test_size=0.1)
model = DecisionTreeClassifier()
model.fit(X_train, y_train)
y_pred = model.predict(X_test)
accuracy = accuracy_score(y_test, y_pred)
print("Accuracy:", accuracy)
dot_data = export_graphviz(model, out_file=None, feature_names=iris.feature_names, class_names=iris.target_names)
graph = graphviz.Source(dot_data)
graph.render("iris")
```
阅读全文