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_train.py 6.2 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170
  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. """ test model train """
  16. import numpy as np
  17. import mindspore.nn as nn
  18. from mindspore.ops import operations as P
  19. from mindspore.common.initializer import initializer
  20. from mindspore import Tensor, Parameter, Model
  21. from mindspore.nn.loss import SoftmaxCrossEntropyWithLogits
  22. from mindspore.nn.optim import Momentum
  23. # fn is a funcation use i as input
  24. def lr_gen(fn, epoch_size):
  25. for i in range(epoch_size):
  26. yield fn(i)
  27. def me_train_tensor(net, input_np, label_np, epoch_size=2):
  28. """me_train_tensor"""
  29. loss = SoftmaxCrossEntropyWithLogits(is_grad=False, sparse=True, reduction="mean")
  30. opt = Momentum(filter(lambda x: x.requires_grad, net.get_parameters()), lr_gen(lambda i: 0.1, epoch_size), 0.9, 0.01, 1024)
  31. Model(net, loss, opt)
  32. _network = nn.WithLossCell(net, loss)
  33. _train_net = nn.TrainOneStepCell(_network, opt)
  34. _train_net.set_train()
  35. label_np = np.argmax(label_np, axis=-1).astype(np.int32)
  36. for epoch in range(0, epoch_size):
  37. print(f"epoch %d"%(epoch))
  38. _train_net(Tensor(input_np), Tensor(label_np))
  39. def test_bias_add(test_with_simu):
  40. """test_bias_add"""
  41. import mindspore.context as context
  42. is_pynative_mode = (context.get_context("mode") == context.PYNATIVE_MODE)
  43. # training api is implemented under Graph mode
  44. if is_pynative_mode:
  45. context.set_context(mode=context.GRAPH_MODE)
  46. if test_with_simu:
  47. return
  48. class Net(nn.Cell):
  49. """Net definition"""
  50. def __init__(self,
  51. output_channels,
  52. bias_init='zeros',
  53. ):
  54. super(Net, self).__init__()
  55. self.biasAdd = P.BiasAdd()
  56. if isinstance(bias_init, Tensor):
  57. if bias_init.dim() != 1 or bias_init.shape()[0] != output_channels:
  58. raise ValueError("bias_init shape error")
  59. self.bias = Parameter(initializer(
  60. bias_init, [output_channels]), name="bias")
  61. def construct(self, input_x):
  62. return self.biasAdd(input_x, self.bias)
  63. bias_init = Tensor(np.ones([3]).astype(np.float32))
  64. input_np = np.ones([1, 3, 3, 3], np.float32)
  65. label_np = np.ones([1, 3, 3, 3], np.int32) * 2
  66. me_train_tensor(Net(3, bias_init=bias_init), input_np, label_np)
  67. def test_conv(test_with_simu):
  68. """test_conv"""
  69. import mindspore.context as context
  70. is_pynative_mode = (context.get_context("mode") == context.PYNATIVE_MODE)
  71. # training api is implemented under Graph mode
  72. if is_pynative_mode:
  73. context.set_context(mode=context.GRAPH_MODE)
  74. if test_with_simu:
  75. return
  76. class Net(nn.Cell):
  77. "Net definition"""
  78. def __init__(self,
  79. cin,
  80. cout,
  81. kernel_size):
  82. super(Net, self).__init__()
  83. Tensor(np.ones([6, 3, 3, 3]).astype(np.float32) * 0.01)
  84. self.conv = nn.Conv2d(cin,
  85. cout,
  86. kernel_size)
  87. def construct(self, input_x):
  88. return self.conv(input_x)
  89. net = Net(3, 6, (3, 3))
  90. input_np = np.ones([1, 3, 32, 32]).astype(np.float32) * 0.01
  91. label_np = np.ones([1, 6, 32, 32]).astype(np.int32)
  92. me_train_tensor(net, input_np, label_np)
  93. def test_net():
  94. """test_net"""
  95. import mindspore.context as context
  96. is_pynative_mode = (context.get_context("mode") == context.PYNATIVE_MODE)
  97. # training api is implemented under Graph mode
  98. if is_pynative_mode:
  99. context.set_context(mode=context.GRAPH_MODE)
  100. class Net(nn.Cell):
  101. """Net definition"""
  102. def __init__(self):
  103. super(Net, self).__init__()
  104. Tensor(np.ones([64, 3, 7, 7]).astype(np.float32) * 0.01)
  105. self.conv = nn.Conv2d(3, 64, (7, 7), pad_mode="same", stride=2)
  106. self.relu = nn.ReLU()
  107. self.bn = nn.BatchNorm2d(64)
  108. self.mean = P.ReduceMean(keep_dims=True)
  109. self.flatten = nn.Flatten()
  110. self.dense = nn.Dense(64, 12)
  111. def construct(self, input_x):
  112. output = input_x
  113. output = self.conv(output)
  114. output = self.bn(output)
  115. output = self.relu(output)
  116. output = self.mean(output, (-2, -1))
  117. output = self.flatten(output)
  118. output = self.dense(output)
  119. return output
  120. net = Net()
  121. input_np = np.ones([32, 3, 224, 224]).astype(np.float32) * 0.01
  122. label_np = np.ones([32, 12]).astype(np.int32)
  123. me_train_tensor(net, input_np, label_np)
  124. def test_bn():
  125. """test_bn"""
  126. import mindspore.context as context
  127. is_pynative_mode = (context.get_context("mode") == context.PYNATIVE_MODE)
  128. # training api is implemented under Graph mode
  129. if is_pynative_mode:
  130. context.set_context(mode=context.GRAPH_MODE)
  131. class Net(nn.Cell):
  132. """Net definition"""
  133. def __init__(self, cin, cout):
  134. super(Net, self).__init__()
  135. self.bn = nn.BatchNorm2d(cin)
  136. self.flatten = nn.Flatten()
  137. self.dense = nn.Dense(cin, cout)
  138. def construct(self, input_x):
  139. output = input_x
  140. output = self.bn(output)
  141. output = self.flatten(output)
  142. output = self.dense(output)
  143. return output
  144. net = Net(2048, 16)
  145. input_np = np.ones([32, 2048, 1, 1]).astype(np.float32) * 0.01
  146. label_np = np.ones([32, 16]).astype(np.int32)
  147. me_train_tensor(net, input_np, label_np)