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_momentum_op.py 2.5 kB

5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. # Copyright 2019 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. import pytest
  16. import numpy as np
  17. import mindspore.nn as nn
  18. from mindspore.nn.optim import Momentum
  19. from mindspore.ops import operations as P
  20. from mindspore.nn import TrainOneStepCell, WithLossCell
  21. from mindspore.nn import Dense
  22. from mindspore import Tensor
  23. import mindspore.context as context
  24. context.set_context(mode=context.GRAPH_MODE, device_target="CPU")
  25. class MomentumNet(nn.Cell):
  26. def __init__(self):
  27. super(MomentumNet, self).__init__()
  28. self.batch_size = 1
  29. self.reshape = P.Reshape()
  30. weight = Tensor(np.ones([10, 16]).astype(np.float32) * 0.01)
  31. self.fc1 = Dense(16, 10, weight_init=weight)
  32. def construct(self, input_x):
  33. output = self.reshape(input_x, (self.batch_size, -1))
  34. output = self.fc1(output)
  35. return output
  36. @pytest.mark.level0
  37. @pytest.mark.platform_x86_cpu
  38. @pytest.mark.env_onecard
  39. def test_momentum():
  40. epoch = 13
  41. net = MomentumNet()
  42. learning_rate = 0.1
  43. momentum = 0.9
  44. optimizer = Momentum(filter(lambda x: x.requires_grad, net.get_parameters()), learning_rate, momentum)
  45. criterion = nn.SoftmaxCrossEntropyWithLogits(is_grad=False, sparse=True)
  46. net_with_criterion = WithLossCell(net, criterion)
  47. train_network = TrainOneStepCell(net_with_criterion, optimizer) # optimizer
  48. train_network.set_train()
  49. losses = []
  50. for i in range(epoch):
  51. data = Tensor(np.arange(0, 16).reshape(1, 1, 4, 4).astype(np.float32) * 0.01)
  52. label = Tensor(np.array([0]).astype(np.int32))
  53. loss = train_network(data, label)
  54. losses.append(loss)
  55. print("================================")
  56. print(losses)
  57. """
  58. expect output:
  59. [[0.04132498 0.00874167 0.00874167 0.00874167 0.00874167
  60. 0.00874167 0.00874167 0.00874167 0.00874167 0.00874167]]
  61. """
  62. error = np.ones(shape=[1, 10]) * 1.0e-6
  63. return losses