基于欧式距离的聚类代码
时间: 2023-06-09 12:08:11 浏览: 186
基于Java(UI)实现欧式距离的聚类算法的Kmeans作业【100011723】
欧氏距离聚类(也称为“k均值聚类”)的代码如下:
```python
import numpy as np
from scipy.spatial.distance import cdist
class KMeans:
def __init__(self, k=2, max_iter=100, random_state=1):
self.k = k
self.max_iter = max_iter
self.random_state = random_state
def fit(self, X):
rng = np.random.RandomState(self.random_state)
i = rng.permutation(X.shape[0])[:self.k]
self.centers = X[i]
for _ in range(self.max_iter):
z = cdist(X, self.centers).argmin(axis=1)
self.centers = np.array([X[z == k].mean(axis=0)
for k in range(self.k)])
self.labels_ = z
self.inertia_ = sum(cdist(X, self.centers, 'sqeuclidean').min(axis=1))
return self
```
这是一个使用欧氏距离进行k-均值聚类的简单示例。
阅读全文