matlab无监督分类器k-means聚类,并利用Munkres(也称匈牙利算法)进行重排

本文介绍了如何在MATLAB中使用内置的K-means算法进行无监督聚类,并展示了如何利用Munkres(匈牙利)算法对聚类结果进行优化重排。通过MNIST数据集的例子,详细阐述了聚类过程,包括K-means的输出解析、Munkres函数的实现原理以及重排算法的应用,最后给出了聚类的准确率和归一化互信息。
摘要由CSDN通过智能技术生成

matlab利用内置K-means聚类并保存结果

在matlab中,利用内置的程序进行k-means聚类是非常容易的,以下以经典的MNIST数据集为例。

data = load('datasets/MNIST.mat')
[Idx,Ctrs,SumD,D] = kmeans(data.X,10,'Replicates',4);
save('datasets/MNIST_rs.mat','Idx','Ctrs','SumD','D')

上述代码实现了读取数据集,kmeans聚类(数据集中data.X代表训练集,聚10类),保存聚类结果以便于运算的功能。聚类的输出结果如下:

Idx: N*1的向量,存储的是每个点的聚类标号
C: K*P的矩阵,存储的是K个聚类质心位置
sumD: 1*K的和向量,存储的是类间所有点与该类质心点距离之和
D: N*K的矩阵,存储的是每个点与所有质心的距离

 

Munkres函数

首先给出在matlab论坛中找到的重排函数munkres.m:

function [assignment,cost] = munkres(costMat)
% MUNKRES   Munkres Assign Algorithm 
%
% [ASSIGN,COST] = munkres(COSTMAT) returns the optimal assignment in ASSIGN
% with the minimum COST based on the assignment problem represented by the
% COSTMAT, where the (i,j)th element represents the cost to assign the jth
% job to the ith worker.
%

% This is vectorized implementation of the algorithm. It is the fastest
% among all Matlab implementations of the algorithm.

% Examples
% Example 1: a 5 x 5 example
%{
[assignment,cost] = munkres(magic(5));
[assignedrows,dum]=find(assignment);
disp(assignedrows'); % 3 2 1 5 4
disp(cost); %15
%}
% Example 2: 400 x 400 random data
%{
n=400;
A=rand(n);
tic
[a,b]=munkres(A);
toc                 % about 6 seconds 
%}

% Reference:
% "Munkres' Assignment Algorithm, Modified for Rectangular Matrices", 
% http://csclab.murraystate.edu/bob.pilgrim/445/munkres.html

% version 1.0 by Yi Cao at Cranfield University on 17th June 2008

assignment = false(size(costMat));
cost = 0;

costMat(costMat~=costMat)=Inf;
validMat = costMat<Inf;
validCol = any(validMat);
validRow = any(validMat,2);

nRows = sum(validRow);
nCols = sum(validCol);
n = max(nRows,nCols);
if ~n
    return
end
    
dMat = zeros(n);
dMat(1:nRows,1:nCols) = costMat(validRow,validCol);

%**************
  • 4
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值