• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Copyright 2020 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"""test lenet"""
16import numpy as np
17
18import mindspore.context as context
19import mindspore.nn as nn
20from mindspore import Tensor
21from mindspore.common.api import _cell_graph_executor
22from mindspore.ops import operations as P
23from ....train_step_wrap import train_step_with_loss_warp, train_step_with_sens
24
25context.set_context(mode=context.GRAPH_MODE)
26
27
28class LeNet5(nn.Cell):
29    """LeNet5 definition"""
30
31    def __init__(self):
32        super(LeNet5, self).__init__()
33        self.conv1 = nn.Conv2d(1, 6, 5, pad_mode='valid')
34        self.conv2 = nn.Conv2d(6, 16, 5, pad_mode='valid')
35        self.fc1 = nn.Dense(16 * 5 * 5, 120)
36        self.fc2 = nn.Dense(120, 84)
37        self.fc3 = nn.Dense(84, 10)
38        self.relu = nn.ReLU()
39        self.max_pool2d = nn.MaxPool2d(kernel_size=2, stride=2)
40        self.flatten = P.Flatten()
41
42    def construct(self, x):
43        x = self.max_pool2d(self.relu(self.conv1(x)))
44        x = self.max_pool2d(self.relu(self.conv2(x)))
45        x = self.flatten(x)
46        x = self.relu(self.fc1(x))
47        x = self.relu(self.fc2(x))
48        x = self.fc3(x)
49        return x
50
51
52def test_lenet5_train_step():
53    predict = Tensor(np.ones([1, 1, 32, 32]).astype(np.float32) * 0.01)
54    label = Tensor(np.zeros([1, 10]).astype(np.float32))
55    net = train_step_with_loss_warp(LeNet5())
56    _cell_graph_executor.compile(net, predict, label)
57
58
59def test_lenet5_train_sens():
60    predict = Tensor(np.ones([1, 1, 32, 32]).astype(np.float32) * 0.01)
61    sens = Tensor(np.ones([1, 10]).astype(np.float32))
62    net = train_step_with_sens(LeNet5(), sens)
63    _cell_graph_executor.compile(net, predict)
64
65
66def test_lenet5_train_step_training():
67    predict = Tensor(np.ones([1, 1, 32, 32]).astype(np.float32) * 0.01)
68    label = Tensor(np.zeros([1, 10]).astype(np.float32))
69    net = train_step_with_loss_warp(LeNet5())
70    net.set_train()
71    _cell_graph_executor.compile(net, predict, label)
72