def test__dot_var(self): a = Variable(np.array(1.0)) b = Variable(np.array(1.0)) c = a + b d = square(c) actual = get_dot_graph(d) self.assertIn(f"{id(d.creator)} -> {id(d)}", actual) self.assertIn(f"{id(c)} -> {id(d.creator)}", actual)
def test_tanh(self): x = Variable(np.array(1.0)) y = F.tanh(x) x.name = 'x' y.name = 'y' y.backward(create_graph=True) iters = 0 for i in range(iters): gx = x.grad x.cleargrad() gx.backward(create_graph=True) gx = x.grad gx.name = 'gx' + str(iters + 1) txt = get_dot_graph(gx) with open('test.dot', 'w') as f: f.write(txt)
def plot(self, *inputs, to_file='model.png'): y = self.forward(*inputs) return utils.get_dot_graph(y, verbose=True, to_file=to_file)
''' 計算グラフの可視化は、次のコマンドで行えます $ python step22.py | dot -T png -o sample.png ''' import numpy as np from dezero import Variable from dezero.utils import get_dot_graph def goldstein(x0, x1): y = (1 + (x0 + x1 + 1)**2 * (19 - 14*x0 + 3*x0**2 - 14*x1 + 6*x0*x1 + 3*x1**2)) *\ (30 + (2*x0 - 3*x1)**2 * (18 - 32*x0 + 12*x0**2 + 48*x1 - 36*x0*x1 + 27*x1**2)) return y x0 = Variable(np.array(1.0)) x1 = Variable(np.array(1.0)) y = goldstein(x0, x1) y.backward() x0.name = 'x0' x1.name = 'x1' y.name = 'y' print(get_dot_graph(y))
def my_sin(x, iters=5): y = 0 for i in range(iters): t = (-1)**i * x**(2 * i + 1) / math.factorial(2 * i + 1) y = y + t return y def my_sin(x, threshould=0.0001): y = 0 for i in range(100000): t = (-1)**i * x**(2 * i + 1) / math.factorial(2 * i + 1) y = y + t if abs(t.data) < threshould: break return y x = Variable(np.array(np.pi / 4)) y = my_sin(x) # , threshould=1e-150) y.backward() print('--- approximate sin ---') print(y.data) print(x.grad) # 0.7071032148228457 # 可視化 (dotファイルに保存) x.name = 'x' y.name = 'y' dot = get_dot_graph(y) with open('my_sin.dot', 'w') as o: o.write(dot)
''' y=tanh(x)のn階微分 計算グラフの可視化は、次のコマンドで行えます $ python tanh.py | dot -T png -o sample.png ''' import numpy as np from dezero import Variable from dezero.utils import get_dot_graph import dezero.functions as F x = Variable(np.array(1.0)) y = F.tanh(x) x.name = 'x' y.name = 'y' y.backward(create_graph=True) iters = 3 for i in range(iters): gx = x.grad x.cleargrad() gx.backward(create_graph=True) gx = x.grad gx.name = 'gx' + str(iters + 1) print(get_dot_graph(gx))