实现Kmeans聚类,并实现可视化聚类结果
时间: 2024-06-01 07:11:47 浏览: 102
以下是一个Python实现Kmeans聚类的示例代码,同时使用matplotlib库可视化聚类结果:
```python
import numpy as np
import matplotlib.pyplot as plt
# 生成测试数据
np.random.seed(42)
X = np.random.rand(50, 2)
# 定义Kmeans类
class KMeans:
def __init__(self, k=2, max_iterations=500):
self.k = k
self.max_iterations = max_iterations
def fit(self, data):
self.centroids = data[np.random.choice(len(data), self.k, replace=False)]
for i in range(self.max_iterations):
self.labels = np.argmin(np.sqrt(((data - self.centroids[:, np.newaxis])**2).sum(axis=2)), axis=0)
new_centroids = np.array([data[self.labels == j].mean(axis=0) for j in range(self.k)])
if np.allclose(self.centroids, new_centroids):
break
self.centroids = new_centroids
def predict(self, data):
return np.argmin(np.sqrt(((data - self.centroids[:, np.newaxis])**2).sum(axis=2)), axis=0)
# 初始化Kmeans类并进行聚类
kmeans = KMeans(k=2)
kmeans.fit(X)
# 可视化聚类结果
plt.scatter(X[:, 0], X[:, 1], c=kmeans.labels)
plt.scatter(kmeans.centroids[:, 0], kmeans.centroids[:, 1], marker='*', s=300, c='r')
plt.show()
```
在此示例中,我们生成了50个二维随机数据点,然后使用Kmeans聚类将其分为两个簇。最终的可视化结果如下图所示:
![Kmeans聚类可视化结果](https://i.imgur.com/h8yv1iM.png)
阅读全文