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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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. grad_all_with_sens = C.GradOperation(get_all=True, sens_param=True)
  25. batch_size = 1
  26. channel = 1
  27. height = 32
  28. weight = 32
  29. num_class = 10
  30. class LeNetGrad(nn.Cell):
  31. """Backward of LeNet"""
  32. def __init__(self, network):
  33. super(LeNetGrad, self).__init__()
  34. self.grad_op = grad_all_with_sens
  35. self.network = network
  36. def construct(self, x, sens):
  37. grad_op = self.grad_op(self.network)(x, sens)
  38. return grad_op
  39. def test_compile():
  40. """Compile forward graph"""
  41. net = LeNet(num_class=num_class)
  42. np.random.seed(7)
  43. inp = Tensor(np.array(np.random.randn(batch_size,
  44. channel,
  45. height,
  46. weight) * 3, np.float32))
  47. _executor.compile(net, inp)
  48. def test_compile_grad():
  49. """Compile forward and backward graph"""
  50. net = LeNet5(num_class=num_class)
  51. inp = Tensor(np.array(np.random.randn(batch_size,
  52. channel,
  53. height,
  54. weight) * 3, np.float32))
  55. sens = Tensor(np.ones([batch_size, num_class]).astype(np.float32))
  56. grad_op = LeNetGrad(net)
  57. _executor.compile(grad_op, inp, sens)