forked from GPflow/GPflowOpt
-
Notifications
You must be signed in to change notification settings - Fork 0
/
test_transforms.py
95 lines (72 loc) · 2.88 KB
/
test_transforms.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
import gpflowopt
import tensorflow as tf
from gpflow import settings
import numpy as np
import pytest
float_type = settings.tf_float
np_float_type = np.float32 if float_type is tf.float32 else np.float64
class DummyTransform(gpflowopt.transforms.DataTransform):
"""
As linear transform overrides backward/build_backward, create a different transform to obtain coverage of the
default implementations
"""
def __init__(self, c):
super(DummyTransform, self).__init__()
self.value = c
def build_forward(self, X):
return X * self.value
def __invert__(self):
return DummyTransform(1 / self.value)
def __str__(self):
return '(dummy)'
transforms = [
(DummyTransform, (2.0,)),
(gpflowopt.transforms.LinearTransform, ([2.0, 3.5], [1.2, 0.7]))
]
@pytest.mark.parametrize('transform,args', transforms)
def test_forward_backward(transform, args):
x_np = np.random.rand(10, 2).astype(np_float_type)
with tf.Session(graph=tf.Graph()):
t = transform(*args)
y = t.forward(x_np)
x = t.backward(y)
np.testing.assert_allclose(x, x_np)
@pytest.mark.parametrize('transform,args', transforms)
def test_invert_np(transform, args):
x_np = np.random.rand(10, 2).astype(np_float_type)
with tf.Session(graph=tf.Graph()):
t = transform(*args)
y = t.forward(x_np)
x = t.backward(y)
xi = (~t).forward(y)
np.testing.assert_allclose(x, x_np)
np.testing.assert_allclose(xi, x_np)
np.testing.assert_allclose(x, xi)
def test_backward_variance_full_cov():
with tf.Session(graph=tf.Graph()) as session:
t = ~gpflowopt.transforms.LinearTransform([2.0, 1.0], [1.2, 0.7])
x = tf.placeholder(float_type, [2, 10, 10])
A = np.random.rand(10, 10)
B1 = np.dot(A, A.T)
A = np.random.rand(10, 10)
B2 = np.dot(A, A.T)
B = np.stack((B1, B2), axis=0)
scaled = t.build_backward_variance(x)
Bs = session.run(scaled, feed_dict={x: B})
np.testing.assert_allclose(Bs[0, :, :] / 4.0, B1)
np.testing.assert_allclose(Bs[1, :, :], B2)
def test_backward_variance():
with tf.Session(graph=tf.Graph()) as session:
t = ~gpflowopt.transforms.LinearTransform([2.0, 1.0], [1.2, 0.7])
x = tf.placeholder(float_type, [10, 2])
B = np.random.rand(10, 2)
scaled = t.build_backward_variance(x)
Bs = session.run(scaled, feed_dict={x: B})
np.testing.assert_allclose(Bs, B * np.array([4, 1]))
def test_assign():
with tf.Session(graph=tf.Graph()):
t1 = gpflowopt.transforms.LinearTransform([2.0, 1.0], [1.2, 0.7])
t2 = gpflowopt.transforms.LinearTransform([1.0, 1.0], [0., 0.])
t1.assign(t2)
np.testing.assert_allclose(t1.A.read_value(), t2.A.read_value())
np.testing.assert_allclose(t1.b.read_value(), t2.b.read_value())