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.

lenet.py 2.5 kB

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