forked from WegraLee/deep-learning-from-scratch-3
-
Notifications
You must be signed in to change notification settings - Fork 0
/
test_basic_math.py
97 lines (78 loc) · 2.66 KB
/
test_basic_math.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
95
96
97
import unittest
import numpy as np
from dezero import Variable
from dezero.utils import gradient_check, array_equal
import dezero.functions as F
class TestAdd(unittest.TestCase):
def test_forward1(self):
x0 = np.array([1, 2, 3])
x1 = Variable(np.array([1, 2, 3]))
y = x0 + x1
res = y.data
expected = np.array([2, 4, 6])
self.assertTrue(array_equal(res, expected))
def test_datatype(self):
"""np.float64ではなく、0次元のndarrayを返すかどうか"""
x = Variable(np.array(2.0))
y = x ** 2
self.assertFalse(np.isscalar(y))
def test_backward1(self):
x = Variable(np.random.randn(3, 3))
y = np.random.randn(3, 3)
f = lambda x: x + y
self.assertTrue(gradient_check(f, x))
def test_backward2(self):
x = Variable(np.random.randn(3, 3))
y = np.random.randn(3, 1)
f = lambda x: x + y
self.assertTrue(gradient_check(f, x))
def test_backward3(self):
x = np.random.randn(3, 3)
y = np.random.randn(3, 1)
self.assertTrue(gradient_check(F.add, x, y))
class TestMul(unittest.TestCase):
def test_forward1(self):
x0 = np.array([1, 2, 3])
x1 = Variable(np.array([1, 2, 3]))
y = x0 * x1
res = y.data
expected = np.array([1, 4, 9])
self.assertTrue(array_equal(res, expected))
def test_backward1(self):
x = np.random.randn(3, 3)
y = np.random.randn(3, 3)
f = lambda x: x * y
self.assertTrue(gradient_check(f, x))
def test_backward2(self):
x = np.random.randn(3, 3)
y = np.random.randn(3, 1)
f = lambda x: x * y
self.assertTrue(gradient_check(f, x))
def test_backward3(self):
x = np.random.randn(3, 3)
y = np.random.randn(3, 1)
f = lambda y: x * y
self.assertTrue(gradient_check(f, x))
class TestDiv(unittest.TestCase):
def test_forward1(self):
x0 = np.array([1, 2, 3])
x1 = Variable(np.array([1, 2, 3]))
y = x0 / x1
res = y.data
expected = np.array([1, 1, 1])
self.assertTrue(array_equal(res, expected))
def test_backward1(self):
x = np.random.randn(3, 3)
y = np.random.randn(3, 3)
f = lambda x: x / y
self.assertTrue(gradient_check(f, x))
def test_backward2(self):
x = np.random.randn(3, 3)
y = np.random.randn(3, 1)
f = lambda x: x / y
self.assertTrue(gradient_check(f, x))
def test_backward3(self):
x = np.random.randn(3, 3)
y = np.random.randn(3, 1)
f = lambda x: x / y
self.assertTrue(gradient_check(f, x))