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.py 3.4 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  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.module import Linear, Module
  16. from megengine.optimizer import SGD
  17. batch_size = 64
  18. data_shape = (batch_size, 2)
  19. label_shape = (batch_size,)
  20. def minibatch_generator():
  21. while True:
  22. inp_data = np.zeros((batch_size, 2))
  23. label = np.zeros(batch_size, dtype=np.int32)
  24. for i in range(batch_size):
  25. # [x0, x1], sampled from U[-1, 1]
  26. inp_data[i, :] = np.random.rand(2) * 2 - 1
  27. label[i] = 0 if np.prod(inp_data[i]) < 0 else 1
  28. yield inp_data.astype(np.float32), label.astype(np.int32)
  29. def calculate_precision(data: np.ndarray, pred: np.ndarray) -> float:
  30. """ Calculate precision for given data and prediction.
  31. :type data: [[x, y], ...]
  32. :param data: Input data
  33. :type pred: [[x_pred, y_pred], ...]
  34. :param pred: Network output data
  35. """
  36. correct = 0
  37. assert len(data) == len(pred)
  38. for inp_data, pred_output in zip(data, pred):
  39. label = 0 if np.prod(inp_data) < 0 else 1
  40. pred_label = np.argmax(pred_output)
  41. if pred_label == label:
  42. correct += 1
  43. return float(correct) / len(data)
  44. class XORNet(Module):
  45. def __init__(self):
  46. self.mid_layers = 14
  47. self.num_class = 2
  48. super().__init__()
  49. self.fc0 = Linear(self.num_class, self.mid_layers, bias=True)
  50. self.fc1 = Linear(self.mid_layers, self.mid_layers, bias=True)
  51. self.fc2 = Linear(self.mid_layers, self.num_class, bias=True)
  52. def forward(self, x):
  53. x = self.fc0(x)
  54. x = F.tanh(x)
  55. x = self.fc1(x)
  56. x = F.tanh(x)
  57. x = self.fc2(x)
  58. return x
  59. def test_training_converge():
  60. net = XORNet()
  61. opt = SGD(net.parameters(), lr=0.01, momentum=0.9, weight_decay=5e-4)
  62. gm = ad.GradManager().attach(net.parameters())
  63. def train(data, label):
  64. with gm:
  65. pred = net(data)
  66. loss = F.nn.cross_entropy(pred, label)
  67. gm.backward(loss)
  68. return loss
  69. def infer(data):
  70. return net(data)
  71. train_dataset = minibatch_generator()
  72. losses = []
  73. for data, label in itertools.islice(train_dataset, 2000):
  74. data = Tensor(data, dtype=np.float32)
  75. label = Tensor(label, dtype=np.int32)
  76. opt.clear_grad()
  77. loss = train(data, label)
  78. opt.step()
  79. losses.append(loss.numpy())
  80. assert np.mean(losses[-100:]) < 0.1, "Final training Loss must be low enough"
  81. ngrid = 10
  82. x = np.linspace(-1.0, 1.0, ngrid)
  83. xx, yy = np.meshgrid(x, x)
  84. xx = xx.reshape((ngrid * ngrid, 1))
  85. yy = yy.reshape((ngrid * ngrid, 1))
  86. data = mge.tensor(np.concatenate((xx, yy), axis=1).astype(np.float32))
  87. pred = infer(data).numpy()
  88. precision = calculate_precision(data.numpy(), pred)
  89. assert precision == 1.0, "Test precision must be high enough, get {}".format(
  90. precision
  91. )

MegEngine 安装包中集成了使用 GPU 运行代码所需的 CUDA 环境,不用区分 CPU 和 GPU 版。 如果想要运行 GPU 程序,请确保机器本身配有 GPU 硬件设备并安装好驱动。 如果你想体验在云端 GPU 算力平台进行深度学习开发的感觉,欢迎访问 MegStudio 平台