您的位置:首页 > 编程语言 > MATLAB

K-means 聚类算法MATLAB代码

2017-03-29 22:27 211 查看
%----------------------main function-----------------------------

%% Clear Memory & Command Window

clc

clear

close all

%% Generate Points

Sigma = [0.5 0.05; 0.05 0.5];

f1    = mvnrnd([0.5 0]  ,Sigma,100);

f2    = mvnrnd([0.5 0.5],Sigma,100);

f3    = mvnrnd([0.5 1]  ,Sigma,100);f4    = mvnrnd([0.5 1.5],Sigma,100);

%% K-means options

feature_vector     = F;                                 % Input

number_of_clusters = 8;                                 % Number of Clusters

Kmeans_iteration   = 40;                                % K-means Iteration

%% Test K-means

[cluster_centers, data]  = km_fun(feature_vector, number_of_clusters, Kmeans_iteration); % K-means clusterig

%% Plot

CV    = '+r+b+c+m+k+yorobocomokoysrsbscsmsksy';       % Color Vector

hold on

for i = 1 : number_of_clusters

    PT = feature_vector(data(:, number_of_clusters+1) == i, :);                % Find points of each cluster

    plot(PT(:, 1),PT(:, 2),CV(2*i-1 : 2*i), 'LineWidth', 2);                   % Plot points with determined color and shape

    plot(cluster_centers(:, 1), cluster_centers(:, 2), '*k', 'LineWidth', 7);  % Plot cluster centers

end

hold off

grid on

%----------------------subfunction----------------------------------------

%% K-means

function [CENTS, DAL] = km_fun(F, K, KMI)

CENTS = F( ceil(rand(K,1)*size(F,1)) ,:);              % Cluster Centers

DAL   = zeros(size(F,1),K+2);                          % Distances and Labels

for n = 1:KMI

        

   for i = 1:size(F,1)

      for j = 1:K  

        DAL(i,j) = norm(F(i,:) - CENTS(j,:)); % compute the distances to every centers     

      end

      [Distance, CN] = min(DAL(i,1:K));                % 1:K are Distance from Cluster Centers 1:K 

      DAL(i,K+1) = CN;                                 % K+1 is Cluster Label

      DAL(i,K+2) = Distance;                           % K+2 is Minimum Distance

   end

   for i = 1:K

      A = (DAL(:,K+1) == i);                           % Cluster K Points

      CENTS(i,:) = mean(F(A,:));                       % New Cluster Centers

      if sum(isnan(CENTS(:))) ~= 0                     % If CENTS(i,:) Is Nan Then Replace It With Random Point

         NC = find(isnan(CENTS(:,1)) == 1);            % Find Nan Centers

         for Ind = 1:size(NC,1)

         CENTS(NC(Ind),:) = F(randi(size(F,1)),:);

         end

      end

   end

end

end
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: