k-means对样本进行分簇

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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值