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.1 kB

3 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  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 Normal
  18. class LeNet5(nn.Cell):
  19. """
  20. Lenet network
  21. Args:
  22. num_class (int): Number of classes. Default: 10.
  23. num_channel (int): Number of channels. Default: 1.
  24. Returns:
  25. Tensor, output tensor
  26. Examples:
  27. >>> LeNet(num_class=10)
  28. """
  29. def __init__(self, num_class=10, num_channel=1, include_top=True):
  30. super(LeNet5, self).__init__()
  31. self.conv1 = nn.Conv2d(num_channel, 6, 5, pad_mode='valid')
  32. self.conv2 = nn.Conv2d(6, 16, 5, pad_mode='valid')
  33. self.relu = nn.ReLU()
  34. self.max_pool2d = nn.MaxPool2d(kernel_size=2, stride=2)
  35. self.include_top = include_top
  36. if self.include_top:
  37. self.flatten = nn.Flatten()
  38. self.fc1 = nn.Dense(16 * 5 * 5, 120, weight_init=Normal(0.02))
  39. self.fc2 = nn.Dense(120, 84, weight_init=Normal(0.02))
  40. self.fc3 = nn.Dense(84, num_class, weight_init=Normal(0.02))
  41. def construct(self, x):
  42. x = self.conv1(x)
  43. x = self.relu(x)
  44. x = self.max_pool2d(x)
  45. x = self.conv2(x)
  46. x = self.relu(x)
  47. x = self.max_pool2d(x)
  48. if not self.include_top:
  49. return x
  50. x = self.flatten(x)
  51. x = self.relu(self.fc1(x))
  52. x = self.relu(self.fc2(x))
  53. x = self.fc3(x)
  54. return x