-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathlitekmeans.m
486 lines (434 loc) · 15.1 KB
/
litekmeans.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
function [label, center, bCon, sumD, D] = litekmeans(X, k, varargin)
% litekmeans - K-means clustering, accelerated by matlab matrix operations
%
% FORMAT: [l, c, bc, sd, d] = litekmeans(x, k, ['PARAM', value, ...])
%
% Input fields:
%
% x SxD double matrix (samples-by-dimensions)
% k number of class labels to produce
% supported parameter/value pairs are
% 'ClusterMaxIter' - number of iterations for seed finding (10)
% 'Distance' distance measure (type) that will be minimzed, one of
% {'sqEuclidean'} - squared Euclidean distance
% 'cosine' - 1 minus the cosine of the included angle
% between points (treated as vectors); each row
% of x should be normalized to unit; if the
% intial center matrix is provided, it should
% also be normalized
% 'MaxIter' maximum number of iterations allowed (default: 100)
% 'Replicates number of times to repeat the clustering, each with a
% new set of initial centroids (default: 1; if the initial
% centroids are provided, the replicate will be set to 1)
% 'Start' method used to choose initial cluster centroids
% {'sample'} - Select K observations from X at random
% 'cluster' - Perform preliminary clustering phase on random 10%
% subsample of X; this preliminary phase is itself
% initialized using 'sample'; An additional parameter,
% 'clusterMaxIter', can be used to control the maximum
% number of iterations in each preliminary clustering
% problem
% matrix - A K-by-P matrix of starting locations; or a K-by-1
% indicate vector indicating which K points in X
% should be used as the initial center; in this case,
% you can pass in [] for K, and KMEANS infers K from
% the first dimension of the matrix
%
% Output fields:
%
% l Sx1 class/cluster labels (range 1:k)
% c KxD class/cluster centroid points
% bc boolean value indicating whether the iteration converged
% sd 1xK within-cluster sums of distances
% d SxK distances of each point to each clusters centroid
%
% Note: the algorithm partitions the points in the S-by-D data matrix, x,
% into k clusters; this partition minimizes the sum, over all
% clusters, of the within-cluster sums of point-to-cluster-centroid
% distances
% rows of x correspond to points, columns correspond to variables
% litekmeans returns an S-by-1 vector label containing the
% cluster indices of each sample/point
%
% Examples:
%
% fea = rand(500,10);
% [label, center] = litekmeans(fea, 5, 'MaxIter', 50);
%
% fea = rand(500,10);
% [label, center] = litekmeans(fea, 5, 'MaxIter', 50, 'Replicates', 10);
%
% fea = rand(500,10);
% [label, center, bCon, sumD, D] = litekmeans(fea, 5, 'MaxIter', 50);
% TSD = sum(sumD);
%
% fea = rand(500,10);
% initcenter = rand(5,10);
% [label, center] = litekmeans(fea, 5, 'MaxIter', 50, 'Start', initcenter);
%
% fea = rand(500,10);
% idx=randperm(500);
% [label, center] = litekmeans(fea, 5, 'MaxIter', 50, 'Start', idx(1:5));
%
% See also KMEANS
%
% [Cite] Deng Cai, "Litekmeans: the fastest matlab implementation of
% kmeans" - available at:
% http://www.zjucadcg.cn/dengcai/Data/Clustering.html, 2011.
% Version: v2.0
% Build: 13020213
% Date: Feb-02 2013, 1:49 PM EST
% Author: Deng Cai (dengcai AT gmail.com)
% Editor: Jochen Weber, SCAN Unit, Columbia University, NYC, NY, USA
% URL/Info: http://neuroelf.net/
% Copyright (c) 2011, Deng Cai
% All rights reserved.
% version 2.0 --December/2011
% version 1.0 --November/2011
% argument check
if nargin < 2 || ...
~isa(X, 'double') || ...
ndims(X) ~= 2 || ...
numel(k) ~= 1
error( ...
'litekmeans:TooFewInputs', ...
'At least two input arguments, x and k, required.' ...
);
end
[n, p] = size(X);
% parse optional arguments
pnames = { 'distance', 'start' , 'maxiter', 'replicates', 'onlinephase', 'clustermaxiter'};
dflts = {'sqeuclidean', 'sample', [] , [] , 'off', [] };
[eid, errmsg, distance, start, maxit, reps, online, clustermaxit] = ...
getargs(pnames, dflts, varargin{:});
if ~isempty(eid)
error(sprintf('litekmeans:%s', eid), errmsg);
end
if ischar(distance)
distNames = {'sqeuclidean','cosine'};
j = strcmpi(distance, distNames);
j = find(j);
if length(j) > 1
error('litekmeans:AmbiguousDistance', ...
'Ambiguous ''Distance'' parameter value: %s.', distance);
elseif isempty(j)
error('litekmeans:UnknownDistance', ...
'Unknown ''Distance'' parameter value: %s.', distance);
end
distance = distNames{j};
else
error('litekmeans:InvalidDistance', ...
'The ''Distance'' parameter value must be a string.');
end
center = [];
if ischar(start)
startNames = {'sample', 'cluster'};
j = find(strncmpi(start, startNames, length(start)));
if length(j) > 1
error(message('litekmeans:AmbiguousStart', start));
elseif isempty(j)
error(message('litekmeans:UnknownStart', start));
elseif isempty(k)
error('litekmeans:MissingK', ...
'You must specify the number of clusters, K.');
end
if j == 2
if floor(.1 * n) < 5 * k
j = 1;
end
end
start = startNames{j};
elseif isnumeric(start)
if size(start, 2) == p
center = start;
elseif (size(start, 2) == 1 || size(start, 1) == 1)
center = X(start, :);
else
error('litekmeans:MisshapedStart', ...
'The ''Start'' matrix must have the same number of columns as X.');
end
if isempty(k)
k = size(center, 1);
elseif (k ~= size(center, 1))
error('litekmeans:MisshapedStart', ...
'The ''Start'' matrix must have K rows.');
end
start = 'numeric';
else
error('litekmeans:InvalidStart', ...
'The ''Start'' parameter value must be a string or a numeric matrix or array.');
end
% the maximum iteration number is default 100
if isempty(maxit)
maxit = 100;
end
% the maximum iteration number for preliminary clustering phase on random
% 10% subsamples is default 10
if isempty(clustermaxit)
clustermaxit = 10;
end
% assume one replicate
if isempty(reps) || ...
~isempty(center)
reps = 1;
end
if ~(isscalar(k) && isnumeric(k) && isreal(k) && k > 0 && (round(k) == k))
error('litekmeans:InvalidK', ...
'X must be a positive integer value.');
elseif n < k
error('litekmeans:TooManyClusters', ...
'X must have more rows than the number of clusters.');
end
% initialize some outputs
bestlabel = [];
sumD = zeros(1, k);
bCon = false;
% iterate across replications
for t = 1:reps
% permute points
rs = randperm(n);
% centroid selection
switch start
% from data
case 'sample'
center = X(rs(1:k), :);
% cluster instead
case 'cluster'
[dump, center] = litekmeans(X(rs(ceil(.1 * n)), :), k, varargin{:}, ...
'start', 'sample', 'replicates', 1, 'MaxIter', clustermaxit);
% data given already!
case 'numeric'
end
% initialize counters
last = 0;
label = 1;
it = 0;
% distance measure
switch distance
% euclidean
case 'sqeuclidean'
% find labels (up to max. iterations)
while any(label ~= last) && it < maxit
% keep track of labels
last = label;
% distance computation
bb = full(sum(center .* center, 2)');
ab = full(X * center');
D = bb(ones(1, n), :) - 2 * ab;
% assign samples to the nearest centers
[val, label] = min(D, [], 2);
ll = unique(label);
% some clusters dropped ...
if length(ll) < k
missCluster = 1:k;
missCluster(ll) = [];
missNum = length(missCluster);
aa = sum(X .* X, 2);
val = aa + val;
[dump, idx] = sort(val, 1, 'descend');
label(idx(1:missNum)) = missCluster;
end
% transform label into indicator matrix
E = sparse(1:n,label,1,n,k,n);
% compute center of each cluster
center = full((E * spdiags(1 ./ sum(E, 1)', 0, k, k))' * X);
% iteration counter
it = it + 1;
end
% converged?
if it < maxit
bCon = true;
end
% assign best labels
if isempty(bestlabel)
bestlabel = label;
bestcenter = center;
% with replications?
if reps > 1
% not converged
if it >= maxit
aa = full(sum(X.*X,2));
bb = full(sum(center.*center,2));
ab = full(X*center');
D = bsxfun(@plus,aa,bb') - 2*ab;
D(D<0) = 0;
% converged
else
aa = full(sum(X.*X,2));
D = aa(:,ones(1,k)) + D;
D(D<0) = 0;
end
% distance measure
D = sqrt(D);
% compute across clusters
for j = 1:k
sumD(j) = sum(D(label==j,j));
end
bestsumD = sumD;
bestD = D;
end
% update best labels
else
% not converged
if it >= maxit
aa = full(sum(X.*X,2));
bb = full(sum(center.*center,2));
ab = full(X*center');
D = bsxfun(@plus,aa,bb') - 2*ab;
D(D<0) = 0;
% converged
else
aa = full(sum(X.*X,2));
D = aa(:,ones(1,k)) + D;
D(D<0) = 0;
end
% distance measure
D = sqrt(D);
for j = 1:k
sumD(j) = sum(D(label==j,j));
end
if sum(sumD) < sum(bestsumD)
bestlabel = label;
bestcenter = center;
bestsumD = sumD;
bestD = D;
end
end
% cosine distance
case 'cosine'
% follows logic from above
while any(label ~= last) && it < maxit
last = label;
% compute measure and assign samples to nearest center
W = full(X * center');
[val, label] = max(W, [], 2);
ll = unique(label);
if length(ll) < k
missCluster = 1:k;
missCluster(ll) = [];
missNum = length(missCluster);
[dump, idx] = sort(val);
label(idx(1:missNum)) = missCluster;
end
% transform label into indicator matrix
E = sparse(1:n, label, 1, n, k, n);
% compute center of each cluster
center = full((E * spdiags(1 ./ sum(E, 1)', 0, k, k))' * X);
centernorm = sqrt(sum(center.^2, 2));
center = center ./ centernorm(:, ones(1, p));
% iteration counter
it = it + 1;
end
if it<maxit
bCon = true;
end
if isempty(bestlabel)
bestlabel = label;
bestcenter = center;
if reps > 1
if any(label ~= last)
W = full(X * center');
end
D = 1 - W;
for j = 1:k
sumD(j) = sum(D(label == j, j));
end
bestsumD = sumD;
bestD = D;
end
else
if any(label ~= last)
W=full(X * center');
end
D = 1 - W;
for j = 1:k
sumD(j) = sum(D(label == j, j));
end
if sum(sumD) < sum(bestsumD)
bestlabel = label;
bestcenter = center;
bestsumD = sumD;
bestD = D;
end
end
end
end
% fill outputs
label = bestlabel;
center = bestcenter;
if reps > 1
sumD = bestsumD;
D = bestD;
elseif nargout > 3
switch distance
% euclidean distance measure
case 'sqeuclidean'
aa = full(sum(X .* X, 2));
if it >= maxit
bb = full(sum(center .* center, 2));
ab = full(X * center');
D = bsxfun(@plus, aa, bb') - 2 * ab;
else
D = aa(:, ones(1, k)) + D;
end
D(D < 0) = 0;
D = sqrt(D);
% cosine distance measure
case 'cosine'
if it >= maxit
W = full(X * center');
end
D = 1 - W;
end
for j = 1:k
sumD(j) = sum(D(label == j, j));
end
end
% sub-function for parsing arguments (modified from MATLAB)
function [eid, emsg, varargout] = getargs(pnames, dflts, varargin)
% original Copyright 1993-2008 The MathWorks, Inc.
% modified by Deng Cai ([email protected]) 2011.11.27
% initialize some variables
emsg = '';
eid = '';
nparams = numel(pnames);
varargout = dflts;
unrecog = {};
nargs = numel(varargin);
% must have name/value pairs
if mod(nargs, 2)~=0
eid = 'WrongNumberArgs';
emsg = 'Wrong number of arguments.';
else
% process name/value pairs
for j = 1:2:nargs
pname = varargin{j};
if ~ischar(pname)
eid = 'BadParamName';
emsg = 'Parameter name must be text.';
break;
end
i = strcmpi(pname, pnames);
i = find(i);
if isempty(i)
% if they've asked to get back unrecognized names/values, add this
% one to the list
if nargout > nparams+2
unrecog((end+1):(end+2)) = {varargin{j}, varargin{j+1}};
% otherwise, it's an error
else
eid = 'BadParamName';
emsg = sprintf('Invalid parameter name: %s.', pname);
break;
end
elseif length(i) > 1
eid = 'BadParamName';
emsg = sprintf('Ambiguous parameter name: %s.', pname);
break;
else
varargout{i} = varargin{j+1};
end
end
end
% return everything
varargout{nparams+1} = unrecog;