kmeans算法实现代码
时间: 2023-10-29 09:06:08 浏览: 78
以下是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.randint(0, len(data) - 1)])
for i in range(self.max_iterations):
clusters = {}
for j in range(self.k):
clusters[j] = []
for point in data:
distances = [np.linalg.norm(point - centroid) for centroid in self.centroids]
cluster_index = distances.index(min(distances))
clusters[cluster_index].append(point)
prev_centroids = self.centroids.copy()
for cluster_index in clusters:
self.centroids[cluster_index] = np.average(clusters[cluster_index], axis=0)
optimized = True
for j in range(self.k):
original_centroid = prev_centroids[j]
current_centroid = self.centroids[j]
if np.sum((current_centroid - original_centroid) / original_centroid * 100.0) > 0.001:
optimized = False
if optimized:
break
def predict(self, data):
distances = [np.linalg.norm(data - centroid) for centroid in self.centroids]
cluster_index = distances.index(min(distances))
return cluster_index
```
其中,`fit`方法用于训练模型,`predict`方法用于预测数据的类别。
阅读全文