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