原始数据

#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <string>
#include <algorithm>
#include <numeric>
#include <cmath>
#include <limits>

template <class T>
void ReadDataFromFile(const std::string &filename, std::vector<std::vector<T> > &vv_data) {
    std::ifstream vm_info(filename.c_str());
    T x, y;
    std::vector<T> v_data;

while(!vm_info.eof()) {
        v_data.clear();
        vm_info >> x >> y;
        v_data.push_back(x);
        v_data.push_back(y);
        vv_data.push_back(v_data);
    }
    vm_info.close();
}

template <class T>
void Display2DVector(std::vector<std::vector<T> > &vv) {
    for(size_t i=0;i<vv.size();++i) {
        for(typename::std::vector<T>::const_iterator it=vv.at(i).begin();it!=vv.at(i).end();++it) {
            std::cout<<*it<<" ";
        }
        std::cout<<"\n";
    }
    std::cout<<"--------the total of the 2DVector is "<<vv.size()<<std::endl;
}

template <class T>
void AddIndicator(std::vector<std::vector<T> > &vv, const int &k) {
    for(size_t i=0; i<vv.size(); ++i) {
        for(size_t j=0; j<k; ++j) {
            vv.at(i).push_back(0);
        }
    }
}

template <class T1, class T2>
void UpdateIndicator(std::vector<std::vector<T1> > &vv, const std::vector<T2> &u, const int &k) {
    for(size_t i=0; i<vv.size(); ++i) {
        double dis=std::numeric_limits<double>::max(), dis_min, cluster;
        for(size_t j=0; j<k; ++j) {
            dis_min=pow(vv.at(i).at(0)-u.at(j*2), 2.0)+pow(vv.at(i).at(1)-u.at(j*2+1), 2.0);
            if(dis_min < dis) {
                dis=dis_min;
                cluster=j;
            }
        }
    vv.at(i).at(cluster+2)=1;
    }
}

template <class T1, class T2>
void UpdateMeans(const std::vector<std::vector<T1> > &vv, std::vector<T2> &u, const int &k) {
    std::vector<T2> sum_set(u.size(), 0);

for(size_t i=0; i<k; ++i) {
        double sum_indi=0.0;
        for(size_t j=0; j<vv.size(); ++j) {
            sum_indi+=vv.at(j).at(i+2);
            sum_set.at(i*2)+=vv.at(j).at(i+2)*vv.at(j).at(0);
            sum_set.at(i*2+1)+=vv.at(j).at(i+2)*vv.at(j).at(1);
        }
        sum_set.at(i*2)/=sum_indi;
        sum_set.at(i*2+1)/=sum_indi;
    }
    u=sum_set;
}

template <class T1, class T2>
double DistortionMeasure(const std::vector<std::vector<T1> > &vv, const std::vector<T2> &u, const int &k) {
    double cost=0.0;
    for(size_t i=0; i<vv.size(); ++i) {
        for(size_t j=0; j<k; ++j) {
            cost+=vv.at(i).at(j+2)*(pow(vv.at(i).at(0)-u.at(j*2), 2.0)+pow(vv.at(i).at(1)-u.at(j*2+1), 2.0));
        }
    }

return cost;
}

int main() {
    int k=4;
    double mean[]={39, 42, 70, 2, 230, 10, 190, 85};
    std::vector<double> u(mean, mean+sizeof(mean)/sizeof(mean[0]));

std::string oridata="kmeans.dat";
    std::vector<std::vector<double> > vv_data;

ReadDataFromFile(oridata, vv_data);

AddIndicator(vv_data, k);

std::cout<<"the original mean: \n";
    for(std::vector<double>::const_iterator it=u.begin(); it!=u.end(); ++it) {
        std::cout<<*it<<" ";
    }
    std::cout<<std::endl;

double cost_old=std::numeric_limits<double>::max();
    while(true) {
        double cost_new=DistortionMeasure(vv_data, u, k);

if(std::abs(cost_new-cost_old)<0.0000001)
            break;

UpdateIndicator(vv_data, u, k);

UpdateMeans(vv_data, u, k);
        cost_old=cost_new;
    }

std::cout<<"the new mean: \n";
    for(std::vector<double>::const_iterator it=u.begin(); it!=u.end(); ++it) {
        std::cout<<*it<<" ";
    }
    std::cout<<std::endl;

return 0;
}

The two phases of re-assigning data points to clusters and re-computing the cluster means are repeated in turn until there is no further change in the assignments(or  until some maximum number of iterations is exceeded).

