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"""LeNet.""" 16import mindspore.nn as nn 17from mindspore.common.initializer import TruncatedNormal 18 19 20def conv(in_channels, out_channels, kernel_size, stride=1, padding=0): 21 """weight initial for conv layer""" 22 weight = weight_variable() 23 return nn.Conv2d(in_channels, out_channels, 24 kernel_size=kernel_size, stride=stride, padding=padding, 25 weight_init=weight, has_bias=False, pad_mode="valid") 26 27 28def fc_with_initialize(input_channels, out_channels): 29 """weight initial for fc layer""" 30 weight = weight_variable() 31 bias = weight_variable() 32 return nn.Dense(input_channels, out_channels, weight, bias) 33 34 35def weight_variable(): 36 """weight initial""" 37 return TruncatedNormal(0.02) 38 39 40class LeNet5(nn.Cell): 41 """ 42 Lenet network 43 44 Args: 45 num_class (int): Num classes. Default: 10. 46 47 Returns: 48 Tensor, output tensor 49 Examples: 50 >>> LeNet(num_class=10) 51 52 """ 53 def __init__(self, num_class=10, channel=1): 54 super(LeNet5, self).__init__() 55 self.num_class = num_class 56 self.conv1 = conv(channel, 6, 5) 57 self.conv2 = conv(6, 16, 5) 58 self.fc1 = fc_with_initialize(16 * 5 * 5, 120) 59 self.fc2 = fc_with_initialize(120, 84) 60 self.fc3 = fc_with_initialize(84, self.num_class) 61 self.relu = nn.ReLU() 62 self.max_pool2d = nn.MaxPool2d(kernel_size=2, stride=2) 63 self.flatten = nn.Flatten() 64 65 def construct(self, x): 66 x = self.conv1(x) 67 x = self.relu(x) 68 x = self.max_pool2d(x) 69 x = self.conv2(x) 70 x = self.relu(x) 71 x = self.max_pool2d(x) 72 x = self.flatten(x) 73 x = self.fc1(x) 74 x = self.relu(x) 75 x = self.fc2(x) 76 x = self.relu(x) 77 x = self.fc3(x) 78 return x 79