K-means 聚类算法MATLAB代码

该博客展示了如何在MATLAB中使用K-means算法进行聚类。通过km_fun子函数,初始化聚类中心,计算每个样本点与中心的距离,并更新聚类中心。最后,用不同颜色和形状绘制各个聚类点及中心。
摘要由CSDN通过智能技术生成

%----------------------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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值