File: test_umap_metrics.py

package info (click to toggle)
umap-learn 0.5.3%2Bdfsg-2
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 2,468 kB
  • sloc: python: 9,458; sh: 87; makefile: 20
file content (552 lines) | stat: -rw-r--r-- 17,618 bytes parent folder | download
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
import numpy as np
from numpy.testing import assert_array_almost_equal
import umap.distances as dist
import umap.sparse as spdist

from sklearn.metrics import pairwise_distances
from sklearn.neighbors import BallTree
from scipy.version import full_version as scipy_full_version
import pytest



# ===================================================
#  Metrics Test cases
# ===================================================

# ----------------------------------
# Utility functions for Metric tests
# ----------------------------------


def run_test_metric(metric, test_data, dist_matrix, with_grad=False):
    """Core utility function to test target metric on test data"""
    if with_grad:
        dist_function = dist.named_distances_with_gradients[metric]
    else:
        dist_function = dist.named_distances[metric]
    sample_size = test_data.shape[0]
    test_matrix = [
        [dist_function(test_data[i], test_data[j]) for j in range(sample_size)]
        for i in range(sample_size)
    ]
    if with_grad:
        test_matrix = [d for pairs in test_matrix for d, grad in pairs]

    test_matrix = np.array(test_matrix).reshape(sample_size, sample_size)

    assert_array_almost_equal(
        test_matrix,
        dist_matrix,
        err_msg="Distances don't match " "for metric {}".format(metric),
    )


def spatial_check(metric, spatial_data, spatial_distances, with_grad=False):
    # Check that metric is supported for this test, otherwise, fail!
    assert metric in spatial_distances, f"{metric} not valid for spatial data"
    dist_matrix = pairwise_distances(spatial_data, metric=metric)
    # scipy is bad sometimes
    if metric == "braycurtis":
        dist_matrix[np.where(~np.isfinite(dist_matrix))] = 0.0

    if metric in ("cosine", "correlation"):
        dist_matrix[np.where(~np.isfinite(dist_matrix))] = 1.0
        # And because distance between all zero vectors should be zero
        dist_matrix[10, 11] = 0.0
        dist_matrix[11, 10] = 0.0

    run_test_metric(metric, spatial_data, dist_matrix, with_grad=with_grad)


def binary_check(metric, binary_data, binary_distances):
    # Check that metric is supported for this test, otherwise, fail!
    assert metric in binary_distances, f"{metric} not valid for binary data"
    dist_matrix = pairwise_distances(binary_data, metric=metric)

    if metric in ("jaccard", "dice", "sokalsneath", "yule"):
        dist_matrix[np.where(~np.isfinite(dist_matrix))] = 0.0

    if metric in ("kulsinski", "russellrao"):
        dist_matrix[np.where(~np.isfinite(dist_matrix))] = 0.0
        # And because distance between all zero vectors should be zero
        dist_matrix[10, 11] = 0.0
        dist_matrix[11, 10] = 0.0

    run_test_metric(metric, binary_data, dist_matrix)


def run_test_sparse_metric(metric, sparse_test_data, dist_matrix):
    """Core utility function to run test of target metric on sparse data"""
    dist_function = spdist.sparse_named_distances[metric]
    if metric in spdist.sparse_need_n_features:
        test_matrix = np.array(
            [
                [
                    dist_function(
                        sparse_test_data[i].indices,
                        sparse_test_data[i].data,
                        sparse_test_data[j].indices,
                        sparse_test_data[j].data,
                        sparse_test_data.shape[1],
                    )
                    for j in range(sparse_test_data.shape[0])
                ]
                for i in range(sparse_test_data.shape[0])
            ]
        )
    else:
        test_matrix = np.array(
            [
                [
                    dist_function(
                        sparse_test_data[i].indices,
                        sparse_test_data[i].data,
                        sparse_test_data[j].indices,
                        sparse_test_data[j].data,
                    )
                    for j in range(sparse_test_data.shape[0])
                ]
                for i in range(sparse_test_data.shape[0])
            ]
        )
    assert_array_almost_equal(
        test_matrix,
        dist_matrix,
        err_msg="Sparse distances don't match " "for metric {}".format(metric),
    )


