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.

run_lenet_ps.py 5.1 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136
  1. # Copyright 2022 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. import os
  16. import sys
  17. import mindspore.context as context
  18. import mindspore.dataset as ds
  19. import mindspore.dataset.transforms.c_transforms as C
  20. import mindspore.dataset.vision.c_transforms as CV
  21. import mindspore.nn as nn
  22. from mindspore.common import dtype as mstype
  23. from mindspore.dataset.vision import Inter
  24. from mindspore.nn.metrics import Accuracy
  25. from mindspore.train import Model
  26. from mindspore.train.callback import LossMonitor
  27. from mindspore.common.initializer import TruncatedNormal
  28. DATASET_PATH = "/home/workspace/mindspore_dataset/mnist"
  29. context.set_context(mode=context.GRAPH_MODE, enable_compile_cache=True, compile_cache_path=sys.argv[1])
  30. context.set_ps_context(enable_ps=True)
  31. def conv(in_channels, out_channels, kernel_size, stride=1, padding=0):
  32. """weight initial for conv layer"""
  33. weight = weight_variable()
  34. return nn.Conv2d(in_channels, out_channels,
  35. kernel_size=kernel_size, stride=stride, padding=padding,
  36. weight_init=weight, has_bias=False, pad_mode="valid")
  37. def fc_with_initialize(input_channels, out_channels):
  38. """weight initial for fc layer"""
  39. weight = weight_variable()
  40. bias = weight_variable()
  41. return nn.Dense(input_channels, out_channels, weight, bias)
  42. def weight_variable():
  43. """weight initial"""
  44. return TruncatedNormal(0.02)
  45. class LeNet5(nn.Cell):
  46. def __init__(self, num_class=10, channel=1):
  47. super(LeNet5, self).__init__()
  48. self.num_class = num_class
  49. self.conv1 = conv(channel, 6, 5)
  50. self.conv2 = conv(6, 16, 5)
  51. self.fc1 = fc_with_initialize(16 * 5 * 5, 120)
  52. self.fc2 = fc_with_initialize(120, 84)
  53. self.fc3 = fc_with_initialize(84, self.num_class)
  54. self.relu = nn.ReLU()
  55. self.max_pool2d = nn.MaxPool2d(kernel_size=2, stride=2)
  56. self.flatten = nn.Flatten()
  57. def construct(self, x):
  58. x = self.conv1(x)
  59. x = self.relu(x)
  60. x = self.max_pool2d(x)
  61. x = self.conv2(x)
  62. x = self.relu(x)
  63. x = self.max_pool2d(x)
  64. x = self.flatten(x)
  65. x = self.fc1(x)
  66. x = self.relu(x)
  67. x = self.fc2(x)
  68. x = self.relu(x)
  69. x = self.fc3(x)
  70. return x
  71. def create_dataset(data_path, batch_size=32, repeat_size=1,
  72. num_parallel_workers=1):
  73. """
  74. create dataset for train or test
  75. """
  76. # define dataset
  77. mnist_ds = ds.MnistDataset(data_path)
  78. resize_height, resize_width = 32, 32
  79. rescale = 1.0 / 255.0
  80. shift = 0.0
  81. rescale_nml = 1 / 0.3081
  82. shift_nml = -1 * 0.1307 / 0.3081
  83. # define map operations
  84. resize_op = CV.Resize((resize_height, resize_width), interpolation=Inter.LINEAR) # Bilinear mode
  85. rescale_nml_op = CV.Rescale(rescale_nml, shift_nml)
  86. rescale_op = CV.Rescale(rescale, shift)
  87. hwc2chw_op = CV.HWC2CHW()
  88. type_cast_op = C.TypeCast(mstype.int32)
  89. # apply map operations on images
  90. mnist_ds = mnist_ds.map(operations=type_cast_op, input_columns="label", num_parallel_workers=num_parallel_workers)
  91. mnist_ds = mnist_ds.map(operations=resize_op, input_columns="image", num_parallel_workers=num_parallel_workers)
  92. mnist_ds = mnist_ds.map(operations=rescale_op, input_columns="image", num_parallel_workers=num_parallel_workers)
  93. mnist_ds = mnist_ds.map(operations=rescale_nml_op, input_columns="image", num_parallel_workers=num_parallel_workers)
  94. mnist_ds = mnist_ds.map(operations=hwc2chw_op, input_columns="image", num_parallel_workers=num_parallel_workers)
  95. # apply DatasetOps
  96. buffer_size = 10000
  97. mnist_ds = mnist_ds.shuffle(buffer_size=buffer_size) # 10000 as in LeNet train script
  98. mnist_ds = mnist_ds.batch(batch_size, drop_remainder=True)
  99. mnist_ds = mnist_ds.repeat(repeat_size)
  100. return mnist_ds
  101. if __name__ == "__main__":
  102. network = LeNet5(10)
  103. network.set_param_ps()
  104. net_loss = nn.SoftmaxCrossEntropyWithLogits(sparse=True, reduction="mean")
  105. net_opt = nn.Momentum(network.trainable_params(), 0.01, 0.9)
  106. model = Model(network, net_loss, net_opt, metrics={"Accuracy": Accuracy()})
  107. ds_train = create_dataset(os.path.join(DATASET_PATH, "train"), 32, 1)
  108. model.train(1, ds_train, callbacks=[LossMonitor()], dataset_sink_mode=False)
  109. ds_eval = create_dataset(os.path.join(DATASET_PATH, "test"), 32, 1)
  110. acc = model.eval(ds_eval, dataset_sink_mode=False)
  111. print("Accuracy:", acc['Accuracy'])
  112. assert acc['Accuracy'] > 0.83