写一个k-means应用的python代码
时间: 2024-05-09 16:14:19 浏览: 72
好的,下面是一个简单的k-means聚类应用的Python代码:
```python
import numpy as np
import matplotlib.pyplot as plt
class KMeans:
def __init__(self, k=2, max_iterations=500):
self.k = k
self.max_iterations = max_iterations
def fit(self, X):
self.centroids = X[np.random.choice(range(len(X)), self.k, replace=False)]
for i in range(self.max_iterations):
clusters = [[] for _ in range(self.k)]
for x in X:
distances = [np.linalg.norm(x - c) for c in self.centroids]
cluster_index = np.argmin(distances)
clusters[cluster_index].append(x)
prev_centroids = self.centroids.copy()
for i, cluster in enumerate(clusters):
if len(cluster) == 0:
continue
self.centroids[i] = np.mean(cluster, axis=0)
if np.allclose(prev_centroids, self.centroids):
break
def predict(self, X):
distances = [np.linalg.norm(X - c, axis=1) for c in self.centroids]
cluster_index = np.argmin(distances, axis=0)
return cluster_index
# 生成数据
np.random.seed(42)
X = np.random.randn(100, 2)
X[:50] += 3
# 进行聚类
kmeans = KMeans(k=2)
kmeans.fit(X)
# 可视化结果
plt.scatter(X[:, 0], X[:, 1], c=kmeans.predict(X))
plt.scatter(kmeans.centroids[:, 0], kmeans.centroids[:, 1], marker='x', s=200, linewidths=3, color='r')
plt.show()
```
这个代码实现了一个简单的K-Means聚类算法,并用于对一个二维数据集进行聚类。您可以通过修改数据集和聚类数量来测试不同的聚类效果。
阅读全文