/
hierarchy.py
3036 lines (2471 loc) · 111 KB
/
hierarchy.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
"""
-----------------------------------------
Hierarchical Clustering Library for Scipy
Copyright (C) Damian Eads, 2007-2008.
All Rights Reserved.
New BSD License
-----------------------------------------
Flat cluster formation
fcluster forms flat clusters from hierarchical clusters.
fclusterdata forms flat clusters directly from data.
leaders singleton root nodes for flat cluster.
Agglomerative cluster formation
linkage agglomeratively clusters original observations.
single the single/min/nearest algorithm. (alias)
complete the complete/max/farthest algorithm. (alias)
average the average/UPGMA algorithm. (alias)
weighted the weighted/WPGMA algorithm. (alias)
centroid the centroid/UPGMC algorithm. (alias)
median the median/WPGMC algorithm. (alias)
ward the Ward/incremental algorithm. (alias)
Distance matrix computation from a collection of raw observation vectors
pdist computes distances between each observation pair.
squareform converts a sq. D.M. to a condensed one and vice versa.
Statistic computations on hierarchies
cophenet computes the cophenetic distance between leaves.
from_mlab_linkage converts a linkage produced by MATLAB(TM).
inconsistent the inconsistency coefficients for cluster.
maxinconsts the maximum inconsistency coefficient for each cluster.
maxdists the maximum distance for each cluster.
maxRstat the maximum specific statistic for each cluster.
to_mlab_linkage converts a linkage to one MATLAB(TM) can understand.
Visualization
dendrogram visualizes linkages (requires matplotlib).
Tree representations of hierarchies
cnode represents cluster nodes in a cluster hierarchy.
lvlist a left-to-right traversal of the leaves.
totree represents a linkage matrix as a tree object.
Distance functions between two vectors u and v
braycurtis the Bray-Curtis distance.
canberra the Canberra distance.
chebyshev the Chebyshev distance.
cityblock the Manhattan distance.
correlation the Correlation distance.
cosine the Cosine distance.
dice the Dice dissimilarity (boolean).
euclidean the Euclidean distance.
hamming the Hamming distance (boolean).
jaccard the Jaccard distance (boolean).
kulsinski the Kulsinski distance (boolean).
mahalanobis the Mahalanobis distance.
matching the matching dissimilarity (boolean).
minkowski the Minkowski distance.
rogerstanimoto the Rogers-Tanimoto dissimilarity (boolean).
russellrao the Russell-Rao dissimilarity (boolean).
seuclidean the normalized Euclidean distance.
sokalmichener the Sokal-Michener dissimilarity (boolean).
sokalsneath the Sokal-Sneath dissimilarity (boolean).
sqeuclidean the squared Euclidean distance.
yule the Yule dissimilarity (boolean).
Predicates
is_valid_dm checks for a valid distance matrix.
is_valid_im checks for a valid inconsistency matrix.
is_valid_linkage checks for a valid hierarchical clustering.
is_valid_y checks for a valid condensed distance matrix.
is_isomorphic checks if two flat clusterings are isomorphic.
is_monotonic checks if a linkage is monotonic.
Z_y_correspond checks for validity of distance matrix given a linkage.
Utility Functions
numobs_dm # of observations in a distance matrix.
numobs_linkage # of observations in a linkage.
numobs_y # of observations in a condensed distance matrix.
Legal stuff
copying Displays the license for this package.
MATLAB and MathWorks are registered trademarks of The MathWorks, Inc.
Mathematica is a registered trademark of The Wolfram Research, Inc.
References:
[1] "Statistics toolbox." API Reference Documentation. The MathWorks.
http://www.mathworks.com/access/helpdesk/help/toolbox/stats/.
Accessed October 1, 2007.
[2] "Hierarchical clustering." API Reference Documentation.
The Wolfram Research, Inc. http://reference.wolfram.com/...
...mathematica/HierarchicalClustering/tutorial/...
HierarchicalClustering.html. Accessed October 1, 2007.
[3] Gower, JC and Ross, GJS. "Minimum Spanning Trees and Single Linkage
Cluster Analysis." Applied Statistics. 18(1): pp. 54--64. 1969.
[4] Ward Jr, JH. "Hierarchical grouping to optimize an objective
function." Journal of the American Statistical Association. 58(301):
pp. 236--44. 1963.
[5] Johnson, SC. "Hierarchical clustering schemes." Psychometrika.
32(2): pp. 241--54. 1966.
[6] Sneath, PH and Sokal, RR. "Numerical taxonomy." Nature. 193: pp.
855--60. 1962.
[7] Batagelj, V. "Comparing resemblance measures." Journal of
Classification. 12: pp. 73--90. 1995.
[8] Sokal, RR and Michener, CD. "A statistical method for evaluating
systematic relationships." Scientific Bulletins. 38(22):
pp. 1409--38. 1958.
[9] Edelbrock, C. "Mixture model tests of hierarchical clustering
algorithms: the problem of classifying everybody." Multivariate
Behavioral Research. 14: pp. 367--84. 1979.
[10] Jain, A., and Dubes, R., "Algorithms for Clustering Data."
Prentice-Hall. Englewood Cliffs, NJ. 1988.
[11] Fisher, RA "The use of multiple measurements in taxonomic
problems." Annals of Eugenics, 7(2): 179-188. 1936
"""
_copyingtxt="""
cluster.py
Author: Damian Eads
Date: September 22, 2007
Copyright (c) 2007, 2008, Damian Eads
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
- Redistributions of source code must retain the above
copyright notice, this list of conditions and the
following disclaimer.
- Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer
in the documentation and/or other materials provided with the
distribution.
- Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""
import _hierarchy_wrap, scipy, numpy, types, math, sys, scipy.stats
_cpy_non_euclid_methods = {'single': 0, 'complete': 1, 'average': 2, 'weighted': 6}
_cpy_euclid_methods = {'centroid': 3, 'median': 4, 'ward': 5}
_cpy_linkage_methods = set(_cpy_non_euclid_methods.keys()).union(set(_cpy_euclid_methods.keys()))
_array_type = type(numpy.array([]))
try:
import warnings
def _warning(s):
warnings.warn('scipy-cluster: %s' % s, stacklevel=3)
except:
def _warning(s):
print ('[WARNING] scipy-cluster: %s' % s)
def _unbiased_variance(X):
"""
Computes the unbiased variance of each dimension of a collection of
observation vectors, represented by a matrix where the rows are the
observations.
"""
#n = numpy.double(X.shape[1])
return scipy.stats.var(X, axis=0) # * n / (n - 1.0)
def _copy_array_if_base_present(a):
"""
Copies the array if its base points to a parent array.
"""
if a.base is not None:
return a.copy()
elif (a.dtype == 'float32'):
return numpy.float64(a)
else:
return a
def _copy_arrays_if_base_present(T):
"""
Accepts a tuple of arrays T. Copies the array T[i] if its base array
points to an actual array. Otherwise, the reference is just copied.
This is useful if the arrays are being passed to a C function that
does not do proper striding.
"""
l = [_copy_array_if_base_present(a) for a in T]
return l
def copying():
""" Displays the license for this package."""
print _copyingtxt
return None
def _randdm(pnts):
""" Generates a random distance matrix stored in condensed form. A
pnts * (pnts - 1) / 2 sized vector is returned.
"""
if pnts >= 2:
D = numpy.random.rand(pnts * (pnts - 1) / 2)
else:
raise ValueError("The number of points in the distance matrix must be at least 2.")
return D
def single(y):
"""
Z = single(y)
Performs single/min/nearest linkage on the condensed distance
matrix Z. See linkage for more information on the return structure
and algorithm.
(a condensed alias for single)
"""
return linkage(y, method='single', metric='euclidean')
def complete(y):
"""
Z = complete(y)
Performs complete complete/max/farthest point linkage on the
condensed distance matrix Z. See linkage for more information
on the return structure and algorithm.
(a condensed alias for linkage)
"""
return linkage(y, method='complete', metric='euclidean')
def average(y):
"""
Z = average(y)
Performs average/UPGMA linkage on the condensed distance matrix Z. See
linkage for more information on the return structure and algorithm.
(a condensed alias for linkage)
"""
return linkage(y, method='average', metric='euclidean')
def weighted(y):
"""
Z = weighted(y)
Performs weighted/WPGMA linkage on the condensed distance matrix Z.
See linkage for more information on the return structure and
algorithm.
(a condensed alias for linkage)
"""
return linkage(y, method='weighted', metric='euclidean')
def centroid(y):
"""
Z = centroid(y)
Performs centroid/UPGMC linkage on the condensed distance matrix Z.
See linkage for more information on the return structure and
algorithm.
(a condensed alias for linkage)
Z = centroid(X)
Performs centroid/UPGMC linkage on the observation matrix X using
Euclidean distance as the distance metric. See linkage for more
information on the return structure and algorithm.
"""
return linkage(y, method='centroid', metric='euclidean')
def median(y):
"""
Z = median(y)
Performs median/WPGMC linkage on the condensed distance matrix Z.
See linkage for more information on the return structure and
algorithm.
Z = median(X)
Performs median/WPGMC linkage on the observation matrix X using
Euclidean distance as the distance metric. See linkage for more
information on the return structure and algorithm.
(a condensed alias for linkage)
"""
return linkage(y, method='median', metric='euclidean')
def ward(y):
"""
Z = ward(y)
Performs Ward's linkage on the condensed distance matrix Z. See
linkage for more information on the return structure and algorithm.
Z = ward(X)
Performs Ward's linkage on the observation matrix X using Euclidean
distance as the distance metric. See linkage for more information
on the return structure and algorithm.
(a condensed alias for linkage)
"""
return linkage(y, method='ward', metric='euclidean')
def linkage(y, method='single', metric='euclidean'):
""" Z = linkage(y, method)
Performs hierarchical/agglomerative clustering on the
condensed distance matrix y. y must be a {n \choose 2} sized
vector where n is the number of original observations paired
in the distance matrix. The behavior of this function is very
similar to the MATLAB(TM) linkage function.
A (n - 1) * 4 matrix Z is returned. At the i'th iteration,
clusters with indices Z[i, 0] and Z[i, 1] are combined to
form cluster n + i. A cluster with an index less than n
corresponds to one of the n original observations. The
distance between clusters Z[i, 0] and Z[i, 1] is given by
Z[i, 2]. The fourth value Z[i, 3] represents the number of
original observations in the newly formed cluster.
The following linkage methods are used to compute the
distance dist(s, t) between two clusters s and t. The
algorithm begins with a forest of clusters that have yet
to be used in the hierarchy being formed. When two clusters
s and t from this forest are combined into a single cluster u,
s and t are removed from the forest, and u is added to
the forest. When only one cluster remains in the forest,
the algorithm stops, and this cluster becomes the root.
A distance matrix is maintained at each iteration. The
d[i,j] entry corresponds to the distance between cluster
i and j in the original forest.
At each iteration, the algorithm must update the distance
matrix to reflect the distance of the newly formed cluster
u with the remaining clusters in the forest.
Suppose there are |u| original observations u[0], ..., u[|u|-1]
in cluster u and |v| original objects v[0], ..., v[|v|-1]
in cluster v. Recall s and t are combined to form cluster
u. Let v be any remaining cluster in the forest that is not
u.
The following are methods for calculating the distance between
the newly formed cluster u and each v.
* method='single' assigns dist(u,v) = MIN(dist(u[i],v[j])
for all points i in cluster u and j in cluster v.
(also called Nearest Point Algorithm)
* method='complete' assigns dist(u,v) = MAX(dist(u[i],v[j])
for all points i in cluster u and j in cluster v.
(also called Farthest Point Algorithm
or the Voor Hees Algorithm)
* method='average' assigns dist(u,v) =
\sum_{ij} { dist(u[i], v[j]) } / (|u|*|v|)
for all points i and j where |u| and |v| are the
cardinalities of clusters u and v, respectively.
(also called UPGMA)
* method='weighted' assigns
dist(u,v) = (dist(s,v) + dist(t,v))/2
where cluster u was formed with cluster s and t and v
is a remaining cluster in the forest. (also called WPGMA)
Z = linkage(X, method, metric='euclidean')
Performs hierarchical clustering on the objects defined by the
n by m observation matrix X.
If the metric is 'euclidean' then the following methods may be
used:
* method='centroid' assigns dist(s,t) = euclid(c_s, c_t) where
c_s and c_t are the centroids of clusters s and t,
respectively. When two clusters s and t are combined into a new
cluster u, the new centroid is computed over all the original
objects in clusters s and t. The distance then becomes
the Euclidean distance between the centroid of u and the
centroid of a remaining cluster v in the forest.
(also called UPGMC)
* method='median' assigns dist(s,t) as above. When two clusters
s and t are combined into a new cluster u, the average of
centroids s and t give the new centroid u. (also called WPGMC)
* method='ward' uses the Ward variance minimization algorithm.
The new entry dist(u, v) is computed as follows,
dist(u,v) =
----------------------------------------------------
| |v|+|s| |v|+|t| |v|
| ------- d(v,s)^2 + ------- d(v,t)^2 - --- d(s,t)^2
\| T T T
where u is the newly joined cluster consisting of clusters
s and t, v is an unused cluster in the forest, T=|v|+|s|+|t|,
and |*| is the cardinality of its argument.
(also called incremental)
Warning to MATLAB(TM) users: when the minimum distance pair in
the forest is chosen, there may be two or more pairs with the
same minimum distance. This implementation may chose a
different minimum than the MATLAB(TM) version.
"""
if type(method) != types.StringType:
raise TypeError("Argument 'method' must be a string.")
if type(y) != _array_type:
raise TypeError("Argument 'y' must be a numpy array.")
s = y.shape
if len(s) == 1:
is_valid_y(y, throw=True, name='y')
d = numpy.ceil(numpy.sqrt(s[0] * 2))
if method not in _cpy_non_euclid_methods.keys():
raise ValueError("Valid methods when the raw observations are omitted are 'single', 'complete', 'weighted', and 'average'.")
# Since the C code does not support striding using strides.
[y] = _copy_arrays_if_base_present([y])
Z = numpy.zeros((d - 1, 4))
_hierarchy_wrap.linkage_wrap(y, Z, int(d), \
int(_cpy_non_euclid_methods[method]))
elif len(s) == 2:
X = y
n = s[0]
m = s[1]
if method not in _cpy_linkage_methods:
raise ValueError('Invalid method: %s' % method)
if method in _cpy_non_euclid_methods.keys():
dm = pdist(X, metric)
Z = numpy.zeros((n - 1, 4))
_hierarchy_wrap.linkage_wrap(dm, Z, n, \
int(_cpy_non_euclid_methods[method]))
elif method in _cpy_euclid_methods.keys():
if metric != 'euclidean':
raise ValueError('Method %s requires the distance metric to be euclidean' % s)
dm = pdist(X, metric)
Z = numpy.zeros((n - 1, 4))
_hierarchy_wrap.linkage_euclid_wrap(dm, Z, X, m, n,
int(_cpy_euclid_methods[method]))
return Z
class cnode:
"""
A tree node class for representing a cluster. Leaf nodes correspond
to original observations, while non-leaf nodes correspond to
non-singleton clusters.
The totree function converts a matrix returned by the linkage
function into an easy-to-use tree representation.
"""
def __init__(self, id, left=None, right=None, dist=0, count=1):
if id < 0:
raise ValueError('The id must be non-negative.')
if dist < 0:
raise ValueError('The distance must be non-negative.')
if (left is None and right is not None) or \
(left is not None and right is None):
raise ValueError('Only full or proper binary trees are permitted. This node has one child.')
if count < 1:
raise ValueError('A cluster must contain at least one original observation.')
self.id = id
self.left = left
self.right = right
self.dist = dist
if self.left is None:
self.count = count
else:
self.count = left.count + right.count
def getId(self):
"""
i = nd.getId()
Returns the id number of the node nd. For 0 <= i < n, i
corresponds to original observation i. For n <= i < 2n - 1,
i corresponds to non-singleton cluster formed at iteration i-n.
"""
return self.id
def getCount(self):
"""
c = nd.getCount()
Returns the number of leaf nodes (original observations)
belonging to the cluster node nd. If the nd is a leaf, c=1.
"""
return self.count
def getLeft(self):
"""
left = nd.getLeft()
Returns a reference to the left child. If the node is a
leaf, None is returned.
"""
return self.left
def getRight(self):
"""
left = nd.getLeft()
Returns a reference to the right child. If the node is a
leaf, None is returned.
"""
return self.right
def isLeaf(self):
"""
Returns True if the node is a leaf.
"""
return self.left is None
def preOrder(self, func=(lambda x: x.id)):
"""
vlst = preOrder(func)
Performs preorder traversal without recursive function calls.
When a leaf node is first encountered, func is called with the
leaf node as its argument, and its result is appended to the
list vlst.
For example, the statement
ids = root.preOrder(lambda x: x.id)
returns a list of the node ids corresponding to the leaf
nodes of the tree as they appear from left to right.
"""
# Do a preorder traversal, caching the result. To avoid having to do
# recursion, we'll store the previous index we've visited in a vector.
n = self.count
curNode = [None] * (2 * n)
lvisited = numpy.zeros((2 * n,), dtype='bool')
rvisited = numpy.zeros((2 * n,), dtype='bool')
curNode[0] = self
k = 0
preorder = []
while k >= 0:
nd = curNode[k]
ndid = nd.id
if nd.isLeaf():
preorder.append(func(nd))
k = k - 1
else:
if not lvisited[ndid]:
curNode[k + 1] = nd.left
lvisited[ndid] = True
k = k + 1
elif not rvisited[ndid]:
curNode[k + 1] = nd.right
rvisited[ndid] = True
k = k + 1
# If we've visited the left and right of this non-leaf
# node already, go up in the tree.
else:
k = k - 1
return preorder
_cnode_bare = cnode(0)
_cnode_type = type(cnode)
def totree(Z, rd=False):
"""
r = totree(Z)
Converts a hierarchical clustering encoded in the matrix Z
(by linkage) into an easy-to-use tree object. The reference r
to the root cnode object is returned.
Each cnode object has a left, right, dist, id, and count
attribute. The left and right attributes point to cnode
objects that were combined to generate the cluster. If
both are None then the cnode object is a leaf node, its
count must be 1, and its distance is meaningless but set
to 0.
(r, d) = totree(Z, rd=True)
Same as totree(Z) except a tuple is returned where r is
the reference to the root cnode and d is a reference to a
dictionary mapping cluster ids to cnodes. If a cluster id
is less than n, then it corresponds to a singleton cluster
(leaf node).
Note: This function is provided for the convenience of the
library user. cnodes are not used as input to any of the
functions in this library.
"""
is_valid_linkage(Z, throw=True, name='Z')
# The number of original objects is equal to the number of rows minus
# 1.
n = Z.shape[0] + 1
# Create a list full of None's to store the node objects
d = [None] * (n*2-1)
# If we encounter a cluster being combined more than once, the matrix
# must be corrupt.
if len(numpy.unique(Z[:, 0:2].reshape((2 * (n - 1),)))) != 2 * (n - 1):
raise ValueError('Corrupt matrix Z. Some clusters are more than once.')
# If a cluster index is out of bounds, report an error.
if (Z[:, 0:2] >= 2 * n - 1).any():
raise ValueError('Corrupt matrix Z. Some cluster indices (first and second) are out of bounds.')
if (Z[:, 0:2] < 0).any():
raise ValueError('Corrupt matrix Z. Some cluster indices (first and second columns) are negative.')
if (Z[:, 2] < 0).any():
raise ValueError('Corrupt matrix Z. Some distances (third column) are negative.')
if (Z[:, 3] < 0).any():
raise ValueError('Some counts (fourth column) are negative.')
# Create the nodes corresponding to the n original objects.
for i in xrange(0, n):
d[i] = cnode(i)
nd = None
for i in xrange(0, n - 1):
fi = int(Z[i, 0])
fj = int(Z[i, 1])
if fi > i + n:
raise ValueError('Corrupt matrix Z. Index to derivative cluster is used before it is formed. See row %d, column 0' % fi)
if fj > i + n:
raise ValueError('Corrupt matrix Z. Index to derivative cluster is used before it is formed. See row %d, column 1' % fj)
nd = cnode(i + n, d[fi], d[fj], Z[i, 2])
# ^ id ^ left ^ right ^ dist
if Z[i,3] != nd.count:
raise ValueError('Corrupt matrix Z. The count Z[%d,3] is incorrect.' % i)
d[n + i] = nd
if rd:
return (nd, d)
else:
return nd
def squareform(X, force="no", checks=True):
"""
... = squareform(...)
Converts a vector-form distance vector to a square-form distance
matrix, and vice-versa.
v = squareform(X)
Given a square d by d symmetric distance matrix X, v=squareform(X)
returns a d*(d-1)/2 (or {n \choose 2}) sized vector v.
v[{n \choose 2}-{n-i \choose 2} + (j-i-1)] is the distance
between points i and j. If X is non-square or asymmetric, an error
is returned.
X = squareform(v)
Given a d*d(-1)/2 sized v for some integer d>=2 encoding distances
as described, X=squareform(v) returns a d by d distance matrix X. The
X[i, j] and X[j, i] values are set to
v[{n \choose 2}-{n-i \choose 2} + (j-u-1)] and all
diagonal elements are zero.
As with MATLAB(TM), if force is equal to 'tovector' or 'tomatrix',
the input will be treated as a distance matrix or distance vector
respectively.
If checks is set to False, no checks will be made for matrix
symmetry nor zero diagonals. This is useful if it is known that
X - X.T is small and diag(X) is close to zero. These values are
ignored any way so they do not disrupt the squareform
transformation.
"""
if type(X) is not _array_type:
raise TypeError('The parameter passed must be an array.')
if X.dtype != 'double':
raise TypeError('A double array must be passed.')
s = X.shape
# X = squareform(v)
if len(s) == 1 and force != 'tomatrix':
# Grab the closest value to the square root of the number
# of elements times 2 to see if the number of elements
# is indeed a binomial coefficient.
d = int(numpy.ceil(numpy.sqrt(X.shape[0] * 2)))
print d, s[0]
# Check that v is of valid dimensions.
if d * (d - 1) / 2 != int(s[0]):
raise ValueError('Incompatible vector size. It must be a binomial coefficient n choose 2 for some integer n >= 2.')
# Allocate memory for the distance matrix.
M = numpy.zeros((d, d), 'double')
# Since the C code does not support striding using strides.
# The dimensions are used instead.
[X] = _copy_arrays_if_base_present([X])
# Fill in the values of the distance matrix.
_hierarchy_wrap.to_squareform_from_vector_wrap(M, X)
# Return the distance matrix.
M = M + M.transpose()
return M
elif len(s) != 1 and force.lower() == 'tomatrix':
raise ValueError("Forcing 'tomatrix' but input X is not a distance vector.")
elif len(s) == 2 and force.lower() != 'tovector':
if s[0] != s[1]:
raise ValueError('The matrix argument must be square.')
if checks:
if numpy.sum(numpy.sum(X == X.transpose())) != numpy.product(X.shape):
raise ValueError('The distance matrix must be symmetrical.')
if (X.diagonal() != 0).any():
raise ValueError('The distance matrix must have zeros along the diagonal.')
# One-side of the dimensions is set here.
d = s[0]
# Create a vector.
v = numpy.zeros(((d * (d - 1) / 2),), 'double')
# Since the C code does not support striding using strides.
# The dimensions are used instead.
[X] = _copy_arrays_if_base_present([X])
# Convert the vector to squareform.
_hierarchy_wrap.to_vector_from_squareform_wrap(X, v)
return v
elif len(s) != 2 and force.lower() == 'tomatrix':
raise ValueError("Forcing 'tomatrix' but input X is not a distance vector.")
else:
raise ValueError('The first argument must be a vector or matrix. A %d-dimensional array is not permitted' % len(s))
def minkowski(u, v, p):
"""
d = minkowski(u, v, p)
Returns the Minkowski distance between two vectors u and v,
||u-v||_p = (\sum {|u_i - v_i|^p})^(1/p).
"""
if p < 1:
raise ValueError("p must be at least 1")
return math.pow((abs(u-v)**p).sum(), 1.0/p)
def euclidean(u, v):
"""
d = euclidean(u, v)
Computes the Euclidean distance between two n-vectors u and v, ||u-v||_2
"""
q=numpy.matrix(u-v)
return numpy.sqrt((q*q.T).sum())
def sqeuclidean(u, v):
"""
d = sqeuclidean(u, v)
Computes the squared Euclidean distance between two n-vectors u and v,
(||u-v||_2)^2.
"""
return ((u-v)*(u-v).T).sum()
def cosine(u, v):
"""
d = cosine(u, v)
Computes the Cosine distance between two n-vectors u and v,
(1-uv^T)/(||u||_2 * ||v||_2).
"""
return (1.0 - (scipy.dot(u, v.T) / \
(numpy.sqrt(scipy.dot(u, u.T)) * numpy.sqrt(scipy.dot(v, v.T)))))
def correlation(u, v):
"""
d = correlation(u, v)
Computes the correlation distance between two n-vectors u and v,
1 - (u - n|u|_1)(v - n|v|_1)^T
--------------------------------- ,
|(u - n|u|_1)|_2 |(v - n|v|_1)|^T
where |*|_1 is the Manhattan norm and n is the common dimensionality
of the vectors.
"""
umu = u.mean()
vmu = v.mean()
um = u - umu
vm = v - vmu
return 1.0 - (scipy.dot(um, vm) /
(numpy.sqrt(scipy.dot(um, um)) \
* numpy.sqrt(scipy.dot(vm, vm))))
def hamming(u, v):
"""
d = hamming(u, v)
Computes the Hamming distance between two n-vectors u and v,
which is simply the proportion of disagreeing components in u
and v. If u and v are boolean vectors, the hamming distance is
(c_{01} + c_{10}) / n
where c_{ij} is the number of occurrences of
u[k] == i and v[k] == j
for k < n.
"""
return (u != v).mean()
def jaccard(u, v):
"""
d = jaccard(u, v)
Computes the Jaccard-Needham dissimilarity between two boolean
n-vectors u and v, which is
c_{TF} + c_{FT}
------------------------
c_{TT} + c_{FT} + c_{TF}
where c_{ij} is the number of occurrences of
u[k] == i and v[k] == j
for k < n.
"""
return numpy.double(scipy.bitwise_and((u != v), scipy.bitwise_or(u != 0, v != 0)).sum()) / numpy.double(scipy.bitwise_or(u != 0, v != 0).sum())
def kulsinski(u, v):
"""
d = kulsinski(u, v)
Computes the Kulsinski dissimilarity between two boolean n-vectors
u and v, which is
c_{TF} + c_{FT} - c_{TT} + n
----------------------------
c_{FT} + c_{TF} + n
where c_{ij} is the number of occurrences of
u[k] == i and v[k] == j
for k < n.
"""
(nff, nft, ntf, ntt) = _nbool_correspond_all(u, v)
return (ntf + nft - ntt + n) / (ntf + nft + n)
def seuclidean(u, v, V):
"""
d = seuclidean(u, v, V)
Returns the standardized Euclidean distance between two
n-vectors u and v. V is a m-dimensional vector of component
variances. It is usually computed among a larger collection vectors.
"""
if type(V) is not _array_type or len(V.shape) != 1 or V.shape[0] != u.shape[0] or u.shape[0] != v.shape[0]:
raise TypeError('V must be a 1-D numpy array of doubles of the same dimension as u and v.')
return numpy.sqrt(((u-v)**2 / V).sum())
def cityblock(u, v):
"""
d = cityblock(u, v)
Computes the Manhattan distance between two n-vectors u and v,
\sum {u_i-v_i}.
"""
return abs(u-v).sum()
def mahalanobis(u, v, VI):
"""
d = mahalanobis(u, v, VI)
Computes the Mahalanobis distance between two n-vectors u and v,
(u-v)VI(u-v)^T
where VI is the inverse covariance matrix.
"""
if type(V) is not _array_type:
raise TypeError('V must be a 1-D numpy array of doubles of the same dimension as u and v.')
return numpy.sqrt(scipy.dot(scipy.dot((u-v),VI),(u-v).T).sum())
def chebyshev(u, v):
"""
d = chebyshev(u, v)
Computes the Chebyshev distance between two n-vectors u and v,
\max {|u_i-v_i|}.
"""
return max(abs(u-v))
def braycurtis(u, v):
"""
d = braycurtis(u, v)
Computes the Bray-Curtis distance between two n-vectors u and v,
\sum{|u_i-v_i|} / \sum{|u_i+v_i|}.
"""
return abs(u-v).sum() / abs(u+v).sum()
def canberra(u, v):
"""
d = canberra(u, v)
Computes the Canberra distance between two n-vectors u and v,
\sum{|u_i-v_i|} / \sum{|u_i|+|v_i}.
"""
return abs(u-v).sum() / (abs(u).sum() + abs(v).sum())
def _nbool_correspond_all(u, v):
not_u = scipy.bitwise_not(u)
not_v = scipy.bitwise_not(v)
nff = scipy.bitwise_and(not_u, not_v).sum()
nft = scipy.bitwise_and(not_u, v).sum()
ntf = scipy.bitwise_and(u, not_v).sum()
ntt = scipy.bitwise_and(u, v).sum()
return (nff, nft, ntf, ntt)
def _nbool_correspond_ft_tf(u, v):
not_u = scipy.bitwise_not(u)
not_v = scipy.bitwise_not(v)
nft = scipy.bitwise_and(not_u, v).sum()
ntf = scipy.bitwise_and(u, not_v).sum()
return (nft, ntf)
def yule(u, v):
"""
d = yule(u, v)
Computes the Yule dissimilarity between two boolean n-vectors u and v,
R
---------------------
c_{TT} + c_{FF} + R/2
where c_{ij} is the number of occurrences of
u[k] == i and v[k] == j
for k < n, and
R = 2.0 * (c_{TF} + c_{FT}).
"""
(nff, nft, ntf, ntt) = _nbool_correspond_all(u, v)
return float(2.0 * ntf * nft) / float(ntt * nff + ntf * nft)
def matching(u, v):