【人工智能】无监督学习-Kmeans聚类

 

/**
 * @brief 进行一次聚类迭代, 获得新聚类中心点数组
 * 
 * @param points 所有点的数组
 * @param last 上一次的聚类中心点的数组
 * @return 新聚类中心点数组
 */
vector<Point> update(vector<Point> &points, const vector<Point> &last){
    int k=last.size();
    vector<vector<Point>>cluster(k);
    for(auto &p:points){//注意auto的使用,浅拷贝
        vector<double>dis(k);
        for(int i=0;i<k;i++){
            dis[i]=p.distance(last[i]);
        }
        int idx=0;
        for(int i=1;i<k;i++){
            if(dis[i]<dis[idx])idx=i;
        }
        p.groupId=idx;
        cluster[idx].push_back(p);
    }
    int dimension=points[0].coordinate.size();
    vector<Point>newCenters(k);
    for(int i=0;i<k;i++){
        Point center;
        for(int j=0;j<dimension;j++){
            double sum=0;//
            for(auto &p:cluster[i]){
                sum+=p.coordinate[j];
            }
            center.coordinate.push_back(sum/cluster[i].size());
        }
        center.groupId=i;
        newCenters[i]=center;
    }
    return newCenters;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值