2
2
import numpy as np
3
3
from numpy .testing import assert_array_almost_equal
4
4
5
+
5
6
class IdentityBilinearMixin (BilinearMixin ):
6
7
"""A simple Identity bilinear mixin that returns an identity matrix
7
8
M as learned. Can change M for a random matrix calling random_M.
@@ -15,50 +16,54 @@ def fit(self, X, y):
15
16
self .d = np .shape (X [0 ])[- 1 ]
16
17
self .components_ = np .identity (self .d )
17
18
return self
18
-
19
+
19
20
def random_M (self ):
20
21
self .components_ = np .random .rand (self .d , self .d )
21
22
23
+
22
24
def test_same_similarity_with_two_methods ():
23
25
d = 100
24
26
u = np .random .rand (d )
25
27
v = np .random .rand (d )
26
28
mixin = IdentityBilinearMixin ()
27
- mixin .fit ([u , v ], [0 , 0 ]) # Dummy fit
28
- mixin .random_M ()
29
+ mixin .fit ([u , v ], [0 , 0 ])
30
+ mixin .random_M () # Dummy fit
29
31
30
32
# The distances must match, whether calc with get_metric() or score_pairs()
31
33
dist1 = mixin .score_pairs ([[u , v ], [v , u ]])
32
34
dist2 = [mixin .get_metric ()(u , v ), mixin .get_metric ()(v , u )]
33
35
34
36
assert_array_almost_equal (dist1 , dist2 )
35
37
38
+
36
39
def test_check_correctness_similarity ():
37
40
d = 100
38
41
u = np .random .rand (d )
39
42
v = np .random .rand (d )
40
43
mixin = IdentityBilinearMixin ()
41
- mixin .fit ([u , v ], [0 , 0 ]) # Dummy fit
44
+ mixin .fit ([u , v ], [0 , 0 ]) # Identity fit
42
45
dist1 = mixin .score_pairs ([[u , v ], [v , u ]])
43
46
u_v = np .dot (np .dot (u .T , np .identity (d )), v )
44
47
v_u = np .dot (np .dot (v .T , np .identity (d )), u )
45
48
desired = [u_v , v_u ]
46
49
assert_array_almost_equal (dist1 , desired )
47
50
51
+
48
52
def test_check_handmade_example ():
49
53
u = np .array ([0 , 1 , 2 ])
50
54
v = np .array ([3 , 4 , 5 ])
51
55
mixin = IdentityBilinearMixin ()
52
- mixin .fit ([u , v ], [0 , 0 ])
56
+ mixin .fit ([u , v ], [0 , 0 ]) # Identity fit
53
57
c = np .array ([[2 , 4 , 6 ], [6 , 4 , 2 ], [1 , 2 , 3 ]])
54
- mixin .components_ = c # Force a components_
58
+ mixin .components_ = c # Force components_
55
59
dists = mixin .score_pairs ([[u , v ], [v , u ]])
56
60
assert_array_almost_equal (dists , [96 , 120 ])
57
61
62
+
58
63
def test_check_handmade_symmetric_example ():
59
64
u = np .array ([0 , 1 , 2 ])
60
65
v = np .array ([3 , 4 , 5 ])
61
66
mixin = IdentityBilinearMixin ()
62
- mixin .fit ([u , v ], [0 , 0 ])
67
+ mixin .fit ([u , v ], [0 , 0 ]) # Identity fit
63
68
dists = mixin .score_pairs ([[u , v ], [v , u ]])
64
- assert_array_almost_equal (dists , [14 , 14 ])
69
+ assert_array_almost_equal (dists , [14 , 14 ])
0 commit comments