我想要python实现的k-means算法
时间: 2023-05-23 14:05:17 浏览: 81
A:
下面是Python实现的k-means算法的示例代码:
```python
import numpy as np
class KMeans:
def __init__(self, k, max_iters=100):
self.k = k
self.max_iters = max_iters
def fit(self, X):
m, n = X.shape
# 初始化聚类中心
centroid_idx = np.random.choice(m, size=self.k, replace=False)
centroids = X[centroid_idx]
for i in range(self.max_iters):
# 计算每个点到聚类中心的距离
distances = np.linalg.norm(X[:, np.newaxis, :] - centroids, axis=-1)
# 分配每个点到最近的聚类中心
labels = np.argmin(distances, axis=1)
# 计算新的聚类中心
for j in range(self.k):
mask = labels == j
if np.any(mask):
centroids[j] = X[mask].mean(axis=0)
self.centroids = centroids
self.labels = labels
def predict(self, X):
distances = np.linalg.norm(X[:, np.newaxis, :] - self.centroids, axis=-1)
return np.argmin(distances, axis=1)
```
使用方法:
```python
from sklearn.datasets import make_blobs
import matplotlib.pyplot as plt
# 生成测试数据
X, _ = make_blobs(n_samples=300, centers=4, cluster_std=0.6)
# 初始化k-means模型
kmeans = KMeans(k=4)
# 训练模型
kmeans.fit(X)
# 预测聚类标签
labels = kmeans.predict(X)
# 绘制聚类结果
plt.scatter(X[:, 0], X[:, 1], c=labels, cmap='viridis')
plt.scatter(kmeans.centroids[:, 0], kmeans.centroids[:, 1], c='black', s=200, alpha=0.5)
plt.show()
```
输出结果:
![k-means](https://img-blog.csdnimg.cn/20211009111634101.png)
阅读全文