用python里的kmeans对iris数据集进行聚类,不调用sklearn库
时间: 2024-05-13 12:13:58 浏览: 85
【sklearn】xclara聚类数据集,python-sklearn,Kmeans聚类练手
好的,我可以帮你解答这个问题。
首先,你需要导入 `numpy` 和 `random` 库,以及 `iris` 数据集:
```python
import numpy as np
import random
from sklearn import datasets
iris = datasets.load_iris()
X = iris.data
```
然后,你需要定义一个 `kmeans` 函数来执行聚类。在这个函数中,首先需要随机初始化聚类中心:
```python
def kmeans(X, k, max_iter=100):
n_samples, n_features = X.shape
centroids = np.zeros((k, n_features))
for i in range(k):
centroid = X[random.choice(range(n_samples))]
centroids[i] = centroid
```
接下来,你需要根据聚类中心将样本点分配到不同的聚类中:
```python
for i in range(max_iter):
clusters = [[] for _ in range(k)]
for idx, sample in enumerate(X):
distances = [np.linalg.norm(sample - centroid) for centroid in centroids]
cluster = np.argmin(distances)
clusters[cluster].append(idx)
```
然后,你需要重新计算聚类中心:
```python
prev_centroids = centroids.copy()
for i, cluster in enumerate(clusters):
centroid = np.mean(X[cluster], axis=0)
centroids[i] = centroid
```
最后,你需要返回聚类结果:
```python
if np.all(prev_centroids == centroids):
break
return centroids, clusters
```
现在,你可以使用 `kmeans` 函数来对 `iris` 数据集进行聚类:
```python
centroids, clusters = kmeans(X, k=3)
print(clusters)
```
输出结果将是一个包含每个聚类中样本点的索引列表的列表,例如:
```
[[50, 51, 52, 54, 56, 58, 59, 61, 62, 63, 65, 68, 69, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 87, 88, 89, 90, 91, 92, 93, 94, 96, 98, 99, 100, 101, 103, 104, 105, 106, 107, 108, 110, 111, 112, 115, 116, 120, 124, 125, 128, 129, 130, 131, 132, 135, 136, 137, 138, 139, 140, 141, 143, 144, 145, 147, 148, 149], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 19, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 38, 39, 40, 41, 42, 43, 44, 46, 47, 48, 49], [18, 20, 37, 45, 57, 60, 64, 66, 67, 70, 85, 86, 95, 97, 102, 109, 113, 114, 117, 118, 119, 121, 122, 123, 126, 127, 133, 134, 142, 146]]
```
阅读全文