1
2
3
4
5
6
7
8
9 """Unit tests for PyMVPA kernels"""
10
11 import unittest
12 import numpy as N
13
14 from mvpa.clfs.distance import squared_euclidean_distance, \
15 pnorm_w, pnorm_w_python
16
17
18 from tests_warehouse import datasets
19
21
23
24
25 data = datasets['uni4large'].samples[:5, :8]
26
27 ed = squared_euclidean_distance(data)
28
29
30
31
32 true_size = (5, 5)
33 self.failUnless(ed.shape == true_size)
34
35
36 ed_manual = N.zeros(true_size, 'd')
37 for i in range(true_size[0]):
38 for j in range(true_size[1]):
39
40 ed_manual[i,j] = ((data[i,:] - data[j,:] )** 2).sum()
41 ed_manual[ed_manual < 0] = 0
42
43 self.failUnless(N.diag(ed_manual).sum() < 0.0000000001)
44 self.failUnless(N.diag(ed).sum() < 0.0000000001)
45
46
47 self.failUnless((ed - ed_manual).sum() < 0.0000001)
48
49
51 data0 = datasets['uni4large'].samples.T
52 weight = N.abs(data0[11, :60])
53
54 self.failUnlessRaises(ValueError, pnorm_w_python,
55 data0[:10,:2], p=1.2, heuristic='buga')
56 self.failUnlessRaises(ValueError, pnorm_w_python,
57 data0[:10,:2], weight=weight)
58
59 self.failUnlessRaises(ValueError, pnorm_w_python,
60 data0[:10,:2], data0[:10, :3],
61 weight=weight)
62 self.failUnlessRaises(ValueError, pnorm_w,
63 data0[:10,:2], data0[:10, :3],
64 weight=weight)
65
66 self.failUnlessRaises(ValueError, pnorm_w,
67 data0[:10,:2], weight=weight)
68
69
70 for did, (data1, data2, w) in enumerate(
71 [ (data0[:2, :60], None, None),
72 (data0[:2, :60], data0[3:4, 1:61], None),
73 (data0[:2, :60], None, weight),
74 (data0[:2, :60], data0[3:4, 1:61], weight),
75 ]):
76
77 for p in [1, 2, 1.2]:
78 kwargs = {'data1': data1,
79 'data2': data2,
80 'weight' : w,
81 'p' : p}
82 d = pnorm_w(**kwargs)
83
84 kwargs0 = kwargs.copy()
85 kwargs0['data2'] = N.zeros(data1.shape)
86 d0 = pnorm_w(**kwargs0)
87 d0norm = N.linalg.norm(d - d0, 'fro')
88
89 for iid, d2 in enumerate(
90 [pnorm_w_python(**kwargs),
91 pnorm_w_python(use_sq_euclidean=True, **kwargs),
92 pnorm_w_python(heuristic='auto', **kwargs),
93 pnorm_w_python(use_sq_euclidean=False, **kwargs),
94 pnorm_w_python(heuristic='auto', use_sq_euclidean=False, **kwargs),
95 pnorm_w_python(heuristic='samples', use_sq_euclidean=False, **kwargs),
96 pnorm_w_python(heuristic='features', use_sq_euclidean=False, **kwargs),
97 ]):
98 dnorm = N.linalg.norm(d2 - d, 'fro')
99 self.failUnless(dnorm/d0norm < 1e-7,
100 msg="Failed comparison of different implementations on "
101 "data #%d, implementation #%d, p=%s. "
102 "Norm of the difference is %g"
103 % (did, iid, p, dnorm))
104
105
108
109
110 if __name__ == '__main__':
111 import runner
112