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.4 kB

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