weighted k-means代码
时间: 2023-06-23 19:04:38 浏览: 107
下面是使用Python实现的weighted k-means算法的示例代码:
```
import numpy as np
from scipy.spatial.distance import cdist
def weighted_kmeans(X, k, weights, max_iterations=100):
# Initialize centroids randomly
centroids = X[np.random.choice(X.shape[0], k, replace=False)]
for i in range(max_iterations):
# Calculate distances between data points and centroids
distances = cdist(X, centroids, 'euclidean')
# Assign data points to nearest centroid based on weighted distances
cluster_ids = np.argmin(distances * weights[:, None], axis=1)
# Update centroids based on weighted mean of assigned data points
for j in range(k):
centroid = np.mean(X[cluster_ids == j] * weights[cluster_ids == j][:, None], axis=0)
centroids[j] = centroid
return centroids, cluster_ids
```
这个函数接收三个参数:
- X: 数据矩阵,每一行代表一个数据点。
- k: 聚类的数量。
- weights: 每个数据点的权重,应该是一个长度为X.shape[0]的向量。
函数返回两个值:
- centroids: 聚类中心的坐标矩阵,每一行代表一个中心。
- cluster_ids: 每个数据点所属的聚类的ID,应该是一个长度为X.shape[0]的向量。
阅读全文