def sparse_spatial_check(metric, sparse_spatial_data):
    # Check that metric is supported for this test, otherwise, fail!
    assert (
        metric in spdist.sparse_named_distances
    ), f"{metric} not supported for sparse data"
    dist_matrix = pairwise_distances(np.asarray(sparse_spatial_data.todense()), metric=metric)

    if metric in ("braycurtis", "dice", "sokalsneath", "yule"):
        dist_matrix[np.where(~np.isfinite(dist_matrix))] = 0.0

    if metric in ("cosine", "correlation", "kulsinski", "russellrao"):
        dist_matrix[np.where(~np.isfinite(dist_matrix))] = 1.0
        # And because distance between all zero vectors should be zero
        dist_matrix[10, 11] = 0.0
        dist_matrix[11, 10] = 0.0

    run_test_sparse_metric(metric, sparse_spatial_data, dist_matrix)


def sparse_binary_check(metric, sparse_binary_data):
    # Check that metric is supported for this test, otherwise, fail!
    assert (
        metric in spdist.sparse_named_distances
    ), f"{metric} not supported for sparse data"
    dist_matrix = pairwise_distances(np.asarray(sparse_binary_data.todense()), metric=metric)
    if metric in ("jaccard", "dice", "sokalsneath", "yule"):
        dist_matrix[np.where(~np.isfinite(dist_matrix))] = 0.0

    if metric in ("kulsinski", "russellrao"):
        dist_matrix[np.where(~np.isfinite(dist_matrix))] = 1.0
        # And because distance between all zero vectors should be zero
        dist_matrix[10, 11] = 0.0
        dist_matrix[11, 10] = 0.0

    run_test_sparse_metric(metric, sparse_binary_data, dist_matrix)


# --------------------
# Spatial Metric Tests
# --------------------


def test_euclidean(spatial_data, spatial_distances):
    spatial_check("euclidean", spatial_data, spatial_distances)


def test_manhattan(spatial_data, spatial_distances):
    spatial_check("manhattan", spatial_data, spatial_distances)


def test_chebyshev(spatial_data, spatial_distances):
    spatial_check("chebyshev", spatial_data, spatial_distances)


def test_minkowski(spatial_data, spatial_distances):
    spatial_check("minkowski", spatial_data, spatial_distances)


def test_hamming(spatial_data, spatial_distances):
    spatial_check("hamming", spatial_data, spatial_distances)


def test_canberra(spatial_data, spatial_distances):
    spatial_check("canberra", spatial_data, spatial_distances)


def test_braycurtis(spatial_data, spatial_distances):
    spatial_check("braycurtis", spatial_data, spatial_distances)


def test_cosine(spatial_data, spatial_distances):
    spatial_check("cosine", spatial_data, spatial_distances)


def test_correlation(spatial_data, spatial_distances):
    spatial_check("correlation", spatial_data, spatial_distances)


# --------------------
# Binary Metric Tests
# --------------------


def test_jaccard(binary_data, binary_distances):
    binary_check("jaccard", binary_data, binary_distances)


def test_matching(binary_data, binary_distances):
    binary_check("matching", binary_data, binary_distances)


def test_dice(binary_data, binary_distances):
    binary_check("dice", binary_data, binary_distances)


def test_kulsinski(binary_data, binary_distances):
    binary_check("kulsinski", binary_data, binary_distances)


def test_rogerstanimoto(binary_data, binary_distances):
    binary_check("rogerstanimoto", binary_data, binary_distances)


def test_russellrao(binary_data, binary_distances):
    binary_check("russellrao", binary_data, binary_distances)


def test_sokalmichener(binary_data, binary_distances):
    binary_check("sokalmichener", binary_data, binary_distances)


def test_sokalsneath(binary_data, binary_distances):
    binary_check("sokalsneath", binary_data, binary_distances)


def test_yule(binary_data, binary_distances):
    binary_check("yule", binary_data, binary_distances)


# ---------------------------
# Sparse Spatial Metric Tests
# ---------------------------


def test_sparse_euclidean(sparse_spatial_data):
    sparse_spatial_check("euclidean", sparse_spatial_data)


def test_sparse_manhattan(sparse_spatial_data):
    sparse_spatial_check("manhattan", sparse_spatial_data)


def test_sparse_chebyshev(sparse_spatial_data):
    sparse_spatial_check("chebyshev", sparse_spatial_data)


def test_sparse_minkowski(sparse_spatial_data):
    sparse_spatial_check("minkowski", sparse_spatial_data)


def test_sparse_hamming(sparse_spatial_data):
    sparse_spatial_check("hamming", sparse_spatial_data)


def test_sparse_canberra(sparse_spatial_data):
    sparse_spatial_check("canberra", sparse_spatial_data)


def test_sparse_cosine(sparse_spatial_data):
    sparse_spatial_check("cosine", sparse_spatial_data)


