K-Means的核心思想
初始化簇中心
代价函数
代码实现
J = zeros(100,1);
M = size(X,1);
min = inf;
for i = 1:100
%随机取k个样本点作为簇中心
randidx = randperm(M);
initial_centroids = X(randidx(1:K),:);
%将所得的中心点进行训练
[centroids0, idx] = runkMeans(X, initial_centroids,10);
for k = 1:M
J(i) = J(i) + sum((X(k,:) - centroids0(idx(M),:)).^2);
end
%取最小代价为样本中心点
if(min > J(i))
centroids =centroids0;
end
end
簇分配
tmp = zeros(K,1);
for i = 1:size(X,1)
for j = 1:K
tmp(j) = sum((X(i,:) - centroids(j,:)).^2);
end
[mins,index]=min(tmp);
idx(i) = index;
end
簇中心移动
for i = 1:m
centroids(idx(i),:) = centroids(idx(i),:) + X(i,:);
end
for j = 1:K
centroids(j,:) = centroids(j,:)/sum(idx == j);
end
图片压缩
% 加载图片
A = double(imread('dragonfly.jpg'));
% 特征缩减
A = A / 255;
img_size = size(A);
X = reshape(A, img_size(1) * img_size(2), 3);
K = 16;
max_iters = 10;
%开始训练模型
initial_centroids = kMeansInitCentroids(X, K);
[centroids, idx] = runkMeans(X, initial_centroids, max_iters);
%开始压缩图片
idx = findClosestCentroids(X, centroids);
X_recovered = centroids(idx,:);
X_recovered = reshape(X_recovered, img_size(1), img_size(2), 3);
%输出所压缩的图片
subplot(1, 2, 2);
imagesc(X_recovered)