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_lenet.py 2.2 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. # Copyright 2020 Huawei Technologies Co., Ltd
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. # ============================================================================
  15. """LeNet test."""
  16. import numpy as np
  17. from lenet import LeNet5
  18. import mindspore.nn as nn
  19. import mindspore.ops.composite as C
  20. from mindspore import Tensor
  21. from mindspore import context
  22. from mindspore.common.api import _executor
  23. context.set_context(mode=context.GRAPH_MODE)
  24. batch_size = 1
  25. channel = 1
  26. height = 32
  27. weight = 32
  28. num_class = 10
  29. class LeNetGrad(nn.Cell):
  30. """Backward of LeNet"""
  31. def __init__(self, network):
  32. super(LeNetGrad, self).__init__()
  33. self.grad_op = C.grad_all_with_sens
  34. self.network = network
  35. def construct(self, x, sens):
  36. grad_op = self.grad_op(self.network)(x, sens)
  37. return grad_op
  38. def test_compile():
  39. """Compile forward graph"""
  40. net = LeNet(num_class=num_class)
  41. np.random.seed(7)
  42. inp = Tensor(np.array(np.random.randn(batch_size,
  43. channel,
  44. height,
  45. weight) * 3, np.float32))
  46. _executor.compile(net, inp)
  47. def test_compile_grad():
  48. """Compile forward and backward graph"""
  49. net = LeNet5(num_class=num_class)
  50. inp = Tensor(np.array(np.random.randn(batch_size,
  51. channel,
  52. height,
  53. weight) * 3, np.float32))
  54. sens = Tensor(np.ones([batch_size, num_class]).astype(np.float32))
  55. grad_op = LeNetGrad(net)
  56. _executor.compile(grad_op, inp, sens)