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

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