如果要自己设定聚类中心,并让输入的数据进行聚类该怎么做,给出代码
时间: 2024-02-19 19:58:43 浏览: 18
以下是一个简单的Python实现,以K=2为例:
```python
import numpy as np
def k_means(data, k, centroids):
# data为输入数据,k为聚类中心个数,centroids为初始聚类中心
# 迭代次数和阈值
max_iter = 100
threshold = 1e-6
# 初始化聚类中心
old_centroids = np.zeros((k, data.shape[1]))
new_centroids = centroids
for i in range(max_iter):
# 计算每个数据点到聚类中心的距离
dist = np.linalg.norm(data[:, np.newaxis, :] - new_centroids, axis=2)
# 将每个数据点分配到距离最近的聚类中心所在的簇
labels = np.argmin(dist, axis=1)
# 更新聚类中心
old_centroids[:] = new_centroids
for j in range(k):
new_centroids[j] = np.mean(data[labels == j], axis=0)
# 判断聚类中心是否变化,如果变化小于阈值则停止迭代
if np.linalg.norm(new_centroids - old_centroids) < threshold:
break
return labels
```
使用方式:
```python
data = np.array([[1, 2], [1, 4], [1, 0], [4, 2], [4, 4], [4, 0]])
k = 2
centroids = np.array([[1, 0], [4, 0]])
labels = k_means(data, k, centroids)
print(labels)
```
输出结果:
```
[0 0 0 1 1 1]
```
其中,labels为每个数据点所属的簇的索引。