matlab kmeans 代码

来源:互联网 发布:js给集合添加元素 编辑:程序博客网 时间:2024/06/14 20:53

代码中包括随机数据的产生, 和kmeans的无监督学习
kmeans主要分为三步:
1. classify the different classes
2. define new center
3. stop condition
不停的进行迭代直到满足迭代次数或者是结束条件

这里的距离采用的是欧式距离

clear;% generate data% clear;% data = round(rand(100, 2)*100);% save('data','data');%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%load data1;% class number NN = 2;[row, col] = size(data);u = round(rand(N, col)*100);% max iteration 100j = 100;while(j>0)    % classify the different classes    for i=1:row        for j = 1:N            z(j) = norm(data(i,:)- u(j,:));        end        [v, index] = min(z);        c(i) = index;    end    % define new center    sum = zeros(N,col);    num = zeros(1,N);    for i =1:row        for j = 1:N            if c(i) == j                sum(j,:) = sum(j,:) + data(i,:);                num(j) = num(j) + 1;            end        end    end    for i = 1:N        ut(i,:) = sum(i,:)/num(i);    end    % stop condition     for i = 1:N        udis(i) = norm(ut(i,:)-u(i,:));    end    if max(udis) < 1e-10        break;    end    % update new center    u = ut;    j = j-1;endfor i=1:row    if c(i) == 1        plot(data(i,1),data(i,2), 'or');        hold on;    elseif c(i) == 2        plot(data(i,1),data(i,2), '+b');        hold on;    elseif c(i) == 3        plot(data(i,1),data(i,2), '*g');        hold on;    elseif c(i) == 4        plot(data(i,1),data(i,2), 'xb');        hold on;    else        plot(data(i,1),data(i,2), '.y');        hold on;    endend
0 0
原创粉丝点击