【问题标题】:How to calculate distance from cluster centroids from the outputs of Matlab kmean() function如何根据 Matlab kmean() 函数的输出计算与簇质心的距离
【发布时间】:2019-12-09 01:51:00
【问题描述】:

我有 2 个来自 k 表示 matlab 函数的输出簇
[idx,C] = kmeans(X,2);

我不知道如何使用“idx”计算质心和集群中每个点之间的距离

我想得到与质心距离>2的所有点的矩阵

% not Matlab code; just illustrating concept    

示例 c1->{x1,x2}= x1-c1=3 x2-c1=2

c2->{y1,y2}=
y1-c2=4
y2-c2=1

output={y1,x1}

【问题讨论】:

    标签: matlab distance k-means centroid


    【解决方案1】:

    试试这个方法:

    更新答案现在使用循环。

    r = randn(300,2)*5;
    r(151:end,:) = r(151:end,:) + 15;
    
    n_clusters = 2;
    
    [idx, C] = kmeans(r, n_clusters);
    
    clusters = cell(n_clusters, 1);
    distances = cell(n_clusters, 1);
    for ii = 1:n_clusters
        clusters{ii} = r(idx==ii, :);
        distances{ii} = sqrt(sum((clusters{ii}-C(ii,:)).^2,2));    
    end
    
    figure;
    subplot(1,2,1);   
    for ii = 1:n_clusters
        plot(clusters{ii}(:,1), clusters{ii}(:,2), '.');
        hold on
        plot(C(ii,1), C(ii,2), 'ko','MarkerFaceColor', 'w');
    end
    
    title('Clusters and centroids');
    
    subplot(1,2,2);
    
    for ii = 1:n_clusters
        plot(clusters{ii}(distances{ii} > 2,1), clusters{ii}(distances{ii} > 2,2), '.');
        hold on
        plot(C(ii,1), C(ii,2), 'ko','MarkerFaceColor', 'w');
    end
    title('Centroids and points with distance > 2');
    

    要获得一个包含点数大于 2 的矩阵的单元格,您可以这样做:

    distant_points = cell(n_clusters,1);
    for ii = 1:n_clusters
        distant_points{ii} = clusters{ii}(distances{ii} > 2,:)
    end
    
    

    【讨论】:

    • 非常感谢。它运作良好,我试图做的不仅仅是 for 循环中的集群,这是最好的方法吗?对于 j = 1 : 2 簇{j} = r(idx==j, :);结束 j = 1 : 2 距离{j} = sqrt(sum((cluster{j}-C(j,:)).^2,2));距离点{j} = 集群{j}(距离{j} >0.2 ,:);结束
    猜你喜欢
    • 1970-01-01
    • 2017-05-01
    • 2018-04-06
    • 2021-01-14
    • 1970-01-01
    • 2021-06-13
    • 1970-01-01
    • 2017-03-13
    • 2015-01-20
    相关资源
    最近更新 更多