def test_sparse_correlation(sparse_spatial_data):
    sparse_spatial_check("correlation", sparse_spatial_data)


def test_sparse_braycurtis(sparse_spatial_data):
    sparse_spatial_check("braycurtis", sparse_spatial_data)


# ---------------------------
# Sparse Binary Metric Tests
# ---------------------------


def test_sparse_jaccard(sparse_binary_data):
    sparse_binary_check("jaccard", sparse_binary_data)


def test_sparse_matching(sparse_binary_data):
    sparse_binary_check("matching", sparse_binary_data)


def test_sparse_dice(sparse_binary_data):
    sparse_binary_check("dice", sparse_binary_data)


def test_sparse_kulsinski(sparse_binary_data):
    sparse_binary_check("kulsinski", sparse_binary_data)


def test_sparse_rogerstanimoto(sparse_binary_data):
    sparse_binary_check("rogerstanimoto", sparse_binary_data)


def test_sparse_russellrao(sparse_binary_data):
    sparse_binary_check("russellrao", sparse_binary_data)


def test_sparse_sokalmichener(sparse_binary_data):
    sparse_binary_check("sokalmichener", sparse_binary_data)


def test_sparse_sokalsneath(sparse_binary_data):
    sparse_binary_check("sokalsneath", sparse_binary_data)


# --------------------------------
# Standardised/weighted Distances
# --------------------------------
def test_seuclidean(spatial_data):
    v = np.abs(np.random.randn(spatial_data.shape[1]))
    dist_matrix = pairwise_distances(spatial_data, metric="seuclidean", V=v)
    test_matrix = np.array(
        [
            [
                dist.standardised_euclidean(spatial_data[i], spatial_data[j], v)
                for j in range(spatial_data.shape[0])
            ]
            for i in range(spatial_data.shape[0])
        ]
    )
    assert_array_almost_equal(
        test_matrix,
        dist_matrix,
        err_msg="Distances don't match " "for metric seuclidean",
    )

@pytest.mark.skipif(
    scipy_full_version < "1.8", reason="incorrect function in scipy<1.8"
)
def test_weighted_minkowski(spatial_data):
    v = np.abs(np.random.randn(spatial_data.shape[1]))
    dist_matrix = pairwise_distances(spatial_data, metric="minkowski", w=v, p=3)
    test_matrix = np.array(
        [
            [
                dist.weighted_minkowski(spatial_data[i], spatial_data[j], v, p=3)
                for j in range(spatial_data.shape[0])
            ]
            for i in range(spatial_data.shape[0])
        ]
    )
    assert_array_almost_equal(
        test_matrix,
        dist_matrix,
        err_msg="Distances don't match " "for metric weighted_minkowski",
    )


def test_mahalanobis(spatial_data):
    v = np.cov(np.transpose(spatial_data))
    dist_matrix = pairwise_distances(spatial_data, metric="mahalanobis", VI=v)
    test_matrix = np.array(
        [
            [
                dist.mahalanobis(spatial_data[i], spatial_data[j], v)
                for j in range(spatial_data.shape[0])
            ]
            for i in range(spatial_data.shape[0])
        ]
    )
    assert_array_almost_equal(
        test_matrix,
        dist_matrix,
        err_msg="Distances don't match " "for metric mahalanobis",
    )


def test_haversine(spatial_data):
    tree = BallTree(spatial_data[:, :2], metric="haversine")
    dist_matrix, _ = tree.query(spatial_data[:, :2], k=spatial_data.shape[0])
    test_matrix = np.array(
        [
            [
                dist.haversine(spatial_data[i, :2], spatial_data[j, :2])
                for j in range(spatial_data.shape[0])
            ]
            for i in range(spatial_data.shape[0])
        ]
    )
    test_matrix.sort(axis=1)
    assert_array_almost_equal(
        test_matrix,
        dist_matrix,
        err_msg="Distances don't match " "for metric haversine",
    )


def test_hellinger(spatial_data):
    hellinger_data = np.abs(spatial_data[:-2].copy())
    hellinger_data = hellinger_data / hellinger_data.sum(axis=1)[:, np.newaxis]
    hellinger_data = np.sqrt(hellinger_data)
    dist_matrix = hellinger_data @ hellinger_data.T
    dist_matrix = 1.0 - dist_matrix
    dist_matrix = np.sqrt(dist_matrix)
    # Correct for nan handling
    dist_matrix[np.isnan(dist_matrix)] = 0.0

    test_matrix = dist.pairwise_special_metric(np.abs(spatial_data[:-2]))

    assert_array_almost_equal(
        test_matrix,
        dist_matrix,
        err_msg="Distances don't match " "for metric hellinger",
    )

    # Ensure ll_dirichlet runs
    test_matrix = dist.pairwise_special_metric(
        np.abs(spatial_data[:-2]), metric="ll_dirichlet"
    )
    assert (
        test_matrix is not None
    ), "Pairwise Special Metric with LL Dirichlet metric failed"