K-means (PRML) in C++的更多相关文章

  1. KNN 与 K - Means 算法比较

    KNN K-Means 1.分类算法 聚类算法 2.监督学习 非监督学习 3.数据类型:喂给它的数据集是带label的数据,已经是完全正确的数据 喂给它的数据集是无label的数据,是杂乱无章的,经过 ...

  2. 软件——机器学习与Python,聚类,K——means

    K-means是一种聚类算法: 这里运用k-means进行31个城市的分类 城市的数据保存在city.txt文件中,内容如下: BJ,2959.19,730.79,749.41,513.34,467. ...

  3. 快速查找无序数组中的第K大数?

    1.题目分析: 查找无序数组中的第K大数,直观感觉便是先排好序再找到下标为K-1的元素,时间复杂度O(NlgN).在此,我们想探索是否存在时间复杂度 < O(NlgN),而且近似等于O(N)的高 ...

  4. 网络费用流-最小k路径覆盖

    多校联赛第一场(hdu4862) Jump Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Ot ...

  5. numpy.ones_like(a, dtype=None, order='K', subok=True)返回和原矩阵一样形状的1矩阵

    Return an array of ones with the same shape and type as a given array. Parameters: a : array_like Th ...

  6. 当我们在谈论kmeans(2)

        本稿为初稿,后续可能还会修改:如果转载,请务必保留源地址,非常感谢! 博客园:http://www.cnblogs.com/data-miner/ 其他:建设中- 当我们在谈论kmeans(2 ...

  7. scikit-learn包的学习资料

    http://scikit-learn.org/stable/modules/clustering.html#k-means http://my.oschina.net/u/175377/blog/8 ...

  8. HDU 3584 Cube (三维 树状数组)

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=3584 Cube Problem Description Given an N*N*N cube A,  ...

  9. Torch7学习笔记(二)nn Package

    神经网络Package [目前还属于草稿版,等我整个学习玩以后会重新整理] 模块Module module定义了训练神经网络需要的所有基础方法,并且是可以序列化的抽象类. module有两种状态变量: ...

  10. 2016中国大学生程序设计竞赛 - 网络选拔赛 J. Alice and Bob

    Alice and Bob Time Limit: 10000/5000 MS (Java/Others)    Memory Limit: 131072/131072 K (Java/Others) ...

随机推荐

  1. C# 把时间 月 //把第一个0替换为空

    string str = "2019-01"; //name: "2019-01月" str = str.Substring(str.Length - , ); ...

  2. C# 获得星期几

    var temp = System.DateTime.Today.ToString("dddd", new System.Globalization.CultureInfo(&qu ...

  3. CPU 指令集(Instruction Set Architecture, ISA)

    本文摘自网络 概念 指令集是存储在CPU内部,对CPU运算进行指导和优化的硬程序,用来引导CPU进行加减运算和控制计算机操作系统的一系列指令集合.拥有这些指令集,CPU就可以更高效地运行.系统所下达的 ...

  4. 总结这几天js的学习内容

    对js中难点的理解 1.把变量对象像遍历数组一样简单 对于数组 ,迭代出来的是数组元素,对于对象 ,迭代出来的是对象的属性: var obj = { w: "wen", j: &q ...

  5. Ch’s gift

    Ch’s gift Time Limit: 6000/3000 MS (Java/Others)    Memory Limit: 65536/65536 K (Java/Others) Proble ...

  6. centOS下安装mysql workbench详细步骤

    step0:安装mysql 在按照workbench之前,先安装mysql.指令是 yum install mysql mysql-server mysql-libs mysql-server 关于m ...

  7. C# WPF 窗体传递消息

    对于存在窗体的WPF程序(或者说,起码在任务栏上有个图标,即ShowInTaskbar = true),互相传递消息是很容易的. 步骤: 1,寻找窗体的句柄 2,运用windows API: Send ...

  8. 洛谷 P3258 BZOJ 3631 [JLOI2014]松鼠的新家

    题目描述 松鼠的新家是一棵树,前几天刚刚装修了新家,新家有n个房间,并且有n-1根树枝连接,每个房间都可以相互到达,且俩个房间之间的路线都是唯一的.天哪,他居然真的住在”树“上. 松鼠想邀请小熊维尼前 ...

  9. CTF中编码与加解密总结

    CTF中那些脑洞大开的编码和加密 转自:https://www.cnblogs.com/mq0036/p/6544055.html 0x00 前言 正文开始之前先闲扯几句吧,玩CTF的小伙伴也许会遇到 ...

  10. Fibonacci数列(codevs 1250)

    题目描述 Description 定义:f0=f1=1, fn=fn-1+fn-2(n>=2).{fi}称为Fibonacci数列. 输入n,求fn mod q.其中1<=q<=30 ...