根据鸢尾花数据集,利用sklearn中的方法实现k-means算法
时间: 2024-03-14 14:46:04 浏览: 25
好的,我可以为您介绍实现K-means算法的步骤:
1. 导入必要的库和数据集:
```python
from sklearn.datasets import load_iris
from sklearn.cluster import KMeans
import matplotlib.pyplot as plt
iris = load_iris()
X = iris.data
```
2. 确定k值,即聚类的数量。这里我们设定k=3。
```python
k = 3
```
3. 定义KMeans模型并进行训练:
```python
kmeans = KMeans(n_clusters=k, random_state=0)
kmeans.fit(X)
```
4. 绘制聚类结果,可以使用不同的颜色来表示不同的聚类。
```python
plt.scatter(X[:, 0], X[:, 1], c=kmeans.labels_)
plt.scatter(kmeans.cluster_centers_[:, 0], kmeans.cluster_centers_[:, 1], marker='^', s=100, linewidths=3, color='r')
plt.xlabel('Sepal length')
plt.ylabel('Sepal width')
plt.show()
```
完整的代码如下:
```python
from sklearn.datasets import load_iris
from sklearn.cluster import KMeans
import matplotlib.pyplot as plt
iris = load_iris()
X = iris.data
k = 3
kmeans = KMeans(n_clusters=k, random_state=0)
kmeans.fit(X)
plt.scatter(X[:, 0], X[:, 1], c=kmeans.labels_)
plt.scatter(kmeans.cluster_centers_[:, 0], kmeans.cluster_centers_[:, 1], marker='^', s=100, linewidths=3, color='r')
plt.xlabel('Sepal length')
plt.ylabel('Sepal width')
plt.show()
```
这样就能够基于鸢尾花数据集,利用sklearn中的方法实现k-means算法了。