|
23 | 23 |
|
24 | 24 | class TestCalcGradient(unittest.TestCase):
|
25 | 25 | def test_calc_gradient(self):
|
26 |
| - x = layers.create_parameter(dtype="float32", shape=[5, 10]) |
27 |
| - y = layers.create_parameter(dtype="float32", shape=[10, 8]) |
28 |
| - mul_out = layers.mul(x=x, y=y) |
29 |
| - mean_out = layers.mean(mul_out) |
30 |
| - a = calc_gradient(mean_out, mul_out) |
31 |
| - b = calc_gradient(mean_out, x) |
| 26 | + main = fluid.Program() |
| 27 | + startup = fluid.Program() |
| 28 | + with fluid.program_guard(main, startup): |
| 29 | + x = layers.create_parameter(dtype="float32", shape=[5, 10]) |
| 30 | + y = layers.create_parameter(dtype="float32", shape=[10, 8]) |
| 31 | + mul_out = layers.mul(x=x, y=y) |
| 32 | + mean_out = layers.mean(mul_out) |
| 33 | + a = calc_gradient(mean_out, mul_out) |
| 34 | + b = calc_gradient(mean_out, x) |
32 | 35 | place = fluid.CPUPlace()
|
33 | 36 | exe = fluid.Executor(place)
|
34 |
| - exe.run(fluid.default_startup_program()) |
35 |
| - exe.run(fluid.default_main_program(), feed={}, fetch_list=[a, b]) |
| 37 | + exe.run(startup) |
| 38 | + exe.run(main, feed={}, fetch_list=[a, b]) |
| 39 | + |
| 40 | + |
| 41 | +class TestDoubleGrad(unittest.TestCase): |
| 42 | + def test1(self): |
| 43 | + main = fluid.Program() |
| 44 | + startup = fluid.Program() |
| 45 | + with fluid.program_guard(main, startup): |
| 46 | + net = lambda x: x * x |
| 47 | + x = fluid.layers.create_parameter( |
| 48 | + name='x', |
| 49 | + shape=[1], |
| 50 | + dtype='float32', |
| 51 | + default_initializer=fluid.initializer.Constant(3)) |
| 52 | + grad1, = fluid.gradients(net(x), x) # 2x = 6 |
| 53 | + z = net(x - grad1) |
| 54 | + grad2, = fluid.gradients(z, x) # gradients( (x - 2x)^2) = 2x = 6 |
| 55 | + |
| 56 | + place = fluid.CPUPlace() |
| 57 | + exe = fluid.Executor(place) |
| 58 | + exe.run(startup) |
| 59 | + out = exe.run(main, fetch_list=[grad1.name, grad2.name]) |
| 60 | + self.assertEqual(6, out[0][0]) |
| 61 | + self.assertEqual(6, out[1][0]) |
| 62 | + |
| 63 | + def test2(self): |
| 64 | + main = fluid.Program() |
| 65 | + startup = fluid.Program() |
| 66 | + with fluid.program_guard(main, startup): |
| 67 | + x = fluid.layers.create_parameter( |
| 68 | + name='x', |
| 69 | + shape=[1], |
| 70 | + dtype='float32', |
| 71 | + default_initializer=fluid.initializer.Constant(1)) |
| 72 | + y = x * x |
| 73 | + dx1, = fluid.gradients(y, x) |
| 74 | + z = dx1 * dx1 + y * y |
| 75 | + dx2, = fluid.gradients(z, x) |
| 76 | + |
| 77 | + place = fluid.CPUPlace() |
| 78 | + exe = fluid.Executor(place) |
| 79 | + exe.run(startup) |
| 80 | + out, = exe.run(main, fetch_list=[dx2]) |
| 81 | + self.assertEqual(12, out[0]) |
36 | 82 |
|
37 | 83 |
|
38 | 84 | if __name__ == "__main__":
|
|
0 commit comments