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.

mnist_train.py 3.4 kB

5 years ago
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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. import os
  16. import sys
  17. import mindspore.nn as nn
  18. from mindspore import context, Tensor
  19. from mindspore.train.callback import ModelCheckpoint, CheckpointConfig, LossMonitor
  20. from mindspore.train.serialization import load_checkpoint, load_param_into_net
  21. from mindspore.train import Model
  22. import mindspore.ops.operations as P
  23. from mindspore.nn.metrics import Accuracy
  24. from mindspore.ops import functional as F
  25. from mindspore.common import dtype as mstype
  26. from mindarmour.utils.logger import LogUtil
  27. from lenet5_net import LeNet5
  28. sys.path.append("..")
  29. from data_processing import generate_mnist_dataset
  30. LOGGER = LogUtil.get_instance()
  31. TAG = 'Lenet5_train'
  32. class CrossEntropyLoss(nn.Cell):
  33. """
  34. Define loss for network
  35. """
  36. def __init__(self):
  37. super(CrossEntropyLoss, self).__init__()
  38. self.cross_entropy = P.SoftmaxCrossEntropyWithLogits()
  39. self.mean = P.ReduceMean()
  40. self.one_hot = P.OneHot()
  41. self.on_value = Tensor(1.0, mstype.float32)
  42. self.off_value = Tensor(0.0, mstype.float32)
  43. def construct(self, logits, label):
  44. label = self.one_hot(label, F.shape(logits)[1], self.on_value, self.off_value)
  45. loss = self.cross_entropy(logits, label)[0]
  46. loss = self.mean(loss, (-1,))
  47. return loss
  48. def mnist_train(epoch_size, batch_size, lr, momentum):
  49. context.set_context(mode=context.GRAPH_MODE, device_target="Ascend",
  50. enable_mem_reuse=False)
  51. lr = lr
  52. momentum = momentum
  53. epoch_size = epoch_size
  54. mnist_path = "./MNIST_unzip/"
  55. ds = generate_mnist_dataset(os.path.join(mnist_path, "train"),
  56. batch_size=batch_size, repeat_size=1)
  57. network = LeNet5()
  58. network.set_train()
  59. net_loss = CrossEntropyLoss()
  60. net_opt = nn.Momentum(network.trainable_params(), lr, momentum)
  61. config_ck = CheckpointConfig(save_checkpoint_steps=1875, keep_checkpoint_max=10)
  62. ckpoint_cb = ModelCheckpoint(prefix="checkpoint_lenet", directory='./trained_ckpt_file/', config=config_ck)
  63. model = Model(network, net_loss, net_opt, metrics={"Accuracy": Accuracy()})
  64. LOGGER.info(TAG, "============== Starting Training ==============")
  65. model.train(epoch_size, ds, callbacks=[ckpoint_cb, LossMonitor()], dataset_sink_mode=False) # train
  66. LOGGER.info(TAG, "============== Starting Testing ==============")
  67. param_dict = load_checkpoint("trained_ckpt_file/checkpoint_lenet-10_1875.ckpt")
  68. load_param_into_net(network, param_dict)
  69. ds_eval = generate_mnist_dataset(os.path.join(mnist_path, "test"), batch_size=batch_size)
  70. acc = model.eval(ds_eval)
  71. LOGGER.info(TAG, "============== Accuracy: %s ==============", acc)
  72. if __name__ == '__main__':
  73. mnist_train(10, 32, 0.001, 0.9)

MindArmour关注AI的安全和隐私问题。致力于增强模型的安全可信、保护用户的数据隐私。主要包含3个模块:对抗样本鲁棒性模块、Fuzz Testing模块、隐私保护与评估模块。 对抗样本鲁棒性模块 对抗样本鲁棒性模块用于评估模型对于对抗样本的鲁棒性,并提供模型增强方法用于增强模型抗对抗样本攻击的能力,提升模型鲁棒性。对抗样本鲁棒性模块包含了4个子模块:对抗样本的生成、对抗样本的检测、模型防御、攻防评估。