• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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# ============================================================================
15import numpy as np
16import pytest
17
18import mindspore.context as context
19import mindspore.nn as nn
20from mindspore import Tensor
21from mindspore.nn import TrainOneStepCell, WithLossCell
22from mindspore.nn.optim import Momentum
23from mindspore.ops import operations as P
24
25context.set_context(mode=context.GRAPH_MODE, device_target="CPU")
26
27
28class LeNet(nn.Cell):
29    def __init__(self):
30        super(LeNet, self).__init__()
31        self.relu = P.ReLU()
32        self.batch_size = 32
33
34        self.conv1 = nn.Conv2d(1, 6, kernel_size=5, stride=1, padding=0, has_bias=False, pad_mode='valid')
35        self.conv2 = nn.Conv2d(6, 16, kernel_size=5, stride=1, padding=0, has_bias=False, pad_mode='valid')
36        self.pool = nn.MaxPool2d(kernel_size=2, stride=2)
37        self.reshape = P.Reshape()
38        self.fc1 = nn.Dense(400, 120)
39        self.fc2 = nn.Dense(120, 84)
40        self.fc3 = nn.Dense(84, 10)
41
42    def construct(self, input_x):
43        output = self.conv1(input_x)
44        output = self.relu(output)
45        output = self.pool(output)
46        output = self.conv2(output)
47        output = self.relu(output)
48        output = self.pool(output)
49        output = self.reshape(output, (self.batch_size, -1))
50        output = self.fc1(output)
51        output = self.relu(output)
52        output = self.fc2(output)
53        output = self.relu(output)
54        output = self.fc3(output)
55        return output
56
57
58def train(net, data, label):
59    learning_rate = 0.01
60    momentum = 0.9
61
62    optimizer = Momentum(filter(lambda x: x.requires_grad, net.get_parameters()), learning_rate, momentum)
63    criterion = nn.SoftmaxCrossEntropyWithLogits(sparse=True, reduction='mean')
64    net_with_criterion = WithLossCell(net, criterion)
65    train_network = TrainOneStepCell(net_with_criterion, optimizer)  # optimizer
66    train_network.set_train()
67    res = train_network(data, label)
68    print("+++++++++Loss+++++++++++++")
69    print(res)
70    print("+++++++++++++++++++++++++++")
71    assert res
72
73
74@pytest.mark.level1
75@pytest.mark.platform_x86_cpu
76@pytest.mark.env_onecard
77def test_lenet():
78    data = Tensor(np.ones([32, 1, 32, 32]).astype(np.float32) * 0.01)
79    label = Tensor(np.ones([32]).astype(np.int32))
80    net = LeNet()
81    train(net, data, label)
82