def test_sparse_hellinger(sparse_spatial_data):
    dist_matrix = dist.pairwise_special_metric(
        np.abs(sparse_spatial_data[:-2].toarray())
    )
    test_matrix = np.array(
        [
            [
                spdist.sparse_hellinger(
                    np.abs(sparse_spatial_data[i]).indices,
                    np.abs(sparse_spatial_data[i]).data,
                    np.abs(sparse_spatial_data[j]).indices,
                    np.abs(sparse_spatial_data[j]).data,
                )
                for j in range(sparse_spatial_data.shape[0] - 2)
            ]
            for i in range(sparse_spatial_data.shape[0] - 2)
        ]
    )

    assert_array_almost_equal(
        test_matrix,
        dist_matrix,
        err_msg="Sparse distances don't match " "for metric hellinger",
        decimal=3,
    )

    # Ensure ll_dirichlet runs
    test_matrix = np.array(
        [
            [
                spdist.sparse_ll_dirichlet(
                    sparse_spatial_data[i].indices,
                    sparse_spatial_data[i].data,
                    sparse_spatial_data[j].indices,
                    sparse_spatial_data[j].data,
                )
                for j in range(sparse_spatial_data.shape[0])
            ]
            for i in range(sparse_spatial_data.shape[0])
        ]
    )
    assert (
        test_matrix is not None
    ), "Pairwise Special Metric with LL Dirichlet metric failed"


def test_grad_metrics_match_metrics(spatial_data, spatial_distances):
    for metric in dist.named_distances_with_gradients:
        if metric in spatial_distances:
            spatial_check(metric, spatial_data, spatial_distances, with_grad=True)

    # Handle the few special distances separately
    # SEuclidean
    v = np.abs(np.random.randn(spatial_data.shape[1]))
    dist_matrix = pairwise_distances(spatial_data, metric="seuclidean", V=v)
    test_matrix = np.array(
        [
            [
                dist.standardised_euclidean_grad(spatial_data[i], spatial_data[j], v)[0]
                for j in range(spatial_data.shape[0])
            ]
            for i in range(spatial_data.shape[0])
        ]
    )
    assert_array_almost_equal(
        test_matrix,
        dist_matrix,
        err_msg="Distances don't match " "for metric seuclidean",
    )

    if scipy_full_version >= "1.8":
        # Weighted minkowski
        dist_matrix = pairwise_distances(spatial_data, metric="minkowski", w=v, p=3)
        test_matrix = np.array(
            [
                [
                    dist.weighted_minkowski_grad(spatial_data[i], spatial_data[j], v, p=3)[
                        0
                    ]
                    for j in range(spatial_data.shape[0])
                ]
                for i in range(spatial_data.shape[0])
            ]
        )
        assert_array_almost_equal(
            test_matrix,
            dist_matrix,
            err_msg="Distances don't match " "for metric weighted_minkowski",
        )

    # Mahalanobis
    v = np.abs(np.random.randn(spatial_data.shape[1], spatial_data.shape[1]))
    dist_matrix = pairwise_distances(spatial_data, metric="mahalanobis", VI=v)
    test_matrix = np.array(
        [
            [
                dist.mahalanobis_grad(spatial_data[i], spatial_data[j], v)[0]
                for j in range(spatial_data.shape[0])
            ]
            for i in range(spatial_data.shape[0])
        ]
    )
    assert_array_almost_equal(
        test_matrix,
        dist_matrix,
        decimal=5,
        err_msg="Distances don't match " "for metric mahalanobis",
    )

    # Hellinger
    dist_matrix = dist.pairwise_special_metric(
        np.abs(spatial_data[:-2]), np.abs(spatial_data[:-2])
    )
    test_matrix = np.array(
        [
            [
                dist.hellinger_grad(np.abs(spatial_data[i]), np.abs(spatial_data[j]))[0]
                for j in range(spatial_data.shape[0] - 2)
            ]
            for i in range(spatial_data.shape[0] - 2)
        ]
    )
    assert_array_almost_equal(
        test_matrix,
        dist_matrix,
        err_msg="Distances don't match " "for metric hellinger",
    )