/
distance.py
2138 lines (1740 loc) · 70.3 KB
/
distance.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
"""
=====================================================
Distance computations (:mod:`scipy.spatial.distance`)
=====================================================
.. sectionauthor:: Damian Eads
Function Reference
------------------
Distance matrix computation from a collection of raw observation vectors
stored in a rectangular array.
.. autosummary::
:toctree: generated/
pdist -- pairwise distances between observation vectors.
cdist -- distances between between two collections of observation vectors
squareform -- convert distance matrix to a condensed one and vice versa
Predicates for checking the validity of distance matrices, both
condensed and redundant. Also contained in this module are functions
for computing the number of observations in a distance matrix.
.. autosummary::
:toctree: generated/
is_valid_dm -- checks for a valid distance matrix
is_valid_y -- checks for a valid condensed distance matrix
num_obs_dm -- # of observations in a distance matrix
num_obs_y -- # of observations in a condensed distance matrix
Distance functions between two vectors ``u`` and ``v``. Computing
distances over a large collection of vectors is inefficient for these
functions. Use ``pdist`` for this purpose.
.. autosummary::
:toctree: generated/
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).
"""
# Copyright (C) Damian Eads, 2007-2008. New BSD License.
import warnings
import numpy as np
from numpy.linalg import norm
import _distance_wrap
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 np.issubsctype(a, np.float32):
return np.array(a, dtype=np.double)
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 _convert_to_bool(X):
if X.dtype != np.bool:
X = X.astype(np.bool)
if not X.flags.contiguous:
X = X.copy()
return X
def _convert_to_double(X):
if X.dtype != np.double:
X = X.astype(np.double)
if not X.flags.contiguous:
X = X.copy()
return X
def _validate_vector(u, dtype=None):
# XXX Is order='c' really necessary?
u = np.asarray(u, dtype=dtype, order='c').squeeze()
# Ensure values such as u=1 and u=[1] still return 1-D arrays.
u = np.atleast_1d(u)
if u.ndim > 1:
raise ValueError("Input vector should be 1-D.")
return u
def minkowski(u, v, p):
r"""
Computes the Minkowski distance between two vectors ``u`` and ``v``,
defined as
.. math::
{||u-v||}_p = (\sum{|u_i - v_i|^p})^{1/p}.
Parameters
----------
u : ndarray
An n-dimensional vector.
v : ndarray
An n-dimensional vector.
p : int
The order of the norm of the difference :math:`{||u-v||}_p`.
Returns
-------
d : double
The Minkowski distance between vectors ``u`` and ``v``.
"""
u = _validate_vector(u)
v = _validate_vector(v)
if p < 1:
raise ValueError("p must be at least 1")
dist = norm(u - v, ord=p)
return dist
def wminkowski(u, v, p, w):
r"""
Computes the weighted Minkowski distance between two vectors ``u``
and ``v``, defined as
.. math::
\left(\sum{(w_i |u_i - v_i|^p)}\right)^{1/p}.
Parameters
----------
u : ndarray
An :math:`n`-dimensional vector.
v : ndarray
An :math:`n`-dimensional vector.
p : int
The order of the norm of the difference :math:`{||u-v||}_p`.
w : ndarray
The weight vector.
Returns
-------
d : double
The Minkowski distance between vectors ``u`` and ``v``.
"""
u = _validate_vector(u)
v = _validate_vector(v)
w = _validate_vector(w)
if p < 1:
raise ValueError("p must be at least 1")
dist = norm(w * (u - v), ord=p)
return dist
def euclidean(u, v):
"""
Computes the Euclidean distance between two n-vectors ``u`` and ``v``,
which is defined as
.. math::
{||u-v||}_2
Parameters
----------
u : ndarray
An :math:`n`-dimensional vector.
v : ndarray
An :math:`n`-dimensional vector.
Returns
-------
d : double
The Euclidean distance between vectors ``u`` and ``v``.
"""
u = _validate_vector(u)
v = _validate_vector(v)
dist = norm(u - v)
return dist
def sqeuclidean(u, v):
"""
Computes the squared Euclidean distance between two n-vectors u and v,
which is defined as
.. math::
{||u-v||}_2^2.
Parameters
----------
u : ndarray
An :math:`n`-dimensional vector.
v : ndarray
An :math:`n`-dimensional vector.
Returns
-------
d : double
The squared Euclidean distance between vectors ``u`` and ``v``.
"""
u = _validate_vector(u)
v = _validate_vector(v)
dist = ((u - v) ** 2).sum()
return dist
def cosine(u, v):
r"""
Computes the Cosine distance between two n-vectors u and v, which
is defined as
.. math::
1 - \frac{u \cdot v}
{||u||_2 ||v||_2}.
where :math:`u \cdot v` is the dot product of :math:`u` and
:math:`v`.
Parameters
----------
u : ndarray
An :math:`n`-dimensional vector.
v : ndarray
An :math:`n`-dimensional vector.
Returns
-------
d : double
The Cosine distance between vectors ``u`` and ``v``.
"""
u = _validate_vector(u)
v = _validate_vector(v)
dist = 1.0 - np.dot(u, v) / (norm(u) * norm(v))
return dist
def correlation(u, v):
r"""
Computes the correlation distance between two n-vectors ``u`` and
``v``, which is defined as
.. math::
1 - \frac{(u - \bar{u}) \cdot (v - \bar{v})}
{{||(u - \bar{u})||}_2 {||(v - \bar{v})||}_2}
where :math:`\bar{u}` is the mean of the elements of ``u``
and :math:`x \cdot y` is the dot product of :math:`x` and :math:`y`.
Parameters
----------
u : ndarray
An :math:`n`-dimensional vector.
v : ndarray
An :math:`n`-dimensional vector.
Returns
-------
d : double
The correlation distance between vectors ``u`` and ``v``.
"""
u = _validate_vector(u)
v = _validate_vector(v)
umu = u.mean()
vmu = v.mean()
um = u - umu
vm = v - vmu
dist = 1.0 - np.dot(um, vm) / (norm(um) * norm(vm))
return dist
def hamming(u, v):
r"""
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
.. math::
\frac{c_{01} + c_{10}}{n}
where :math:`c_{ij}` is the number of occurrences of
:math:`\mathtt{u[k]} = i` and :math:`\mathtt{v[k]} = j` for
:math:`k < n`.
Parameters
----------
u : ndarray
An :math:`n`-dimensional vector.
v : ndarray
An :math:`n`-dimensional vector.
Returns
-------
d : double
The Hamming distance between vectors ``u`` and ``v``.
"""
u = _validate_vector(u)
v = _validate_vector(v)
return (u != v).mean()
def jaccard(u, v):
r"""
Computes the Jaccard-Needham dissimilarity between two boolean
n-vectors u and v, which is
.. math::
\frac{c_{TF} + c_{FT}}
{c_{TT} + c_{FT} + c_{TF}}
where :math:`c_{ij}` is the number of occurrences of
:math:`\mathtt{u[k]} = i` and :math:`\mathtt{v[k]} = j` for
:math:`k < n`.
Parameters
----------
u : ndarray
An :math:`n`-dimensional vector.
v : ndarray
An :math:`n`-dimensional vector.
Returns
-------
d : double
The Jaccard distance between vectors ``u`` and ``v``.
"""
u = _validate_vector(u)
v = _validate_vector(v)
dist = (np.double(np.bitwise_and((u != v),
np.bitwise_or(u != 0, v != 0)).sum())
/ np.double(np.bitwise_or(u != 0, v != 0).sum()))
return dist
def kulsinski(u, v):
r"""
Computes the Kulsinski dissimilarity between two boolean n-vectors
u and v, which is defined as
.. math::
\frac{c_{TF} + c_{FT} - c_{TT} + n}
{c_{FT} + c_{TF} + n}
where :math:`c_{ij}` is the number of occurrences of
:math:`\mathtt{u[k]} = i` and :math:`\mathtt{v[k]} = j` for
:math:`k < n`.
Parameters
----------
u : ndarray
An :math:`n`-dimensional vector.
v : ndarray
An :math:`n`-dimensional vector.
Returns
-------
d : double
The Kulsinski distance between vectors ``u`` and ``v``.
"""
u = _validate_vector(u)
v = _validate_vector(v)
n = float(len(u))
(nff, nft, ntf, ntt) = _nbool_correspond_all(u, v)
return (ntf + nft - ntt + n) / (ntf + nft + n)
def seuclidean(u, v, V):
"""
Returns the standardized Euclidean distance between two n-vectors
``u`` and ``v``. ``V`` is an n-dimensional vector of component
variances. It is usually computed among a larger collection
vectors.
Parameters
----------
u : ndarray
An :math:`n`-dimensional vector.
v : ndarray
An :math:`n`-dimensional vector.
V : ndarray
An :math:`n`-dimensional vector.
Returns
-------
d : double
The standardized Euclidean distance between vectors ``u`` and ``v``.
"""
u = _validate_vector(u)
v = _validate_vector(v)
V = _validate_vector(V, dtype=np.float64)
if V.shape[0] != u.shape[0] or u.shape[0] != v.shape[0]:
raise TypeError('V must be a 1-D array of the same dimension '
'as u and v.')
return np.sqrt(((u - v) ** 2 / V).sum())
def cityblock(u, v):
"""
Computes the Manhattan distance between two n-vectors u and v,
which is defined as
.. math::
\\sum_i {\\left| u_i - v_i \\right|}.
Parameters
----------
u : ndarray
An :math:`n`-dimensional vector.
v : ndarray
An :math:`n`-dimensional vector.
Returns
-------
d : double
The City Block distance between vectors ``u`` and ``v``.
"""
u = _validate_vector(u)
v = _validate_vector(v)
return abs(u - v).sum()
def mahalanobis(u, v, VI):
r"""
Computes the Mahalanobis distance between two n-vectors ``u`` and ``v``,
which is defined as
.. math::
(u-v)V^{-1}(u-v)^T
where ``V`` is the covariance matrix. Note that the argument ``VI``
is the inverse of ``V``.
Parameters
----------
u : ndarray
An :math:`n`-dimensional vector.
v : ndarray
An :math:`n`-dimensional vector.
VI : ndarray
The inverse of the covariance matrix.
Returns
-------
d : double
The Mahalanobis distance between vectors ``u`` and ``v``.
"""
u = _validate_vector(u)
v = _validate_vector(v)
VI = np.atleast_2d(VI)
delta = u - v
m = np.dot(np.dot(delta, VI), delta)
return np.sqrt(m)
def chebyshev(u, v):
r"""
Computes the Chebyshev distance between two n-vectors u and v,
which is defined as
.. math::
\max_i {|u_i-v_i|}.
Parameters
----------
u : ndarray
An :math:`n`-dimensional vector.
v : ndarray
An :math:`n`-dimensional vector.
Returns
-------
d : double
The Chebyshev distance between vectors ``u`` and ``v``.
"""
u = _validate_vector(u)
v = _validate_vector(v)
return max(abs(u - v))
def braycurtis(u, v):
r"""
Computes the Bray-Curtis distance between two n-vectors ``u`` and
``v``, which is defined as
.. math::
\sum{|u_i-v_i|} / \sum{|u_i+v_i|}.
The Bray-Curtis distance is in the range [0, 1] if all coordinates are
positive, and is undefined if the inputs are of length zero.
Parameters
----------
u : ndarray
An :math:`n`-dimensional vector.
v : ndarray
An :math:`n`-dimensional vector.
Returns
-------
d : double
The Bray-Curtis distance between vectors ``u`` and ``v``.
"""
u = _validate_vector(u)
v = _validate_vector(v, dtype=np.float64)
return abs(u - v).sum() / abs(u + v).sum()
def canberra(u, v):
r"""
Computes the Canberra distance between two n-vectors u and v,
which is defined as
.. math::
d(u,v) = \sum_i \frac{|u_i-v_i|}
{|u_i|+|v_i|}.
Parameters
----------
u : ndarray
An :math:`n`-dimensional vector.
v : ndarray
An :math:`n`-dimensional vector.
Returns
-------
d : double
The Canberra distance between vectors ``u`` and ``v``.
Notes
-----
When u[i] and v[i] are 0 for given i, then the fraction 0/0 = 0 is used in
the calculation.
"""
u = _validate_vector(u)
v = _validate_vector(v, dtype=np.float64)
olderr = np.seterr(invalid='ignore')
try:
d = np.nansum(abs(u - v) / (abs(u) + abs(v)))
finally:
np.seterr(**olderr)
return d
def _nbool_correspond_all(u, v):
if u.dtype != v.dtype:
raise TypeError("Arrays being compared must be of the same data type.")
if u.dtype == np.int or u.dtype == np.float_ or u.dtype == np.double:
not_u = 1.0 - u
not_v = 1.0 - v
nff = (not_u * not_v).sum()
nft = (not_u * v).sum()
ntf = (u * not_v).sum()
ntt = (u * v).sum()
elif u.dtype == np.bool:
not_u = ~u
not_v = ~v
nff = (not_u & not_v).sum()
nft = (not_u & v).sum()
ntf = (u & not_v).sum()
ntt = (u & v).sum()
else:
raise TypeError("Arrays being compared have unknown type.")
return (nff, nft, ntf, ntt)
def _nbool_correspond_ft_tf(u, v):
if u.dtype == np.int or u.dtype == np.float_ or u.dtype == np.double:
not_u = 1.0 - u
not_v = 1.0 - v
nft = (not_u * v).sum()
ntf = (u * not_v).sum()
else:
not_u = ~u
not_v = ~v
nft = (not_u & v).sum()
ntf = (u & not_v).sum()
return (nft, ntf)
def yule(u, v):
r"""
Computes the Yule dissimilarity between two boolean n-vectors u and v,
which is defined as
.. math::
\frac{R}{c_{TT} + c_{FF} + \frac{R}{2}}
where :math:`c_{ij}` is the number of occurrences of
:math:`\mathtt{u[k]} = i` and :math:`\mathtt{v[k]} = j` for
:math:`k < n` and :math:`R = 2.0 * (c_{TF} + c_{FT})`.
Parameters
----------
u : ndarray
An :math:`n`-dimensional vector.
v : ndarray
An :math:`n`-dimensional vector.
Returns
-------
d : double
The Yule dissimilarity between vectors ``u`` and ``v``.
"""
u = _validate_vector(u)
v = _validate_vector(v)
(nff, nft, ntf, ntt) = _nbool_correspond_all(u, v)
return float(2.0 * ntf * nft) / float(ntt * nff + ntf * nft)
def matching(u, v):
r"""
Computes the Matching dissimilarity between two boolean n-vectors
u and v, which is defined as
.. math::
\frac{c_{TF} + c_{FT}}{n}
where :math:`c_{ij}` is the number of occurrences of
:math:`\mathtt{u[k]} = i` and :math:`\mathtt{v[k]} = j` for
:math:`k < n`.
Parameters
----------
u : ndarray
An :math:`n`-dimensional vector.
v : ndarray
An :math:`n`-dimensional vector.
Returns
-------
d : double
The Matching dissimilarity between vectors ``u`` and ``v``.
"""
u = _validate_vector(u)
v = _validate_vector(v)
(nft, ntf) = _nbool_correspond_ft_tf(u, v)
return float(nft + ntf) / float(len(u))
def dice(u, v):
r"""
Computes the Dice dissimilarity between two boolean n-vectors
``u`` and ``v``, which is
.. math::
\frac{c_{TF} + c_{FT}}
{2c_{TT} + c_{FT} + c_{TF}}
where :math:`c_{ij}` is the number of occurrences of
:math:`\mathtt{u[k]} = i` and :math:`\mathtt{v[k]} = j` for
:math:`k < n`.
Parameters
----------
u : ndarray
An :math:`n`-dimensional vector.
v : ndarray
An :math:`n`-dimensional vector.
Returns
-------
d : double
The Dice dissimilarity between vectors ``u`` and ``v``.
"""
u = _validate_vector(u)
v = _validate_vector(v)
if u.dtype == np.bool:
ntt = (u & v).sum()
else:
ntt = (u * v).sum()
(nft, ntf) = _nbool_correspond_ft_tf(u, v)
return float(ntf + nft) / float(2.0 * ntt + ntf + nft)
def rogerstanimoto(u, v):
r"""
Computes the Rogers-Tanimoto dissimilarity between two boolean
n-vectors ``u`` and ``v``, which is defined as
.. math::
\frac{R}
{c_{TT} + c_{FF} + R}
where :math:`c_{ij}` is the number of occurrences of
:math:`\mathtt{u[k]} = i` and :math:`\mathtt{v[k]} = j` for
:math:`k < n` and :math:`R = 2(c_{TF} + c_{FT})`.
Parameters
----------
u : ndarray
An :math:`n`-dimensional vector.
v : ndarray
An :math:`n`-dimensional vector.
Returns
-------
d : double
The Rogers-Tanimoto dissimilarity between vectors
`u` and `v`.
"""
u = _validate_vector(u)
v = _validate_vector(v)
(nff, nft, ntf, ntt) = _nbool_correspond_all(u, v)
return float(2.0 * (ntf + nft)) / float(ntt + nff + (2.0 * (ntf + nft)))
def russellrao(u, v):
r"""
Computes the Russell-Rao dissimilarity between two boolean n-vectors
``u`` and ``v``, which is defined as
.. math::
\frac{n - c_{TT}}
{n}
where :math:`c_{ij}` is the number of occurrences of
:math:`\mathtt{u[k]} = i` and :math:`\mathtt{v[k]} = j` for
:math:`k < n`.
Parameters
----------
u : ndarray
An :math:`n`-dimensional vector.
v : ndarray
An :math:`n`-dimensional vector.
Returns
-------
d : double
The Russell-Rao dissimilarity between vectors ``u`` and ``v``.
"""
u = _validate_vector(u)
v = _validate_vector(v)
if u.dtype == np.bool:
ntt = (u & v).sum()
else:
ntt = (u * v).sum()
return float(len(u) - ntt) / float(len(u))
def sokalmichener(u, v):
r"""
Computes the Sokal-Michener dissimilarity between two boolean vectors
``u`` and ``v``, which is defined as
.. math::
\frac{R}
{S + R}
where :math:`c_{ij}` is the number of occurrences of
:math:`\mathtt{u[k]} = i` and :math:`\mathtt{v[k]} = j` for
:math:`k < n`, :math:`R = 2 * (c_{TF} + c_{FT})` and
:math:`S = c_{FF} + c_{TT}`.
Parameters
----------
u : ndarray
An :math:`n`-dimensional vector.
v : ndarray
An :math:`n`-dimensional vector.
Returns
-------
d : double
The Sokal-Michener dissimilarity between vectors ``u`` and ``v``.
"""
u = _validate_vector(u)
v = _validate_vector(v)
if u.dtype == np.bool:
ntt = (u & v).sum()
nff = (~u & ~v).sum()
else:
ntt = (u * v).sum()
nff = ((1.0 - u) * (1.0 - v)).sum()
(nft, ntf) = _nbool_correspond_ft_tf(u, v)
return float(2.0 * (ntf + nft)) / float(ntt + nff + 2.0 * (ntf + nft))
def sokalsneath(u, v):
r"""
Computes the Sokal-Sneath dissimilarity between two boolean vectors
``u`` and ``v``,
.. math::
\frac{R}
{c_{TT} + R}
where :math:`c_{ij}` is the number of occurrences of
:math:`\mathtt{u[k]} = i` and :math:`\mathtt{v[k]} = j` for
:math:`k < n` and :math:`R = 2(c_{TF} + c_{FT})`.
Parameters
----------
u : ndarray
An :math:`n`-dimensional vector.
v : ndarray
An :math:`n`-dimensional vector.
Returns
-------
d : double
The Sokal-Sneath dissimilarity between vectors ``u`` and ``v``.
"""
u = _validate_vector(u)
v = _validate_vector(v)
if u.dtype == np.bool:
ntt = (u & v).sum()
else:
ntt = (u * v).sum()
(nft, ntf) = _nbool_correspond_ft_tf(u, v)
denom = ntt + 2.0 * (ntf + nft)
if denom == 0:
raise ValueError('Sokal-Sneath dissimilarity is not defined for '
'vectors that are entirely false.')
return float(2.0 * (ntf + nft)) / denom
def pdist(X, metric='euclidean', p=2, w=None, V=None, VI=None):
r"""
Computes the pairwise distances between m original observations in
n-dimensional space. Returns a condensed distance matrix Y. For
each :math:`i` and :math:`j` (where :math:`i<j<n`), the
metric ``dist(u=X[i], v=X[j])`` is computed and stored in entry ``ij``.
See ``squareform`` for information on how to calculate the index of
this entry or to convert the condensed distance matrix to a
redundant square matrix.
The following are common calling conventions.
1. ``Y = pdist(X, 'euclidean')``
Computes the distance between m points using Euclidean distance
(2-norm) as the distance metric between the points. The points
are arranged as m n-dimensional row vectors in the matrix X.
2. ``Y = pdist(X, 'minkowski', p)``
Computes the distances using the Minkowski distance
:math:`||u-v||_p` (p-norm) where :math:`p \geq 1`.
3. ``Y = pdist(X, 'cityblock')``
Computes the city block or Manhattan distance between the
points.
4. ``Y = pdist(X, 'seuclidean', V=None)``
Computes the standardized Euclidean distance. The standardized
Euclidean distance between two n-vectors ``u`` and ``v`` is
.. math::
\sqrt{\sum {(u_i-v_i)^2 / V[x_i]}}.
V is the variance vector; V[i] is the variance computed over all
the i'th components of the points. If not passed, it is
automatically computed.
5. ``Y = pdist(X, 'sqeuclidean')``
Computes the squared Euclidean distance :math:`||u-v||_2^2` between
the vectors.
6. ``Y = pdist(X, 'cosine')``
Computes the cosine distance between vectors u and v,
.. math::
1 - \frac{u \cdot v}
{{||u||}_2 {||v||}_2}
where :math:`||*||_2` is the 2-norm of its argument ``*``, and
:math:`u \cdot v` is the dot product of ``u`` and ``v``.
7. ``Y = pdist(X, 'correlation')``
Computes the correlation distance between vectors u and v. This is
.. math::
1 - \frac{(u - \bar{u}) \cdot (v - \bar{v})}
{{||(u - \bar{u})||}_2 {||(v - \bar{v})||}_2}
where :math:`\bar{v}` is the mean of the elements of vector v,
and :math:`x \cdot y` is the dot product of :math:`x` and :math:`y`.
8. ``Y = pdist(X, 'hamming')``
Computes the normalized Hamming distance, or the proportion of
those vector elements between two n-vectors ``u`` and ``v``
which disagree. To save memory, the matrix ``X`` can be of type
boolean.
9. ``Y = pdist(X, 'jaccard')``
Computes the Jaccard distance between the points. Given two
vectors, ``u`` and ``v``, the Jaccard distance is the
proportion of those elements ``u[i]`` and ``v[i]`` that
disagree where at least one of them is non-zero.
10. ``Y = pdist(X, 'chebyshev')``
Computes the Chebyshev distance between the points. The
Chebyshev distance between two n-vectors ``u`` and ``v`` is the
maximum norm-1 distance between their respective elements. More
precisely, the distance is given by
.. math::
d(u,v) = \max_i {|u_i-v_i|}.
11. ``Y = pdist(X, 'canberra')``
Computes the Canberra distance between the points. The
Canberra distance between two points ``u`` and ``v`` is
.. math::
d(u,v) = \sum_i \frac{|u_i-v_i|}
{|u_i|+|v_i|}.
12. ``Y = pdist(X, 'braycurtis')``
Computes the Bray-Curtis distance between the points. The
Bray-Curtis distance between two points ``u`` and ``v`` is
.. math::
d(u,v) = \frac{\sum_i {u_i-v_i}}
{\sum_i {u_i+v_i}}
13. ``Y = pdist(X, 'mahalanobis', VI=None)``
Computes the Mahalanobis distance between the points. The
Mahalanobis distance between two points ``u`` and ``v`` is
:math:`(u-v)(1/V)(u-v)^T` where :math:`(1/V)` (the ``VI``
variable) is the inverse covariance. If ``VI`` is not None,