forked from jakevdp/pyDistances
-
Notifications
You must be signed in to change notification settings - Fork 0
/
distmetrics.pyx
1360 lines (1062 loc) · 42.5 KB
/
distmetrics.pyx
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 warnings
import numpy as np
cimport numpy as np
cimport cython
from libc.math cimport fabs, fmax, sqrt, pow
cdef extern from "arrayobject.h":
object PyArray_SimpleNewFromData(int nd, np.npy_intp* dims,
int typenum, void* data)
np.import_array() # required in order to use C-API
# python data types (corresponding C-types are in pxd file)
DTYPE = np.float64
# TODO:
# Functionality:
# - add `override_precomputed` flag on distance functions
#
# Speed:
# - use blas for computations where appropriate
# - boolean functions are slow: how do we access fast C boolean operations?
# - use @cython.cdivision(True) where applicable
# - enable fast euclidean distances using (x-y)^2 = x^2 + y^2 - 2xy
# and 'precomputed norms' flag
#
# Documentation:
# - documentation of metrics
# - double-check consistency with sklearn.metrics & scipy.spatial.distance
#
# Templating?
# - this would be a great candidate to try out cython templating
#
# Future Functionality:
# - make cdist/pdist work with fortran arrays (see note below)
# - make cdist/pdist work with csr matrices. This will require writing
# a new form of each distance function which accepts csr input.
# - implement KD tree based on this (?)
# - cover tree as well (?)
# - templating? this would be a great candidate to try out cython templates.
#
# One idea:
# to save on memory, we could define general distance functions with
# the signature
# dfunc(DTYPE_t* x1, DTYPE_t* x2, Py_ssize_t n,
# Py_ssize_t rowstride1, Py_ssize_t colstride1,
# Py_ssize_t rowstride2, Py_ssize_t colstride2,
# Py_ssize_t rowindex1, Py_ssize_t rowindex2,
# dist_params* params)
#
# This would allow arbitrary numpy arrays to be used by the function,
# but would slightly slow down computation.
###############################################################################
# Helper functions
cdef np.ndarray _norms(np.ndarray X):
return np.sqrt(np.asarray((X ** 2).sum(1), dtype=DTYPE, order='C'))
cdef np.ndarray _centered(np.ndarray X):
return X - X.mean(1).reshape((-1, 1))
cdef inline np.ndarray _buffer_to_ndarray(DTYPE_t* x, np.npy_intp n):
# Wrap a memory buffer with an ndarray. Warning: this is not robust.
# In particular, if x is deallocated before the returned array goes
# out of scope, this could SegFault.
# if we know what n is beforehand, we can simply call
# (in newer cython versions)
#return np.asarray(<double[:100]> x)
# Note: this Segfaults unless np.import_array() is called above
return PyArray_SimpleNewFromData(1, &n, DTYPECODE, <void*>x)
###############################################################################
#Here we define the various distance functions
#
# Distance functions have the following call signature
#
# distance(DTYPE_t* x1, DTYPE_t* x1, Py_ssize_t n,
# dist_params* params,
# Py_ssize_t rowindex1, Py_ssize_t rowindex2)
#
# Parameters
# ----------
# x1, x2 : double*
# pointers to data arrays (see notes below)
# n : integer
# length of vector (see notes below)
# params : structure
# the parameter structure contains various parameters that define
# the distance metric, or aid in faster computation.
# rowindex1, rowindex2 : integers
# these define the offsets where the data starts (see notes below)
#
# Returns
# -------
# D : double
# distance between v1 and v2
#
# Notes
# -----
# the data in the vectors v1 and v2 are defined by the following
# locations in memory:
#
# - v1 = x1[n * row_offset1 : (n + 1) * rowindex1]
# - v2 = x2[n * row_offset2 : (n + 1) * rowindex2]
#
# passing rowindex1 and rowindex2 becomes useful for metrics where
# computation can be made more efficient by precomputing information
# about each point: e.g. the mean and norm in cosine_distance and
# correlation_distance, etc.
###############################################################################
cdef DTYPE_t euclidean_distance(DTYPE_t* x1, DTYPE_t* x2,
Py_ssize_t n, dist_params* params,
Py_ssize_t rowindex1,
Py_ssize_t rowindex2):
cdef Py_ssize_t i
cdef DTYPE_t d, res = 0
x1 += rowindex1 * n
x2 += rowindex2 * n
for i from 0 <= i < n:
d = x1[i] - x2[i]
res += d * d
return sqrt(res)
cdef DTYPE_t manhattan_distance(DTYPE_t* x1, DTYPE_t* x2,
Py_ssize_t n, dist_params* params,
Py_ssize_t rowindex1,
Py_ssize_t rowindex2):
cdef Py_ssize_t i
cdef DTYPE_t res = 0
x1 += rowindex1 * n
x2 += rowindex2 * n
for i from 0 <= i < n:
res += fabs(x1[i] - x2[i])
return res
cdef DTYPE_t chebyshev_distance(DTYPE_t* x1, DTYPE_t* x2,
Py_ssize_t n, dist_params* params,
Py_ssize_t rowindex1,
Py_ssize_t rowindex2):
cdef Py_ssize_t i
cdef DTYPE_t res = 0
x1 += rowindex1 * n
x2 += rowindex2 * n
for i from 0 <= i < n:
res = fmax(res, fabs(x1[i] - x2[i]))
return res
cdef DTYPE_t minkowski_distance(DTYPE_t* x1, DTYPE_t* x2,
Py_ssize_t n, dist_params* params,
Py_ssize_t rowindex1,
Py_ssize_t rowindex2):
cdef Py_ssize_t i
cdef DTYPE_t d, res = 0
x1 += rowindex1 * n
x2 += rowindex2 * n
for i from 0 <= i < n:
d = fabs(x1[i] - x2[i])
res += pow(d, params.minkowski.p)
return pow(res, 1. / params.minkowski.p)
cdef DTYPE_t pminkowski_distance(DTYPE_t* x1, DTYPE_t* x2,
Py_ssize_t n, dist_params* params,
Py_ssize_t rowindex1,
Py_ssize_t rowindex2):
cdef Py_ssize_t i
cdef DTYPE_t d, res = 0
x1 += rowindex1 * n
x2 += rowindex2 * n
for i from 0 <= i < n:
d = fabs(x1[i] - x2[i])
res += pow(d, params.minkowski.p)
return res
cdef DTYPE_t wminkowski_distance(DTYPE_t* x1, DTYPE_t* x2,
Py_ssize_t n, dist_params* params,
Py_ssize_t rowindex1,
Py_ssize_t rowindex2):
cdef Py_ssize_t i
cdef DTYPE_t d, res = 0
x1 += rowindex1 * n
x2 += rowindex2 * n
for i from 0 <= i < n:
d = fabs(x1[i] - x2[i])
res += pow(params.minkowski.w[i] * d, params.minkowski.p)
return pow(res, 1. / params.minkowski.p)
cdef DTYPE_t pwminkowski_distance(DTYPE_t* x1, DTYPE_t* x2,
Py_ssize_t n, dist_params* params,
Py_ssize_t rowindex1,
Py_ssize_t rowindex2):
cdef Py_ssize_t i
cdef DTYPE_t d, res = 0
x1 += rowindex1 * n
x2 += rowindex2 * n
for i from 0 <= i < n:
d = fabs(x1[i] - x2[i])
res += pow(params.minkowski.w[i] * d, params.minkowski.p)
return res
cdef DTYPE_t mahalanobis_distance(DTYPE_t* x1, DTYPE_t* x2,
Py_ssize_t n, dist_params* params,
Py_ssize_t rowindex1,
Py_ssize_t rowindex2):
cdef Py_ssize_t i, j
cdef DTYPE_t d, res = 0
x1 += rowindex1 * n
x2 += rowindex2 * n
assert n == params.mahalanobis.n
# TODO: use blas here
for i from 0 <= i < n:
params.mahalanobis.work_buffer[i] = x1[i] - x2[i]
for i from 0 <= i < n:
d = 0
for j from 0 <= j < n:
d += (params.mahalanobis.VI[i * n + j]
* params.mahalanobis.work_buffer[j])
res += d * params.mahalanobis.work_buffer[i]
return sqrt(res)
cdef DTYPE_t sqmahalanobis_distance(DTYPE_t* x1, DTYPE_t* x2,
Py_ssize_t n, dist_params* params,
Py_ssize_t rowindex1,
Py_ssize_t rowindex2):
cdef Py_ssize_t i, j
cdef DTYPE_t d, res = 0
x1 += rowindex1 * n
x2 += rowindex2 * n
assert n == params.mahalanobis.n
# TODO: use blas here
for i from 0 <= i < n:
params.mahalanobis.work_buffer[i] = x1[i] - x2[i]
for i from 0 <= i < n:
d = 0
for j from 0 <= j < n:
d += (params.mahalanobis.VI[i * n + j]
* params.mahalanobis.work_buffer[j])
res += d * params.mahalanobis.work_buffer[i]
return res
cdef DTYPE_t seuclidean_distance(DTYPE_t* x1, DTYPE_t* x2,
Py_ssize_t n, dist_params* params,
Py_ssize_t rowindex1,
Py_ssize_t rowindex2):
cdef Py_ssize_t i
cdef DTYPE_t d, res = 0
x1 += rowindex1 * n
x2 += rowindex2 * n
for i from 0 <= i < n:
d = x1[i] - x2[i]
res += d * d / params.seuclidean.V[i]
return sqrt(res)
cdef DTYPE_t sqseuclidean_distance(DTYPE_t* x1, DTYPE_t* x2,
Py_ssize_t n, dist_params* params,
Py_ssize_t rowindex1,
Py_ssize_t rowindex2):
cdef Py_ssize_t i
cdef DTYPE_t d, res = 0
x1 += rowindex1 * n
x2 += rowindex2 * n
for i from 0 <= i < n:
d = x1[i] - x2[i]
res += d * d / params.seuclidean.V[i]
return res
cdef DTYPE_t sqeuclidean_distance(DTYPE_t* x1, DTYPE_t* x2,
Py_ssize_t n, dist_params* params,
Py_ssize_t rowindex1,
Py_ssize_t rowindex2):
cdef Py_ssize_t i
cdef DTYPE_t d, res = 0
x1 += rowindex1 * n
x2 += rowindex2 * n
for i from 0 <= i < n:
d = x1[i] - x2[i]
res += d * d
return res
cdef DTYPE_t cosine_distance(DTYPE_t* x1, DTYPE_t* x2,
Py_ssize_t n, dist_params* params,
Py_ssize_t rowindex1,
Py_ssize_t rowindex2):
cdef Py_ssize_t i
cdef DTYPE_t x1nrm = 0, x2nrm = 0, x1Tx2 = 0, normalization = 0
x1 += rowindex1 * n
x2 += rowindex2 * n
# TODO: use blas here
if params.cosine.precomputed_norms:
for i from 0 <= i < n:
x1Tx2 += x1[i] * x2[i]
x1nrm = params.cosine.norms1[rowindex1]
x2nrm = params.cosine.norms2[rowindex2]
normalization = x1nrm * x2nrm
else:
for i from 0 <= i < n:
x1nrm += x1[i] * x1[i]
x2nrm += x2[i] * x2[i]
x1Tx2 += x1[i] * x2[i]
normalization = sqrt(x1nrm * x2nrm)
return 1.0 - (x1Tx2) / normalization
cdef DTYPE_t correlation_distance(DTYPE_t* x1, DTYPE_t* x2,
Py_ssize_t n, dist_params* params,
Py_ssize_t rowindex1,
Py_ssize_t rowindex2):
cdef Py_ssize_t i
cdef DTYPE_t mu1 = 0, mu2 = 0, x1nrm = 0, x2nrm = 0, x1Tx2 = 0
cdef DTYPE_t normalization
cdef DTYPE_t tmp1, tmp2
# TODO : use blas here
if params.correlation.precomputed_data:
x1 = params.correlation.x1 + rowindex1 * n
x2 = params.correlation.x2 + rowindex2 * n
for i from 0 <= i < n:
x1Tx2 += x1[i] * x2[i]
normalization = params.correlation.norms1[rowindex1]
normalization *= params.correlation.norms2[rowindex2]
else:
x1 += rowindex1 * n
x2 += rowindex2 * n
for i from 0 <= i < n:
mu1 += x1[i]
mu2 += x2[i]
mu1 /= n
mu2 /= n
for i from 0 <= i < n:
tmp1 = x1[i] - mu1
tmp2 = x2[i] - mu2
x1nrm += tmp1 * tmp1
x2nrm += tmp2 * tmp2
x1Tx2 += tmp1 * tmp2
normalization = sqrt(x1nrm * x2nrm)
return 1. - x1Tx2 / normalization
cdef DTYPE_t hamming_distance(DTYPE_t* x1, DTYPE_t* x2,
Py_ssize_t n, dist_params* params,
Py_ssize_t rowindex1,
Py_ssize_t rowindex2):
cdef Py_ssize_t i
cdef int n_disagree = 0
x1 += rowindex1 * n
x2 += rowindex2 * n
for i from 0 <= i < n:
n_disagree += (x1[i] != x2[i])
return n_disagree * 1. / n
cdef DTYPE_t jaccard_distance(DTYPE_t* x1, DTYPE_t* x2,
Py_ssize_t n, dist_params* params,
Py_ssize_t rowindex1,
Py_ssize_t rowindex2):
cdef Py_ssize_t i
cdef int n_disagree = 0
x1 += rowindex1 * n
x2 += rowindex2 * n
for i from 0 <= i < n:
if x1[i] != 0:
if x2[i] != 0:
if (x1[i] != x2[i]):
n_disagree += 1
return n_disagree * 1. / n
cdef DTYPE_t canberra_distance(DTYPE_t* x1, DTYPE_t* x2,
Py_ssize_t n, dist_params* params,
Py_ssize_t rowindex1,
Py_ssize_t rowindex2):
cdef DTYPE_t res = 0, denominator
cdef Py_ssize_t i
x1 += rowindex1 * n
x2 += rowindex2 * n
for i from 0 <= i < n:
denominator = (fabs(x1[i]) + fabs(x2[i]))
if denominator > 0:
res += fabs(x1[i] - x2[i]) / denominator
return res
cdef DTYPE_t braycurtis_distance(DTYPE_t* x1, DTYPE_t* x2,
Py_ssize_t n, dist_params* params,
Py_ssize_t rowindex1,
Py_ssize_t rowindex2):
cdef Py_ssize_t i
cdef DTYPE_t numerator = 0, denominator = 0
x1 += rowindex1 * n
x2 += rowindex2 * n
for i from 0 <= i < n:
numerator += fabs(x1[i] - x2[i])
denominator += fabs(x1[i])
denominator += fabs(x2[i])
return numerator / denominator
cdef DTYPE_t yule_distance(DTYPE_t* x1, DTYPE_t* x2,
Py_ssize_t n, dist_params* params,
Py_ssize_t rowindex1,
Py_ssize_t rowindex2):
cdef int TF1, TF2, ntt = 0, nff = 0, ntf = 0, nft = 0
cdef Py_ssize_t i
x1 += rowindex1 * n
x2 += rowindex2 * n
for i from 0 <= i < n:
TF1 = (x1[i] != 0)
TF2 = (x2[i] != 0)
nff += (1 - TF1) * (1 - TF2)
nft += (1 - TF1) * TF2
ntf += TF1 * (1 - TF2)
ntt += TF1 * TF2
return (2. * ntf * nft) / (ntt * nff + ntf * nft)
cdef DTYPE_t matching_distance(DTYPE_t* x1, DTYPE_t* x2,
Py_ssize_t n, dist_params* params,
Py_ssize_t rowindex1,
Py_ssize_t rowindex2):
cdef int TF1, TF2, n_neq = 0
cdef Py_ssize_t i
x1 += rowindex1 * n
x2 += rowindex2 * n
for i from 0 <= i < n:
TF1 = (x1[i] != 0)
TF2 = (x2[i] != 0)
n_neq += (TF1 != TF2)
return n_neq * 1. / n
cdef DTYPE_t dice_distance(DTYPE_t* x1, DTYPE_t* x2,
Py_ssize_t n, dist_params* params,
Py_ssize_t rowindex1,
Py_ssize_t rowindex2):
cdef int TF1, TF2, ntt = 0, n_neq = 0
cdef Py_ssize_t i
x1 += rowindex1 * n
x2 += rowindex2 * n
for i from 0 <= i < n:
TF1 = (x1[i] != 0)
TF2 = (x2[i] != 0)
ntt += TF1 * TF2
n_neq += (TF1 != TF2)
return n_neq * 1. / (2 * ntt + n_neq)
cdef DTYPE_t kulsinski_distance(DTYPE_t* x1, DTYPE_t* x2,
Py_ssize_t n, dist_params* params,
Py_ssize_t rowindex1,
Py_ssize_t rowindex2):
cdef int TF1, TF2, ntt = 0, n_neq = 0
cdef Py_ssize_t i
x1 += rowindex1 * n
x2 += rowindex2 * n
for i from 0 <= i < n:
TF1 = (x1[i] != 0)
TF2 = (x2[i] != 0)
ntt += TF1 * TF2
n_neq += (TF1 != TF2)
return (n_neq - ntt + n) * 1. / (n_neq + n)
cdef DTYPE_t rogerstanimoto_distance(DTYPE_t* x1, DTYPE_t* x2,
Py_ssize_t n, dist_params* params,
Py_ssize_t rowindex1,
Py_ssize_t rowindex2):
cdef int TF1, TF2, n_neq = 0
cdef Py_ssize_t i
x1 += rowindex1 * n
x2 += rowindex2 * n
for i from 0 <= i < n:
TF1 = (x1[i] != 0)
TF2 = (x2[i] != 0)
n_neq += (TF1 != TF2)
return n_neq * 2. / (n + n_neq)
cdef DTYPE_t russellrao_distance(DTYPE_t* x1, DTYPE_t* x2,
Py_ssize_t n, dist_params* params,
Py_ssize_t rowindex1,
Py_ssize_t rowindex2):
cdef int TF1, TF2, ntt = 0
cdef Py_ssize_t i
x1 += rowindex1 * n
x2 += rowindex2 * n
for i from 0 <= i < n:
TF1 = (x1[i] != 0)
TF2 = (x2[i] != 0)
ntt += TF1 * TF2
return (n - ntt) * 1. / n
cdef DTYPE_t sokalmichener_distance(DTYPE_t* x1, DTYPE_t* x2,
Py_ssize_t n, dist_params* params,
Py_ssize_t rowindex1,
Py_ssize_t rowindex2):
cdef int TF1, TF2, n_neq = 0
cdef Py_ssize_t i
x1 += rowindex1 * n
x2 += rowindex2 * n
for i from 0 <= i < n:
TF1 = (x1[i] != 0)
TF2 = (x2[i] != 0)
n_neq += (TF1 != TF2)
return n_neq * 2.0 / (n + n_neq)
cdef DTYPE_t sokalsneath_distance(DTYPE_t* x1, DTYPE_t* x2,
Py_ssize_t n, dist_params* params,
Py_ssize_t rowindex1,
Py_ssize_t rowindex2):
cdef int TF1, TF2, ntt = 0, n_neq = 0
cdef Py_ssize_t i
x1 += rowindex1 * n
x2 += rowindex2 * n
for i from 0 <= i < n:
TF1 = (x1[i] != 0)
TF2 = (x2[i] != 0)
ntt += TF1 * TF2
n_neq += (TF1 != TF2)
return n_neq * 2.0 / (ntt + 2 * n_neq)
cdef DTYPE_t user_distance(DTYPE_t* x1, DTYPE_t* x2,
Py_ssize_t n, dist_params* params,
Py_ssize_t rowindex1,
Py_ssize_t rowindex2):
cdef np.ndarray y1 = _buffer_to_ndarray(x1 + rowindex1 * n, n)
cdef np.ndarray y2 = _buffer_to_ndarray(x2 + rowindex2 * n, n)
return (<object>(params.user.func))(y1, y2)
######################################################################
# conversions between reduced and standard distances
#
# Motivation
# for some distances the full computation does not have to be performed
# in order to compare distances. For example, with euclidean distance,
# to find out if x1 or x2 is closer to y, one only needs to compare
# sum((x1 - y) ** 2) and sum((x2 - y) ** 2). That is, the square root
# does not need to be performed. In order to take advantage of this
# within BallTree, we need a way of recognizing this for various metrics
# and converting between the distances.
#
cdef inline DTYPE_t no_conversion(DTYPE_t x, dist_params* params):
return x
cdef inline DTYPE_t euclidean_from_reduced(DTYPE_t x, dist_params* params):
return sqrt(x)
cdef inline DTYPE_t reduced_from_euclidean(DTYPE_t x, dist_params* params):
return x * x
cdef inline DTYPE_t minkowski_from_reduced(DTYPE_t x, dist_params* params):
return pow(x, 1. / params.minkowski.p)
cdef inline DTYPE_t reduced_from_minkowski(DTYPE_t x, dist_params* params):
return pow(x, params.minkowski.p)
cdef inline dist_func get_reduced_dfunc(dist_func dfunc):
if dfunc == &euclidean_distance:
return &sqeuclidean_distance
elif dfunc == &seuclidean_distance:
return &sqseuclidean_distance
elif dfunc == &minkowski_distance:
return &pminkowski_distance
elif dfunc == &wminkowski_distance:
return &pwminkowski_distance
elif dfunc == &mahalanobis_distance:
return &sqmahalanobis_distance
else:
return dfunc
cdef inline dist_conv_func get_dist_to_reduced(dist_func dfunc):
if dfunc == &euclidean_distance:
return &reduced_from_euclidean
elif dfunc == &seuclidean_distance:
return &reduced_from_euclidean
elif dfunc == &minkowski_distance:
return &reduced_from_minkowski
elif dfunc == &wminkowski_distance:
return &reduced_from_minkowski
elif dfunc == &mahalanobis_distance:
return &reduced_from_euclidean
else:
return &no_conversion
cdef inline dist_conv_func get_reduced_to_dist(dist_func dfunc):
if dfunc == &euclidean_distance:
return &euclidean_from_reduced
elif dfunc == &seuclidean_distance:
return &euclidean_from_reduced
elif dfunc == &minkowski_distance:
return &minkowski_from_reduced
elif dfunc == &wminkowski_distance:
return &minkowski_from_reduced
elif dfunc == &mahalanobis_distance:
return &euclidean_from_reduced
else:
return &no_conversion
###############################################################################
# DistanceMetric class
cdef class DistanceMetric(object):
def __cinit__(self):
"""Initialize all arrays to empty"""
self.mahalanobis_VI = self.seuclidean_V = self.minkowski_w =\
self.norms1 = self.norms2 = self.precentered_data1 =\
self.precentered_data2 = self.work_buffer = np.ndarray(0)
self.dfunc = &euclidean_distance
def __init__(self, metric="euclidean", w=None, p=None, V=None, VI=None):
"""Object for computing distance between points.
This is a specialized object for efficient distance computations.
The objects contain C-pointers to fast implementations of the
distance functions, to support their use in BallTree.
Parameters
----------
metric : string
Distance metric (see Notes below)
w : ndarray
The weight vector (for weighted Minkowski)
p : double
The p-norm to apply (for Minkowski, weighted and unweighted)
V : ndarray
The variance vector (for standardized Euclidean)
VI : ndarray
The inverse of the covariance matrix (for Mahalanobis)
Notes
-----
``metric`` can be one of the following:
- Metrics designed for floating-point input:
- 'euclidean' / 'l2'
- 'seuclidean'
- 'manhattan' / 'cityblock' / 'l1'
- 'chebyshev'
- 'minkowski'
- 'wminkowski'
- 'mahalanobis'
- 'cosine'
- 'correlation'
- 'hamming'
- 'jaccard'
- 'canberra'
- 'braycurtis'
- non-metrics which can be used for fast distance comparison
- 'sqeuclidean'
- 'sqseuclidean'
- 'pminkowski'
- 'pwminkowski'
- 'sqmahalanobis'
- Metrics designed for boolean input:
- 'yule'
- 'matching'
- 'dice'
- 'kulsinski'
- 'rogerstanimoto'
- 'russellrao'
- 'sokalmichener'
- 'sokalsneath'
For details on the form of the metrics, see the docstring of
:class:`distance_metrics`.
"""
self.learn_params_from_data = False
if metric in ["euclidean", 'l2', None]:
self.dfunc = &euclidean_distance
elif metric in ("manhattan", "cityblock", "l1"):
self.dfunc = &manhattan_distance
elif metric == "chebyshev":
self.dfunc = &chebyshev_distance
elif metric == "minkowski":
if p == None:
raise ValueError("For metric = 'minkowski', "
"parameter p must be specified.")
elif p <= 0:
raise ValueError("For metric = 'minkowski', "
"parameter p must be greater than 0.")
elif p == 1:
self.dfunc = &manhattan_distance
elif p == 2:
self.dfunc = &euclidean_distance
elif p == np.inf:
self.dfunc = &chebyshev_distance
else:
self.dfunc = &minkowski_distance
self.params.minkowski.p = p
elif metric == "pminkowski":
if p == None:
raise ValueError("For metric = 'pminkowski', "
"parameter p must be specified.")
elif p <= 0:
raise ValueError("For metric = 'pminkowski', "
"parameter p must be greater than 0.")
elif p == 1:
self.dfunc = &manhattan_distance
elif p == 2:
self.dfunc = &sqeuclidean_distance
elif p == np.inf:
self.dfunc = &chebyshev_distance
else:
self.dfunc = &pminkowski_distance
self.params.minkowski.p = p
elif metric == "wminkowski":
self.dfunc = &wminkowski_distance
if p == None:
raise ValueError("For metric = 'wminkowski', "
"parameter p must be specified.")
elif p <= 0:
raise ValueError("For metric = 'wminkowski', "
"parameter p must be greater than 0.")
self.params.minkowski.p = p
if w is None:
raise ValueError("For metric = 'wminkowski', "
"parameter w must be specified.")
self.minkowski_w = np.asarray(w, dtype=DTYPE, order='C')
assert self.minkowski_w.ndim == 1
self.params.minkowski.w = <DTYPE_t*>self.minkowski_w.data
self.params.minkowski.n = self.minkowski_w.shape[0]
elif metric == "pwminkowski":
self.dfunc = &pwminkowski_distance
if p == None:
raise ValueError("For metric = 'pwminkowski', "
"parameter p must be specified.")
elif p <= 0:
raise ValueError("For metric = 'pwminkowski', "
"parameter p must be greater than 0.")
self.params.minkowski.p = p
if w is None:
raise ValueError("For metric = 'minkowski', "
"parameter w must be specified.")
self.minkowski_w = np.asarray(w, dtype=DTYPE, order='C')
assert self.minkowski_w.ndim == 1
self.params.minkowski.w = <DTYPE_t*>self.minkowski_w.data
self.params.minkowski.n = self.minkowski_w.shape[0]
elif metric in ["sqmahalanobis", "mahalanobis"]:
if VI is None:
self.learn_params_from_data = True
else:
self.mahalanobis_VI = np.asarray(VI, dtype=DTYPE, order='C')
assert self.mahalanobis_VI.ndim == 2
assert (self.mahalanobis_VI.shape[0]
== self.mahalanobis_VI.shape[1])
self.work_buffer = np.empty(
self.mahalanobis_VI.shape[0], dtype=DTYPE)
self.params.mahalanobis.n = self.mahalanobis_VI.shape[0]
self.params.mahalanobis.VI = \
<DTYPE_t*> self.mahalanobis_VI.data
self.params.mahalanobis.work_buffer = \
<DTYPE_t*> self.work_buffer.data
if metric == "mahalanobis":
self.dfunc = &mahalanobis_distance
else:
self.dfunc = &sqmahalanobis_distance
elif metric in ['seuclidean', 'sqseuclidean']:
if V is None:
self.learn_params_from_data = True
else:
self.seuclidean_V = np.asarray(V)
assert self.seuclidean_V.ndim == 1
self.params.seuclidean.V = <DTYPE_t*> self.seuclidean_V.data
self.params.seuclidean.n = self.seuclidean_V.shape[0]
if metric == 'seuclidean':
self.dfunc = &seuclidean_distance
else:
self.dfunc = &sqseuclidean_distance
elif metric == 'sqeuclidean':
self.dfunc = &sqeuclidean_distance
elif metric == 'cosine':
self.params.cosine.precomputed_norms = 0
self.dfunc = &cosine_distance
elif metric == 'correlation':
self.params.correlation.precomputed_data = 0
self.dfunc = &correlation_distance
elif metric == 'hamming':
self.dfunc = &hamming_distance
elif metric == 'jaccard':
self.dfunc = &jaccard_distance
elif metric == 'canberra':
self.dfunc = &canberra_distance
elif metric == 'braycurtis':
self.dfunc = &braycurtis_distance
elif metric == 'yule':
self.dfunc = &yule_distance
elif metric == 'matching':
self.dfunc = &matching_distance
elif metric == 'dice':
self.dfunc = dice_distance
elif metric == 'kulsinski':
self.dfunc = &kulsinski_distance
elif metric == 'rogerstanimoto':
self.dfunc = &rogerstanimoto_distance
elif metric == 'russellrao':
self.dfunc = &russellrao_distance
elif metric == 'sokalmichener':
self.dfunc = &sokalmichener_distance
elif metric == 'sokalsneath':
self.dfunc = &sokalsneath_distance
elif callable(metric):
x = np.random.random(3)
try:
res = float(metric(x, x))
except:
raise ValueError("user-defined metrics must accept two "
"vectors and return a scalar.")
self.params.user.func = <void*> metric
self.dfunc = &user_distance
else:
raise ValueError('unrecognized metric %s' % metric)
self.reduced_dfunc = get_reduced_dfunc(self.dfunc)
self.dist_to_reduced = get_dist_to_reduced(self.dfunc)
self.reduced_to_dist = get_reduced_to_dist(self.dfunc)
def set_params_from_data(self, X1, X2 = None, persist=True):
"""Set internal parameters from data
Some distance metrics require extra information, which can be
learned from the data matrices. This function sets those
internal parameters
Parameters
----------
X1 : array-like
X2 : array-like (optional, default = None)
persist : bool (optional, default = True)
if False, the parameters will be recomputed on the new data
each time another distance measurement is performed.
if True, the parameters will persist for all future distance
computations
"""
if persist:
self.learn_params_from_data = False
X1 = np.asarray(X1)
if X2 is not None: