You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

test_converge_with_drop.py 3.6 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119
  1. # -*- coding: utf-8 -*-
  2. # MegEngine is Licensed under the Apache License, Version 2.0 (the "License")
  3. #
  4. # Copyright (c) 2014-2021 Megvii Inc. All rights reserved.
  5. #
  6. # Unless required by applicable law or agreed to in writing,
  7. # software distributed under the License is distributed on an
  8. # "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9. import itertools
  10. import numpy as np
  11. import megengine as mge
  12. import megengine.autodiff as ad
  13. import megengine.functional as F
  14. from megengine import Tensor
  15. from megengine.core import get_option, set_option
  16. from megengine.module import Linear, Module
  17. from megengine.optimizer import SGD
  18. batch_size = 64
  19. data_shape = (batch_size, 2)
  20. label_shape = (batch_size,)
  21. def minibatch_generator():
  22. while True:
  23. inp_data = np.zeros((batch_size, 2))
  24. label = np.zeros(batch_size, dtype=np.int32)
  25. for i in range(batch_size):
  26. # [x0, x1], sampled from U[-1, 1]
  27. inp_data[i, :] = np.random.rand(2) * 2 - 1
  28. label[i] = 0 if np.prod(inp_data[i]) < 0 else 1
  29. yield inp_data.astype(np.float32), label.astype(np.int32)
  30. def calculate_precision(data: np.ndarray, pred: np.ndarray) -> float:
  31. """ Calculate precision for given data and prediction.
  32. :type data: [[x, y], ...]
  33. :param data: Input data
  34. :type pred: [[x_pred, y_pred], ...]
  35. :param pred: Network output data
  36. """
  37. correct = 0
  38. assert len(data) == len(pred)
  39. for inp_data, pred_output in zip(data, pred):
  40. label = 0 if np.prod(inp_data) < 0 else 1
  41. pred_label = np.argmax(pred_output)
  42. if pred_label == label:
  43. correct += 1
  44. return float(correct) / len(data)
  45. class XORNet(Module):
  46. def __init__(self):
  47. self.mid_layers = 14
  48. self.num_class = 2
  49. super().__init__()
  50. self.fc0 = Linear(self.num_class, self.mid_layers, bias=True)
  51. self.fc1 = Linear(self.mid_layers, self.mid_layers, bias=True)
  52. self.fc2 = Linear(self.mid_layers, self.num_class, bias=True)
  53. def forward(self, x):
  54. y = self.fc0(x)
  55. x = F.tanh(y)
  56. y = self.fc1(x)
  57. x = F.tanh(y)
  58. x = self.fc2(x)
  59. y = (x + x) / 2 # in order to test drop()
  60. y._drop()
  61. return y
  62. def test_training_converge_with_drop():
  63. set_option("enable_drop", 1)
  64. net = XORNet()
  65. opt = SGD(net.parameters(), lr=0.01, momentum=0.9, weight_decay=5e-4)
  66. gm = ad.GradManager().attach(net.parameters())
  67. def train(data, label):
  68. with gm:
  69. pred = net(data)
  70. loss = F.nn.cross_entropy(pred, label)
  71. gm.backward(loss)
  72. return loss
  73. def infer(data):
  74. return net(data)
  75. train_dataset = minibatch_generator()
  76. losses = []
  77. for data, label in itertools.islice(train_dataset, 2000):
  78. data = Tensor(data, dtype=np.float32)
  79. label = Tensor(label, dtype=np.int32)
  80. opt.clear_grad()
  81. loss = train(data, label)
  82. opt.step()
  83. losses.append(loss.numpy())
  84. assert np.mean(losses[-100:]) < 0.1, "Final training Loss must be low enough"
  85. ngrid = 10
  86. x = np.linspace(-1.0, 1.0, ngrid)
  87. xx, yy = np.meshgrid(x, x)
  88. xx = xx.reshape((ngrid * ngrid, 1))
  89. yy = yy.reshape((ngrid * ngrid, 1))
  90. data = mge.tensor(np.concatenate((xx, yy), axis=1).astype(np.float32))
  91. pred = infer(Tensor(data)).numpy()
  92. precision = calculate_precision(data.numpy(), pred)
  93. assert precision == 1.0, "Test precision must be high enough, get {}".format(
  94. precision
  95. )
  96. set_option("enable_drop", 0)