Kmeans聚类算法代码
时间: 2023-07-05 07:29:37 浏览: 83
好的,以下是Kmeans聚类算法的Python代码:
```python
import numpy as np
class KMeans:
def __init__(self, k=2, max_iterations=500):
self.k = k
self.max_iterations = max_iterations
def fit(self, data):
self.centroids = []
for i in range(self.k):
self.centroids.append(data[np.random.choice(range(len(data)))])
for i in range(self.max_iterations):
clusters = [[] for _ in range(self.k)]
for point in data:
distances = [np.linalg.norm(point - centroid) for centroid in self.centroids]
cluster_index = np.argmin(distances)
clusters[cluster_index].append(point)
prev_centroids = self.centroids.copy()
for i in range(self.k):
if clusters[i]:
self.centroids[i] = np.mean(clusters[i], axis=0)
if prev_centroids == self.centroids:
break
def predict(self, data):
predictions = []
for point in data:
distances = [np.linalg.norm(point - centroid) for centroid in self.centroids]
cluster_index = np.argmin(distances)
predictions.append(cluster_index)
return predictions
```
使用示例:
```python
import matplotlib.pyplot as plt
from sklearn.datasets import make_blobs
X, y = make_blobs(n_samples=300, centers=4, cluster_std=0.60, random_state=0)
kmeans = KMeans(k=4)
kmeans.fit(X)
predictions = kmeans.predict(X)
plt.scatter(X[:, 0], X[:, 1], c=predictions, cmap='viridis')
plt.scatter(kmeans.centroids[:, 0], kmeans.centroids[:, 1], marker='*', s=300, c='black')
plt.show()
```
该代码使用KMeans算法对样本数据进行聚类,并将结果可视化展示出来。
阅读全文