【问题标题】:C++: K-mean clustering G-MatrixC++:K-mean 聚类 G-Matrix
【发布时间】:2013-03-23 19:41:38
【问题描述】:

我是新来的,很抱歉这个“问题”对你们中的一些人来说有点太愚蠢了。 我必须在大学做一个关于 k-mean 聚类的 C++ 项目,我需要一些帮助。 这是代码。这是工作。 现在,我必须单独构建 G-Matrix。在代码中我得到以下内容:

 4.30  0.50   * 1 *
 3.54  0.50   * 1 *
 0.71  3.20   * 0 *
 0.71  4.61   * 0 *

质心坐标为:

 4.50
 3.50

质心坐标为:

1.50
1.00

这很好,但我需要像这样的额外 G-Matrix 中的 1,1,0,0:

A B C D
1 1 0 0 ->c1
0 0 1 1 ->c2  

其中A,B,C,D 是点,c1 和c2 是质心。 知道如何显示这个吗?

这是我的代码:

float dmin, dpoint;
float sum[2][2];
int cluster[4], count[4], group;
float flips;
const int rows = 4;
const int columns = 2;
const int crows = 2;
const int ccolumns = 2;

// initialize the points


int point[rows][columns]={{1,1},{2,1},{4,3},{5,4}};


// initialize the centroids

double centroid [crows][ccolumns] = {{1,1},{2,1}};


// ...

for (i = 0; i<4; i++) cluster[i] = 0;

// until there is no change of clusters belonging to each pattern, continue

flips = 4;
while (flips>0) {

    flips = 0;

    for (j = 0; j < 2; j++) 
    {
        count[j] = 0; 
        for (i = 0; i < 2; i++) 
            sum[j][i] = 0;
    }


    // now, we need to calculate the distance

    for (i = 0; i < 4; i++) {

        dmin = 2; group = cluster[i];
        for (j = 0; j < 2; j++)
        {

            dpoint = 0.0;

            dpoint +=  sqrt(pow((point[i][0] - centroid[j][0]),2)+pow((point[i][1] - centroid[j][1]),2));
            fprintf(stdout, "%5.2f ", dpoint); // Show the value of the distance
            if (dpoint < dmin) {
                group = j;
                dmin = dpoint;
            }
        }

        // now, we need to calculate the G matrix (1 or 0)

        fprintf(stdout, "  * %d *\n", group); // displays 0 or 1 (to which cluster it belongs)

        if (cluster[i] != group) 
        {
            flips++;
            cluster[i] = group; // repeat this process until G(n)=G(n+1)
        }

        count[cluster[i]]++;

        for (j = 0; j < 2; j++) 
            sum[cluster[i]][j] += point[i][j];
    }

    // now, display the coordinates of the centroid

    for (i = 0; i < 2; i++) {
        fprintf(stderr," The coordinates of the centroid are: \n");
        for (j = 0; j < 2; j++) {
            centroid[i][j] = sum[i][j]/count[i];
            fprintf(stderr, "%5.2f \n", centroid[i][j]);
        }
    }


}

}

感谢您的帮助!

【问题讨论】:

  • 在这种情况下 K 是什么?我的意思是你想分成多少个集群?
  • 在这个练习中,我有 4 个点必须分配给两个质心。我有另一个 100 点和 10 个质心的练习,所以该方法应该能够扩展...... G-Matrix 为每个点显示相应的组。所以,A B C D 1 1 0 0 ->c1 0 0 1 1 ->c2 表示 A 点和 B 点属于第一组,C 和 D 点属于第二组。

标签: c++ cluster-analysis k-means


【解决方案1】:

好吧,把你的第三列转换成 G-Matrix。

这实际上是微不足道的。该列为您提供要设置为 1 的行号。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-06-30
    • 2017-09-12
    • 2017-07-17
    • 2018-08-12
    • 2015-07-29
    • 1970-01-01
    • 2021-08-05
    • 2011-03-11
    相关资源
    最近更新 更多