/
INCREMENT.py
1333 lines (919 loc) · 42.8 KB
/
INCREMENT.py
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
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os
import incUtils as utils
import incOptics as optics
import HMRF
import caffe
import random
import scipy.sparse.csgraph as csgraph
import numpy as np
from sklearn.cluster import KMeans
import sys
import gc
_VERBOSE_SILENT = 3
_VERBOSE_DEFAULT = 2
_VERBOSE_INFO = 1
_VERBOSE_DEBUG = 0
#class Cluster:
# def __init__(self,instances, representative = None): #, label=None):
# self.instances = instances
# self.representative = representative
#self.label = label
class BaseINCREMENT(object):
#Uses naive implementations of everything
def __init__(self, clustering, distance=utils.EuclideanDistance, as_array=None, symmetric_distance=True, verbose=True, **kwargs):
self.clustering = clustering
self.subclusters = []
self.representatives = [] #actual points, one for each subcluster. Indexes should be aligned with subcluster
self.feedback = [] #list of feedback. Should be clusterings of indexes of representative points
self.final = [] #store final clustering
self.distance = distance #function to determine distance between instances can be set for custom domains
self.symmetric_distance = symmetric_distance #Bool stating whether or not the distance is symmetric
self.as_array = as_array #Used to convert data to a np array
self.num_queries = 0
self.verbose = verbose
if self.verbose <= _VERBOSE_INFO:
print
print "Class:", type(self).__name__
for base in self.__class__.__bases__:
print "\t", base.__name__
print
def setInstanceDistance(func):
self.distance = func
def subcluster(self, **kwargs):
if self.verbose <= _VERBOSE_DEFAULT:
print "Subclustering:"
result = self._subcluster(**kwargs)
print "Subclusters Formed:", len(self.subclusters)
print
return result
def selectRepresentatives(self, **kwargs):
if self.verbose <= _VERBOSE_DEFAULT:
print "Selecting Representatives:"
result = self._selectRepresentatives(**kwargs)
print
return result
def generateFeedback(self, **kwargs):
if self.verbose <= _VERBOSE_DEFAULT:
print "Generating Feedback:"
result = self._generateFeedback(**kwargs)
if self.verbose <= _VERBOSE_DEFAULT:
print "Number of Queries:", self.num_queries
print
return result
def query(self, *args, **kwargs):
return self._query(*args, **kwargs)
def mergeSubclusters(self, **kwargs):
if self.verbose <= _VERBOSE_DEFAULT:
print "Merging Subclusters:"
result = self._mergeSubclusters(**kwargs)
print
return result
def _subcluster(self, **kwargs):
self.subclusters = self.clustering
def _selectRepresentatives(self, **kwargs):
self.representatives = map(lambda x: x[0],self.subclusters)
def _generateFeedback(self, **kwargs):
pass
#Actually presents a set of points to the user, and returns the feedback
#returns a list of clustered indexes into pts
def _query(self, pts, **kwargs):
self.num_queries += 1
return [[i] for i in range(len(pts))]
def _mergeSubclusters(self, **kwargs):
self.final = self.subclusters
def run(self, **kwargs):
if self.verbose <= _VERBOSE_DEFAULT:
print "Running INCREMENT:"
print
self.subcluster(**kwargs)
self.selectRepresentatives(**kwargs)
self.generateFeedback(**kwargs)
self.mergeSubclusters(**kwargs)
class CentroidINCREMENT(BaseINCREMENT):
def __init__(self, clustering, aggregator, **kwargs):
super(CentroidINCREMENT, self).__init__(clustering, **kwargs)
self.aggregator = aggregator
################################# Sub-Clustering ##########################################################
class OpticsSubclustering(BaseINCREMENT):
#performs and subclusters a single cluster of points
def performOPTICS(self, distance, minPts, display):
out = optics.OPTICS(distance, minPts)
sep = optics.separateClusters(out, minPts, display=display)
return out, sep
def breakdown(self, output, separated, indent=""):
reachability = map(lambda c: map(lambda x: x.reachability, c), output)
avgs = map(lambda c:sum(c)/len(c), reachability)
stds = map(lambda c: np.std(c), reachability)
subavgs = []
substds = []
for c, sep in enumerate(separated):
idx = 0
subavgs.append([])
substds.append([])
for i, s in enumerate(sep):
tmp = reachability[c][idx:idx+len(s)]
avg = sum(tmp)/len(tmp)
subavgs[c].append(avg)
substds[c].append(np.std(tmp))
idx += len(s)
idx = 0
print
if indent == "":
print "Subcluster Breakdown:"
for c, sub in enumerate(subavgs):
print indent + "\t%d: %f (%d)" % (c, avgs[c], sum(map(len, separated[c])))
for i, a in enumerate(sub):
print indent + "\t\t%d: %f -- %f (%d)" % (idx, a, substds[c][i], len(separated[c][i]))
idx += 1
print indent + "\t--> std: %f -- %f" % (stds[c], np.std(substds[c]))
print
print indent + "\tAvg: %f -- %f " % (sum(avgs)/len(avgs), np.std(avgs))
print indent + "\tStd: %f -- %f " % (sum(stds)/len(stds), np.std(stds))
#print indent + "Subclusters Formed:", len(self.subclusters)
print
# assumes separated in of the form [Partition][subcluster][OPTICS POINT]
def mapSeparated(self, separated):
subclusters = []
for c,sep in enumerate(separated):
ids = map(lambda sc: map(lambda x: x._id, sc), sep)
lengths = []
for sub in ids:
clust = []
for i in sub:
clust.append(self.clustering[c][i])
lengths.append(len(clust))
subclusters.append(clust)
return subclusters
#Performs OPTICS to subcluster the current clustering
def _subcluster(self, minPts=5, display=False, **kwargs):
self.subclusters = []
if self.verbose <= _VERBOSE_INFO:
print "Computing Distance"
distances = map(lambda x:utils.pairwise(x,self.distance, self.symmetric_distance), self.clustering) #N^2 where N is the number of instances per cluster -- SLOW
if self.verbose <= _VERBOSE_INFO:
print "Running OPTICS: minPts = %d" % (minPts)
output, separated = zip(*map(lambda d: self.performOPTICS(d, minPts, display), distances))
self.subclusters = self.mapSeparated(separated)
if self.verbose <= _VERBOSE_INFO:
self.breakdown(output,separated)
class RecursiveOPTICS(OpticsSubclustering):
#Return of the format Output, subclusters
#subclusters: [Subcluster][OPTIC POINT]
def performOPTICS(self, distance, minPts, display, level = 0, minPtsMin = 3):
#minPts = len(distance)/10
if minPts < minPtsMin:
minPts = minPtsMin
indent = "\t"*level
start = len(distance)
curried = lambda d: super(RecursiveOPTICS, self).performOPTICS(d, minPts, display)
output, subclusters = curried(distance) # Has bug, if there is only a single point, it isnt put in a subcluster
if self.verbose <= _VERBOSE_DEBUG:
print indent + "{%d} Begin (%d): %d" % (level, start, minPts)
if len(subclusters) == 0:
if self.verbose <= _VERBOSE_DEBUG:
print indent + "{%d} End Single" % (level)
return output, [output[:]]
#Base Case -- Return when there is only a single subcluster
if len(subclusters) == 1:
#return output, subclusters # Uncomment to recurse a single subclsuter
if minPts <= minPtsMin or start < 2 or level > 10:
if self.verbose <= _VERBOSE_DEBUG:
print indent + "{%d} Indivisable" % (level)
return output, subclusters
else:
#return super(RecursiveOPTICS, self).performOPTICS(distance, minPts/2, display)
output, subclusters = self.performOPTICS(distance, minPts/2, display, level + 1)
if self.verbose <= _VERBOSE_DEBUG:
print indent + "{%d} End Reduce (%d) : %d" % (level, start, minPts)
return output, subclusters
#Intermediate case
#parse out ids
idxs = map(lambda sub: map(lambda s: s._id, sub), subclusters)
distance = np.array(distance)
dist = []
#Filter distances
for sub in idxs:
dist.append(distance[np.ix_(sub,sub)])
#if minPts > 2:
# minPts = minPts/2
#Recursive step
try:
out, sep = zip(*map(lambda d: self.performOPTICS(d, minPts, display, level+1), dist))
except ValueError:
print "Value Error"
print "distance", len(distance)
print "Dists:", map(len,dist)
print "Minpts:", minPts
print "output:", output
print "subclusters:", subclusters
sys.exit()
#translate sep indexes back
sep = list(sep)
#if self.verbose <= _VERBOSE_INFO:
# self.breakdown(out, sep, indent=indent)
#print "idxs", idxs
#print sep
result = []
for i, p in enumerate(sep):
for sub in p:
for s in sub:
s._id = idxs[i][s._id]
result.append(sub)
#print "result", result
out = [i for x in out for i in x]
lens = map(len, result)
end = sum(lens)
if self.verbose <= _VERBOSE_DEBUG:
print indent + "{%d} End (%d)" % (level, end)
if start != end:
print indent + "Points Given:", start
print indent + "Points Returning:", end
print indent + "Error: Missing Points"
indent += "\t"
print indent + "idsx", idxs
print indent + "sep", sep
print indent + "dists:", map(len,dist)
print indent + "results:", lens
return out, result
################################# Representative Selection #################################################
class MedoidSelector(BaseINCREMENT):
def _selectRepresentatives(self, **kwargs):
self.representatives = []
distances = map(lambda sc: utils.pairwise(sc, self.distance, self.symmetric_distance), self.subclusters)
reps = []
for i, dist in enumerate(distances):
sums = map(sum, dist)
m = utils.arg_min(sums)
reps.append(m)
self.representatives.append(self.subclusters[i][m])
if self.verbose <= _VERBOSE_INFO:
print "Representatives:"
print reps
print
class RandomSelector(BaseINCREMENT):
def selectRepresentattives(self, **kwargs):
self.representatives = []
for sub in self.subclusters:
self.representatives.appen(random.choice(sub))
if self.verbose <= _VERBOSE_INFO:
print "Representatives:"
print reps
print
class CentroidSelector(CentroidINCREMENT):
def _selectRepresentatives(self, **kwargs):
self.representatives = []
reps = map(self.aggregator, self.subclusters)
self.representatives = reps
'''
print "Representatives:"
print self.representatives
print
'''
################################# Query Ordering #################################################
#Base Feedback class. Simply queries for the label of each point individually and sets feedback accordingly.
class AssignmentFeedback(BaseINCREMENT):
def printFeedback(self, feedback):
print "Feedback:", len(feedback)
for f in feedback:
print "\t", f
#Organizes and manages the presentation of representatives and user feedback
def _generateFeedback(self, **kwargs):
if self.verbose <= _VERBOSE_INFO:
print "Assignment Query"
labels = {}
for r,rep in enumerate(self.representatives):
lbl = self.query([rep], **kwargs)
if lbl not in labels:
labels[lbl] = []
labels[lbl].append(r)
feedback = []
for lbl, cluster in labels.items():
feedback.append([cluster])
self.feedback = feedback
if self.verbose <= _VERBOSE_INFO:
self.printFeedback(feedback)
print
print "Number of Assignement Queries: %d" % (self.num_queries)
print
class MinimumDistanceFeedback(AssignmentFeedback):
#Distances should be the pairwise distances between the representatives
def _generateFeedback(self, distances, query_size=9, times_presented=1, num_queries=None, **kwargs):
if times_presented == None:
times_presented=1
#can only perform matching if query_size > 1
if(query_size == 1):
super(MinimumDistanceFeedback, self).generateFeedback(**kwargs)
return
#include index to retrieve the actual point after sorting
rep_distances = map(lambda d: zip(d, range(len(d))) , distances )
queue = range(len(self.representatives))
#list of indexes that have been queried
queried = {}
#initialize queried
for i in queue:
queried[i] = 0
feedback = []
while len(queue) > 0 and (num_queries == None or len(feedback) < num_queries):
i = queue[0]
del queue[0]
#skip points already queried
if queried[i] >= times_presented:
continue
dist = sorted(rep_distances[i][:])
#ensure we dont ask for too many points
size = query_size
if (len(dist) < size):
size = len(dist)
pt_idx = map(lambda d: d[1], dist[:query_size])
pts = map(lambda x: self.representatives[x], pt_idx)
q = self.query(pts, **kwargs)
feedback.append(map(lambda c: map(lambda x: pt_idx[x], c), q)) #translate pt indexes to the indexes of the representatives
#add pts to index to avoid querying again
for idx in pt_idx:
queried[idx] += 1
self.feedback = feedback
if self.verbose <= _VERBOSE_INFO:
self.printFeedback(feedback)
'''
print
print "Number of Queries: %d of size %d" % (self.num_queries, query_size)
print
'''
class FarthestFirstFeedback(AssignmentFeedback):
def __init__(self, *args, **kwargs):
super(FarthestFirstFeedback, self).__init__(*args, **kwargs)
self.overlap=True
def singleLink(self, distances, group):
minimum = None
for g in group:
v = distances[g]
if minimum == None or v < minimum:
minimum = v
return minimum
def findMax(self, presented, unpresented, paired_distances):
distances = map(lambda p: (self.singleLink(paired_distances[p], presented), p),unpresented)
m = max(distances)
return m[1], m[0][1]
def presentQuery(self, pt_idx, **kwargs):
pts = map(lambda x: self.representatives[x], pt_idx)
response = self.query(pts, **kwargs)
return map(lambda c: map(lambda x: pt_idx[x], c), response) #translate pt indexes to the indexes of the representatives
def postProcess(self, feedback):
return feedback
def _generateFeedback(self, query_size=1, num_queries=None, **kwargs):
'''
if(query_size == 1):
super(FarthestFirstFeedback, self).generateFeedback(**kwargs)
return
raise Error("Query Size")
'''
if (self.verbose <= _VERBOSE_INFO):
print "Farthest First"
if self.verbose <= _VERBOSE_DEFAULT:
print "Computing pairwise distances between representatives."
distances = utils.pairwise(self.representatives, self.distance, self.symmetric_distance)
rep_distances = map(lambda d: zip(d, range(len(d))) , distances)
feedback = []
toPresent = set()
presented = set()
unpresented = range(len(self.representatives))
q = 0
if self.verbose <= _VERBOSE_DEFAULT:
print "Beginning Queries"
while (len(unpresented) > 0 and (num_queries == None) or (q < num_queries)):
if len(presented) == 0:
pt = random.choice(unpresented)
unpresented.remove(pt)
toPresent.add(pt)
presented.add(pt)
else:
pt, closest = self.findMax(presented, unpresented, rep_distances)
unpresented.remove(pt)
presented.add(pt)
toPresent.add(pt)
if self.overlap and len(toPresent) < query_size:
toPresent.add(closest)
if len(toPresent) % query_size == 0:
feedback.append(self.presentQuery(list(toPresent), **kwargs))
q += 1
if self.verbose <= _VERBOSE_DEBUG:
print "Queried", q
toPresent = set()
if (len(toPresent) > 0 and (num_queries == None) or (q < num_queries)):
feedback.append(self.presentQuery(list(toPresent), **kwargs))
q += 1
toPresent = set()
self.num_queries = q
self.feedback = self.postProcess(feedback)
if self.verbose <= _VERBOSE_INFO:
self.printFeedback(feedback)
'''
print
print "Number of Queries: %d of size %d" % (self.num_queries, query_size)
print
'''
class FarthestLabelFeedback(FarthestFirstFeedback):
def __init__(self, *args, **kwargs):
super(FarthestLabelFeedback, self).__init__(*args, **kwargs)
self.overlap=False
def presentQuery(self, pt_idx, **kwargs):
pts = map(lambda x: self.representatives[x], pt_idx)
lbls = {}
for i,pt in enumerate(pts):
response = self.query([pt], **kwargs)
if response not in lbls:
lbls[response] = []
lbls[response].append(pt_idx[i])
return lbls
def postProcess(self, feedback):
lbls = {}
for f in feedback:
for k,v in f.items():
if k not in lbls:
lbls[k] = set()
lbls[k].update(v)
response = []
for k,s in lbls.items():
response.append(list(s))
return [response]
class LinkFeedback(AssignmentFeedback):
def completeLink(self, distances, pt, group):
dist = []
for g in group:
dist.append(distances[g])
return max(dist)
#Distances should be the pairwise distances between the representatives
def _generateFeedback(self, distances, query_size=9, times_presented=2, num_queries=None, **kwargs):
if times_presented == None:
times_presented = 2
#can only perform matching if query_size > 1
if(query_size == 1):
super(LinkFeedback, self).generateFeedback(**kwargs)
return
#include index to retrieve the actual point after sorting
rep_distances = map(lambda d: zip(d, range(len(d))) , distances )
feedback = []
#How often a point has been presented
presented = [0] * len(distances)
focusPoints = []
focus = random.choice(range(len(presented)))
candidates = set([focus])
while(num_queries == None or self.num_queries < num_queries):
dist = sorted(rep_distances[focus][:])
#Try to present what has not been presented too many times
toPresent = filter(lambda p: presented[p[1]] < times_presented,dist)
#print "Focus:", focus
#ensure we dont ask for too many points
size = query_size
if (len(toPresent) < size):
#print "Not enough unPresented Points"
#if we need more points, take it from the presented points
_presented = filter(lambda p: presented[p[1]] >= times_presented,dist)
#print "unpresented:", map(lambda d: d[1], toPresent[:size])
diff = size - len(toPresent)
#Ensure we have enough points to present
if(len(_presented) < diff):
diff = len(_presented)
#print "Already presented:", map(lambda d: d[1], _presented[:diff])
toPresent += _presented[:diff]
size = len(toPresent)
#translate point index to points
pt_idx = map(lambda d: d[1], toPresent[:size])
pts = map(lambda x: self.representatives[x], pt_idx)
#print "pt_idx:", pt_idx
#Query
q = self.query(pts, **kwargs)
feedback.append(map(lambda c: map(lambda x: pt_idx[x], c), q)) #translate pt indexes to the indexes of the representatives
#Count the points as presented
for p in pt_idx:
presented[p] += 1
candidates.add(p)
#print "presented:", presented
#print "Times_Presented:", times_presented
#update candidates
update = filter(lambda p: presented[p] < times_presented, candidates)
candidates = set(update)
#print "Candidates:", candidates
focusPoints.append(focus)
#print "FocusPoints:", focusPoints
if(len(update) == 0):
left = filter(lambda p: presented[p] < times_presented/2, range(len(presented)))
if len(left) == 0:
break
focus = random.choice(left)
continue
#find new focus
linkDist = sorted(map(lambda p: (self.completeLink(distances[p],p, focusPoints),p), candidates))
focus = linkDist[-1][1]
'''
print "LinkDist:", linkDist
print "NextFocus:", focus
print
print
'''
self.feedback = feedback
if self.verbose <= _VERBOSE_INFO:
self.printFeedback(feedback)
print
print "Number of Queries: %d of size %d" % (self.num_queries, query_size)
left = filter(lambda p: presented[p] < times_presented, range(len(presented)))
if self.verbose <= _VERBOSE_INFO:
if len(left) != 0:
print "Missed Points:", left
print
class RandomMatchingFeedback(AssignmentFeedback):
def _generateFeedback(self, query_size=9, num_queries=15, **kwargs):
if(query_size == 1):
super(MatchingFeedback, self).generateFeedback(**kwargs)
return
feedback = []
for i in range(num_queries):
pt_idx = random.sample(range(len(self.representatives)), query_size)
pts = map(lambda x: self.representatives[x], pt_idx)
q = self.query(pts, **kwargs)
feedback.append(map(lambda c: map(lambda x: pt_idx[x], c), q)) #translate pt indexes to the indexes of the representatives
self.feedback = feedback
if self.verbose <= _VERBOSE_INFO:
self.printFeedback(feedback)
'''
print
print "Number of Queries: %d of size %d" % (self.num_queries, query_size)
'''
class ClosestPointFeedback(MinimumDistanceFeedback):
#Organizes and manages the presentation of representatives and user feedback
def _generateFeedback(self, **kwargs):
distances = utils.pairwise(self.representatives, self.distance, self.symmetric_distance)
super(ClosestPointFeedback,self).generateFeedback(distances, **kwargs)
#distances should be the pairwise distances between the reps
class FarthestLinkFeedback(LinkFeedback):
#Organizes and manages the presentation of representatives and user feedback
def _generateFeedback(self, **kwargs):
distances = utils.pairwise(self.representatives, self.distance, self.symmetric_distance)
super(FarthestLinkFeedback,self).generateFeedback(distances, **kwargs)
class MinimumSpanningTreeFeedback(MinimumDistanceFeedback):
#Organizes and manages the presentation of representatives and user feedback
def _generateFeedback(self, **kwargs):
distances = utils.pairwise(self.representatives, self.distance, self.symmetric_distance)
mst = csgraph.minimum_spanning_tree(distances)
distances = csgraph.shortest_path(mst,method="D", directed=False)
super(MinimumSpanningTreeFeedback, self). generateFeedback(distances, **kwargs)
class DistanceFeedback(MinimumDistanceFeedback):
#Organizes and manages the presentation of representatives and user feedback
def _generateFeedback(self, **kwargs):
distances = utils.pairwise(self.representatives, self.distance, self.symmetric_distance)
distances = csgraph.shortest_path(distances,method="D", directed=self.symmetric_distance)
super(MinimumDistanceFeedback, self). generateFeedback(distances, **kwargs)
################################# Query #################################################
#If only a single point is presented, return it's label
class OracleMatching(BaseINCREMENT):
#Cheats and looks at target. Simulates a perfect user.
#labeler is a function that accepts an instance and returns its label
def _query(self, pts, labeler=None, **kwargs):
#if no labeling function is provided, default to parent implementation
if labeler == None:
raise("Labeler not provided.")
self.num_queries += 1
#If only 1 point, this is an assignment query. i.e. return it's label.
if(len(pts) == 1):
return labeler(pts[0])
#dictionary from label to point index
clusters = {}
#list for unknown points
unknown = []
for i,p in enumerate(pts):
label = labeler(p)
if label == None:
unknown.append(i)
continue
if label in clusters:
clusters[label].append(i)
else:
clusters[label] = [i]
#Separate from dictionary
feedback = []
#print "Query:"
for label, points in clusters.items():
#print "\tLabel [%s]: %s" % (str(label), str(points))
feedback.append(points)
#print "\tUnknown:", unknown
for point in unknown:
feedback.append([point])
return feedback
################################# Merging #################################################
class MergeSubclusters(BaseINCREMENT):
def mergeFeedback(self, feedback):
flattened = []
for f in feedback:
flattened += f
#print "flattened Feedback:"
#print "\t", feedback
sets = map(set, flattened)
changed = True
while changed:
changed = False
for i,x in enumerate(sets):
for j,y in enumerate(sets):
if i >= j:
continue
if(not x.isdisjoint(y)):
x.update(y)
del sets[j] #double check this. If j doesnt get updated correctly, will cause problem
changed = True
feedback = []
for s in sets:
f = list(s)
feedback.append(f)
return feedback
def _mergeSubclusters(self, **kwargs):
self.final = []
feedback = self.mergeFeedback(self.feedback)
for f in feedback:
cluster = []
for i in f:
cluster += self.subclusters[i]
self.final.append(cluster)
flattened = [x for i in feedback for x in i]
r = range(len(self.representatives))
for i in r:
if i not in flattened:
self.final.append(self.subclusters[i])
if self.verbose <= _VERBOSE_INFO:
print "Merged Feedback:"
for i, f in enumerate(sorted(map(sorted,feedback))):
print "\t", i, ":", f
print
class HRMFMerge(CentroidINCREMENT,MergeSubclusters):
def _mergeSubclusters(self, **kwargs):
M = []
C = []
for f in self.feedback:
for i,x in enumerate(f):
for j,y in enumerate(f):
#only handle symmetry
if j < i:
continue
if i == j:
#Must Links
for s,a in enumerate(x):
for t,b in enumerate(y):
if s <= t:
continue
if([a,b] not in M and [b,a] not in M):
M.append([a,b])
else:
#Connot Links
for s,a in enumerate(x):
for t,b in enumerate(y):
if([b,a] not in C and [a,b] not in C):
C.append([a,b])
#print "M:", sorted(map(sorted,M))
#print
#print "C:", sorted(map(sorted,C))
#print
feedback = self.mergeFeedback(self.feedback)
if self.verbose <= _VERBOSE_INFO:
print "Merged Feedback:"
print "\t", sorted(map(sorted,feedback))
print
hmrf = HMRF.HMRF(self.distance, self.aggregator)
clusters = hmrf.cluster(self.representatives,M,C, feedback)
if self.verbose <= _VERBOSE_INFO:
print
print "Clustered Representatives:", sorted(map(sorted,clusters))
print
self.final = []
for i in clusters:
cluster = []
for x in i:
cluster += self.subclusters[x]
self.final.append(cluster)
class SiameseMerging (MergeSubclusters):
def __init__(self, *args, **kwargs):
super(SiameseMerging, self).__init__(*args, **kwargs)
self.batch_size = 10
self.output_size = 100