k-means对样本进行分簇
题目描述
在k-means聚类算法中,更新簇心后,需要对所有样本重新进行分簇。在分簇过程中一般使用某种距离度量的方式计算样本到所有簇心的距离,并选取距离最小的簇心作为自己所在簇的簇心。请使用python实现样本的分簇。
函数接口定义:
在这里描述函数接口。例如:
clustering_samples(samples, clusters)
其中,samples是需要聚类的样本集,为一个二维列表,如:[[1, 1], [1, 2], [2, 1], [6, 4], [6, 3], [5, 4]]
clusters表示当前的不同簇的簇心,为一个二维列表,如:[[1, 1], [6, 4]]
函数返回值为各个样本对应的簇的索引组成的列表。
裁判测试程序样例:
在这里给出函数被调用进行测试的例子。例如:
import numpy as np
def clustering_samples(samples, clusters):
pass
if __name__ == "__main__":
samples = [[1, 1], [1, 2], [2, 1], [6, 4], [6, 3], [5, 4]]
clusters = [[1, 1], [6, 4]]
print(clustering_samples(samples, clusters))
/* 请在这里填写答案 */
输入样例:
在这里给出一组输入。例如:
[[1, 1], [1, 2], [2, 1], [6, 4], [6, 3], [5, 4]]
[[1, 1], [6, 4]]
输出样例:
在这里给出相应的输出。例如:
[0, 0, 0, 1, 1,1]
代码长度限制
16 KB
时间限制
400 ms
内存限制
64 MB
我的解答
#不允许用numpy
# 计算欧氏距离的平方
def euclideanDistance(listA, listB):
result = []
# 两点相减
for i in range(min(len(listA),len(listB))):
result.append(listA[i] - listB[i])
# 平方
result = [x ** 2 for x in result]
return sum(result)
def clustering_samples(samples, clusters):
lablels = []
for i in range(len(samples)):
lablels.append(-1)
min = float('inf')
for j in range(len(clusters)):
if euclideanDistance(samples[i], clusters[j]) < min:
min = euclideanDistance(samples[i], clusters[j])
lablels[i] = j
return lablels