K中心点算法(k-mediods)python代码
时间: 2024-01-22 11:04:13 浏览: 123
以下是使用Python实现K中心点算法(k-mediods)的代码示例:
```python
import numpy as np
def k_medoids(X, k):
n_samples, n_features = X.shape
# Initialize medoids randomly
medoids = np.random.choice(n_samples, size=k, replace=False)
# Assign each sample to the closest medoid
labels = np.zeros(n_samples)
for i in range(n_samples):
distances = np.sum((X[i] - X[medoids])**2, axis=1)
labels[i] = np.argmin(distances)
# Update medoids as the sample that minimizes the sum of distances
for i in range(k):
indices = np.where(labels == i)[0]
distances = np.sum((X[indices][:, np.newaxis, :] - X[np.newaxis, medoids])**2, axis=2)
new_medoid = indices[np.argmin(np.sum(distances, axis=0))]
medoids[i] = new_medoid
# Assign each sample to the closest medoid (again)
labels = np.zeros(n_samples)
for i in range(n_samples):
distances = np.sum((X[i] - X[medoids])**2, axis=1)
labels[i] = np.argmin(distances)
return medoids, labels
```
其中,输入参数X是一个numpy数组,表示待聚类的数据集,k是指定的聚类个数。函数返回medoids和labels,分别表示聚类的中心点和每个数据点所属的簇标签。
阅读全文