Skip to content

Instantly share code, notes, and snippets.

@rreas
Created June 2, 2012 17:55
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rreas/2859353 to your computer and use it in GitHub Desktop.
Save rreas/2859353 to your computer and use it in GitHub Desktop.
Spherical K-Means Clustering
function [U,V,idx] = spkmeans(X,k,tol,imax)
[d,n] = size(X);
U = zeros(d,k);
V = zeros(k,n);
% random clusters and normalize to unit sphere.
for j = 1:n
V(randi(k),j) = 1;
X(:,j) = X(:,j) ./ norm(X(:,j));
end
% monitor convergence.
olderr = 0;
for iter = 0:imax
% recompute assignments.
if iter > 0
for i = 1:n
dots = X(:,i)' * U;
[~,ix] = max(dots);
col = zeros(k,1);
col(ix,1) = 1;
V(:,i) = col;
end
end
% monitor cost.
newerr = 0;
% update or initialize concept vectors.
for i = 1:k
ix = find(V(i,:) == 1);
m = (1/numel(ix)) * sum(X(:,ix),2);
c = m / norm(m);
U(:,i) = c;
newerr = newerr + sum(X(:,ix)' * c);
end
fprintf('Iteration %f\tCost function: %f\n', iter, newerr);
if newerr > 0 && olderr > 0 && newerr - olderr < tol
break;
end
olderr = newerr;
end
% which clusters?
[~,idx] = max(V);
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment