K-means聚类算法实现采用莺尾花数据,学习决策树,画出决策树
时间: 2023-07-12 14:43:58 浏览: 102
k-means聚类算法实现
以下是实现K-means聚类算法、学习决策树并绘制决策树的步骤:
1. 导入必要的库:
```python
import numpy as np
from sklearn.cluster import KMeans
from sklearn.datasets import load_iris
from sklearn.tree import DecisionTreeClassifier, plot_tree
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
import matplotlib.pyplot as plt
```
2. 加载莺尾花数据集:
```python
iris = load_iris()
X = iris.data
y = iris.target
```
3. K-means聚类算法:
```python
kmeans = KMeans(n_clusters=3, random_state=0)
kmeans.fit(X)
labels = kmeans.labels_
```
4. 学习决策树:
```python
X_train, X_test, y_train, y_test = train_test_split(X, labels, test_size=0.3, random_state=42)
tree = DecisionTreeClassifier()
tree.fit(X_train, y_train)
y_pred = tree.predict(X_test)
accuracy = accuracy_score(y_test, y_pred)
print("Accuracy:", accuracy)
```
5. 绘制决策树:
```python
plt.figure(figsize=(10, 8))
plot_tree(tree, filled=True)
plt.show()
```
这将输出一个决策树的图形化表示,其中每个节点表示一个决策条件,每个叶节点表示一个类别。在这个例子中,决策树的节点和叶节点均使用颜色进行区分,其中绿色表示类别0,红色表示类别1,黄色表示类别2。
阅读全文