-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path149.java
More file actions
476 lines (404 loc) · 13.2 KB
/
Copy path149.java
File metadata and controls
476 lines (404 loc) · 13.2 KB
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
/**
* [CluStream_kMeans.java]
* CluStream with k-means as macroclusterer
*
* Appeared in seminar paper "Understanding of Internal Clustering Validation Measure in Streaming Environment" (Yunsu Kim)
* for the course "Seminar: Data Mining and Multimedia Retrival" in RWTH Aachen University, WS 12/13
*
* @author Yunsu Kim
* based on the code of Timm Jansen (moa@cs.rwth-aachen.de)
* Data Management and Data Exploration Group, RWTH Aachen University
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*
*/
package moa.clusterers.clustream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;
import moa.cluster.CFCluster;
import moa.cluster.Cluster;
import moa.cluster.Clustering;
import moa.cluster.SphereCluster;
import moa.clusterers.AbstractClusterer;
import moa.core.Measurement;
import com.github.javacliparser.IntOption;
import com.yahoo.labs.samoa.instances.DenseInstance;
import com.yahoo.labs.samoa.instances.Instance;
public class WithKmeans extends AbstractClusterer {
private static final long serialVersionUID = 1L;
public IntOption timeWindowOption = new IntOption("horizon",
'h', "Rang of the window.", 1000);
public IntOption maxNumKernelsOption = new IntOption(
"maxNumKernels", 'm',
"Maximum number of micro kernels to use.", 100);
public IntOption kernelRadiFactorOption = new IntOption(
"kernelRadiFactor", 't',
"Multiplier for the kernel radius", 2);
public IntOption kOption = new IntOption(
"k", 'k',
"k of macro k-means (number of clusters)", 5);
private int timeWindow;
private long timestamp = -1;
private ClustreamKernel[] kernels;
private boolean initialized;
private List<ClustreamKernel> buffer; // Buffer for initialization with kNN
private int bufferSize;
private double t;
private int m;
public WithKmeans() {
}
@Override
public void resetLearningImpl() {
this.kernels = new ClustreamKernel[maxNumKernelsOption.getValue()];
this.timeWindow = timeWindowOption.getValue();
this.initialized = false;
this.buffer = new LinkedList<ClustreamKernel>();
this.bufferSize = maxNumKernelsOption.getValue();
t = kernelRadiFactorOption.getValue();
m = maxNumKernelsOption.getValue();
}
@Override
public void trainOnInstanceImpl(Instance instance) {
int dim = instance.numValues();
timestamp++;
// 0. Initialize
if (!initialized) {
if (buffer.size() < bufferSize) {
buffer.add(new ClustreamKernel(instance, dim, timestamp, t, m));
return;
} else {
for (int i = 0; i < buffer.size(); i++) {
kernels[i] = new ClustreamKernel(new DenseInstance(1.0, buffer.get(i).getCenter()), dim, timestamp, t, m);
}
buffer.clear();
initialized = true;
return;
}
}
// 1. Determine closest kernel
ClustreamKernel closestKernel = null;
double minDistance = Double.MAX_VALUE;
for ( int i = 0; i < kernels.length; i++ ) {
//System.out.println(i+" "+kernels[i].getWeight()+" "+kernels[i].getDeviation());
double distance = distance(instance.toDoubleArray(), kernels[i].getCenter());
if (distance < minDistance) {
closestKernel = kernels[i];
minDistance = distance;
}
}
// 2. Check whether instance fits into closestKernel
double radius = 0.0;
if ( closestKernel.getWeight() == 1 ) {
// Special case: estimate radius by determining the distance to the
// next closest cluster
radius = Double.MAX_VALUE;
double[] center = closestKernel.getCenter();
for ( int i = 0; i < kernels.length; i++ ) {
if ( kernels[i] == closestKernel ) {
continue;
}
double distance = distance(kernels[i].getCenter(), center );
radius = Math.min( distance, radius );
}
} else {
radius = closestKernel.getRadius();
}
if ( minDistance < radius ) {
// Date fits, put into kernel and be happy
closestKernel.insert( instance, timestamp );
return;
}
// 3. Date does not fit, we need to free
// some space to insert a new kernel
long threshold = timestamp - timeWindow; // Kernels before this can be forgotten
// 3.1 Try to forget old kernels
for ( int i = 0; i < kernels.length; i++ ) {
if ( kernels[i].getRelevanceStamp() < threshold ) {
kernels[i] = new ClustreamKernel( instance, dim, timestamp, t, m );
return;
}
}
// 3.2 Merge closest two kernels
int closestA = 0;
int closestB = 0;
minDistance = Double.MAX_VALUE;
for ( int i = 0; i < kernels.length; i++ ) {
double[] centerA = kernels[i].getCenter();
for ( int j = i + 1; j < kernels.length; j++ ) {
double dist = distance( centerA, kernels[j].getCenter() );
if ( dist < minDistance ) {
minDistance = dist;
closestA = i;
closestB = j;
}
}
}
assert (closestA != closestB);
kernels[closestA].add( kernels[closestB] );
kernels[closestB] = new ClustreamKernel( instance, dim, timestamp, t, m );
}
@Override
public Clustering getMicroClusteringResult() {
if (!initialized) {
return new Clustering(new Cluster[0]);
}
ClustreamKernel[] result = new ClustreamKernel[kernels.length];
for (int i = 0; i < result.length; i++) {
result[i] = new ClustreamKernel(kernels[i], t, m);
}
return new Clustering(result);
}
@Override
public Clustering getClusteringResult() {
if (!initialized) {
return new Clustering(new Cluster[0]);
}
return kMeans_rand(kOption.getValue(), getMicroClusteringResult());
}
public Clustering getClusteringResult(Clustering gtClustering) {
return kMeans_gta(kOption.getValue(), getMicroClusteringResult(), gtClustering);
}
public String getName() {
return "CluStreamWithKMeans " + timeWindow;
}
/**
* Distance between two vectors.
*
* @param pointA
* @param pointB
* @return dist
*/
private static double distance(double[] pointA, double [] pointB) {
double distance = 0.0;
for (int i = 0; i < pointA.length; i++) {
double d = pointA[i] - pointB[i];
distance += d * d;
}
return Math.sqrt(distance);
}
/**
* k-means of (micro)clusters, with ground-truth-aided initialization.
* (to produce best results)
*
* @param k
* @param data
* @return (macro)clustering - CFClusters
*/
public static Clustering kMeans_gta(int k, Clustering clustering, Clustering gtClustering) {
ArrayList<CFCluster> microclusters = new ArrayList<CFCluster>();
for (int i = 0; i < clustering.size(); i++) {
if (clustering.get(i) instanceof CFCluster) {
microclusters.add((CFCluster)clustering.get(i));
} else {
System.out.println("Unsupported Cluster Type:" + clustering.get(i).getClass() + ". Cluster needs to extend moa.cluster.CFCluster");
}
}
int n = microclusters.size();
assert (k <= n);
/* k-means */
Random random = new Random(0);
Cluster[] centers = new Cluster[k];
int K = gtClustering.size();
for (int i = 0; i < k; i++) {
if (i < K) { // GT-aided
centers[i] = new SphereCluster(gtClustering.get(i).getCenter(), 0);
} else { // Randomized
int rid = random.nextInt(n);
centers[i] = new SphereCluster(microclusters.get(rid).getCenter(), 0);
}
}
return cleanUpKMeans(kMeans(k, centers, microclusters), microclusters);
}
/**
* k-means of (micro)clusters, with randomized initialization.
*
* @param k
* @param data
* @return (macro)clustering - CFClusters
*/
public static Clustering kMeans_rand(int k, Clustering clustering) {
ArrayList<CFCluster> microclusters = new ArrayList<CFCluster>();
for (int i = 0; i < clustering.size(); i++) {
if (clustering.get(i) instanceof CFCluster) {
microclusters.add((CFCluster)clustering.get(i));
} else {
System.out.println("Unsupported Cluster Type:" + clustering.get(i).getClass() + ". Cluster needs to extend moa.cluster.CFCluster");
}
}
int n = microclusters.size();
assert (k <= n);
/* k-means */
Random random = new Random(0);
Cluster[] centers = new Cluster[k];
for (int i = 0; i < k; i++) {
int rid = random.nextInt(n);
centers[i] = new SphereCluster(microclusters.get(rid).getCenter(), 0);
}
return cleanUpKMeans(kMeans(k, centers, microclusters), microclusters);
}
/**
* (The Actual Algorithm) k-means of (micro)clusters, with specified initialization points.
*
* @param k
* @param centers - initial centers
* @param data
* @return (macro)clustering - SphereClusters
*/
protected static Clustering kMeans(int k, Cluster[] centers, List<? extends Cluster> data) {
assert (centers.length == k);
assert (k > 0);
int dimensions = centers[0].getCenter().length;
ArrayList<ArrayList<Cluster>> clustering = new ArrayList<ArrayList<Cluster>>();
for (int i = 0; i < k; i++) {
clustering.add(new ArrayList<Cluster>());
}
while (true) {
// Assign points to clusters
for (Cluster point : data) {
double minDistance = distance(point.getCenter(), centers[0].getCenter());
int closestCluster = 0;
for (int i = 1; i < k; i++) {
double distance = distance(point.getCenter(), centers[i].getCenter());
if (distance < minDistance) {
closestCluster = i;
minDistance = distance;
}
}
clustering.get(closestCluster).add(point);
}
// Calculate new centers and clear clustering lists
SphereCluster[] newCenters = new SphereCluster[centers.length];
for (int i = 0; i < k; i++) {
newCenters[i] = calculateCenter(clustering.get(i), dimensions);
clustering.get(i).clear();
}
// Convergence check
boolean converged = true;
for (int i = 0; i < k; i++) {
if (!Arrays.equals(centers[i].getCenter(), newCenters[i].getCenter())) {
converged = false;
break;
}
}
if (converged) {
break;
} else {
centers = newCenters;
}
}
return new Clustering(centers);
}
/**
* Rearrange the k-means result into a set of CFClusters, cleaning up the redundancies.
*
* @param kMeansResult
* @param microclusters
* @return
*/
protected static Clustering cleanUpKMeans(Clustering kMeansResult, ArrayList<CFCluster> microclusters) {
/* Convert k-means result to CFClusters */
int k = kMeansResult.size();
CFCluster[] converted = new CFCluster[k];
for (CFCluster mc : microclusters) {
// Find closest kMeans cluster
double minDistance = Double.MAX_VALUE;
int closestCluster = 0;
for (int i = 0; i < k; i++) {
double distance = distance(kMeansResult.get(i).getCenter(), mc.getCenter());
if (distance < minDistance) {
closestCluster = i;
minDistance = distance;
}
}
// Add to cluster
if ( converted[closestCluster] == null ) {
converted[closestCluster] = (CFCluster)mc.copy();
} else {
converted[closestCluster].add(mc);
}
}
// Clean up
int count = 0;
for (int i = 0; i < converted.length; i++) {
if (converted[i] != null)
count++;
}
CFCluster[] cleaned = new CFCluster[count];
count = 0;
for (int i = 0; i < converted.length; i++) {
if (converted[i] != null)
cleaned[count++] = converted[i];
}
return new Clustering(cleaned);
}
/**
* k-means helper: Calculate a wrapping cluster of assigned points[microclusters].
*
* @param assigned
* @param dimensions
* @return SphereCluster (with center and radius)
*/
private static SphereCluster calculateCenter(ArrayList<Cluster> assigned, int dimensions) {
double[] result = new double[dimensions];
for (int i = 0; i < result.length; i++) {
result[i] = 0.0;
}
if (assigned.size() == 0) {
return new SphereCluster(result, 0.0);
}
for (Cluster point : assigned) {
double[] center = point.getCenter();
for (int i = 0; i < result.length; i++) {
result[i] += center[i];
}
}
// Normalize
for (int i = 0; i < result.length; i++) {
result[i] /= assigned.size();
}
// Calculate radius: biggest wrapping distance from center
double radius = 0.0;
for (Cluster point : assigned) {
double dist = distance(result, point.getCenter());
if (dist > radius) {
radius = dist;
}
}
SphereCluster sc = new SphereCluster(result, radius);
sc.setWeight(assigned.size());
return sc;
}
/** Miscellaneous **/
@Override
public boolean implementsMicroClusterer() {
return true;
}
public boolean isRandomizable() {
return false;
}
public double[] getVotesForInstance(Instance inst) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
protected Measurement[] getModelMeasurementsImpl() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public void getModelDescription(StringBuilder out, int indent) {
throw new UnsupportedOperationException("Not supported yet.");
}
}