您的位置首页 >综合 > 科技资讯 >

🎨数据分析小技巧:用K-means玩转聚类分析🎉

导读 在数据科学的世界里,K-means聚类是一种简单却强大的无监督学习算法,广泛应用于市场细分、图像压缩和模式识别等领域。🌟它的核心思想是将...

在数据科学的世界里,K-means聚类是一种简单却强大的无监督学习算法,广泛应用于市场细分、图像压缩和模式识别等领域。🌟它的核心思想是将数据集划分为K个簇,每个簇由距离最近的中心点定义。

首先,让我们看看K-means的伪代码骨架:

1️⃣ 初始化K个质心

2️⃣ 分配每个样本到最近的质心

3️⃣ 更新质心为所属簇样本的平均值

4️⃣ 重复步骤2-3直到质心不再变化

现在,用Python实现它👇

```python

import numpy as np

def k_means(data, k=2):

centroids = data[np.random.choice(data.shape[0], k, replace=False)]

while True:

clusters = [[] for _ in range(k)]

for point in data:

dist = np.linalg.norm(point - centroids, axis=1)

cluster_idx = np.argmin(dist)

clusters[cluster_idx].append(point)

new_centroids = [np.mean(cluster, axis=0) for cluster in clusters]

if np.allclose(centroids, new_centroids):

break

centroids = new_centroids

return centroids, clusters

```

掌握K-means后,你就能轻松挖掘数据背后的秘密啦!🚀

版权声明:本文由用户上传,如有侵权请联系删除!