()
| 77 | |
| 78 | |
| 79 | def test_batchnorm(): |
| 80 | nr_chan = 8 |
| 81 | data_shape = (3, nr_chan, 4) |
| 82 | momentum = 0.9 |
| 83 | bn = BatchNorm1d(nr_chan, momentum=momentum) |
| 84 | running_mean = np.zeros((1, nr_chan, 1), dtype=np.float32) |
| 85 | running_var = np.ones((1, nr_chan, 1), dtype=np.float32) |
| 86 | for i in range(3): |
| 87 | xv = np.random.normal(loc=2.3, size=data_shape).astype(np.float32) |
| 88 | mean = np.mean(np.mean(xv, axis=0, keepdims=True), axis=2, keepdims=True) |
| 89 | xv_transposed = np.transpose(xv, [0, 2, 1]).reshape( |
| 90 | (data_shape[0] * data_shape[2], nr_chan) |
| 91 | ) |
| 92 | |
| 93 | var_biased = np.var(xv_transposed, axis=0).reshape((1, nr_chan, 1)) |
| 94 | sd = np.sqrt(var_biased + bn.eps) |
| 95 | |
| 96 | var_unbiased = np.var(xv_transposed, axis=0, ddof=1).reshape((1, nr_chan, 1)) |
| 97 | running_mean = running_mean * momentum + mean * (1 - momentum) |
| 98 | running_var = running_var * momentum + var_unbiased * (1 - momentum) |
| 99 | |
| 100 | yv = bn(Tensor(xv)) |
| 101 | yv_expect = (xv - mean) / sd |
| 102 | |
| 103 | _assert_allclose(yv.numpy(), yv_expect) |
| 104 | _assert_allclose(bn.running_mean.numpy().reshape(-1), running_mean.reshape(-1)) |
| 105 | _assert_allclose(bn.running_var.numpy().reshape(-1), running_var.reshape(-1)) |
| 106 | |
| 107 | # test set 'training' flag to False |
| 108 | mean_backup = bn.running_mean.numpy() |
| 109 | var_backup = bn.running_var.numpy() |
| 110 | bn.training = False |
| 111 | xv = np.random.normal(loc=2.3, size=data_shape).astype(np.float32) |
| 112 | data = Tensor(xv) |
| 113 | yv1 = bn(data) |
| 114 | yv2 = bn(data) |
| 115 | np.testing.assert_equal(yv1.numpy(), yv2.numpy()) |
| 116 | np.testing.assert_equal(mean_backup, bn.running_mean.numpy()) |
| 117 | np.testing.assert_equal(var_backup, bn.running_var.numpy()) |
| 118 | yv_expect = (xv - running_mean) / np.sqrt(running_var + bn.eps) |
| 119 | _assert_allclose(yv1.numpy(), yv_expect) |
| 120 | |
| 121 | |
| 122 | def test_syncbn1d(): |
nothing calls this directly
no test coverage detected