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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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. from mindspore.common.initializer import initializer
  24. import mindspore.context as context
  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 = initializer(Tensor(np.array([0.9]).astype(np.float32)), [1])
  45. optimizer = Momentum(filter(lambda x: x.requires_grad, net.get_parameters()), learning_rate, momentum)
  46. criterion = nn.SoftmaxCrossEntropyWithLogits(is_grad=False, sparse=True)
  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 i 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. """
  57. expect output:
  58. [[0.04132498 0.00874167 0.00874167 0.00874167 0.00874167
  59. 0.00874167 0.00874167 0.00874167 0.00874167 0.00874167]]
  60. """
  61. error = np.ones(shape=[1, 10]) * 1.0e-6
  62. return losses