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.

test_bnn_layer.py 5.0 kB

5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145
  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. """test bnn layers"""
  16. import numpy as np
  17. from mindspore import Tensor
  18. from mindspore.common.initializer import TruncatedNormal
  19. import mindspore.nn as nn
  20. from mindspore.nn import TrainOneStepCell
  21. from mindspore.nn.probability import bnn_layers
  22. from mindspore.ops import operations as P
  23. from mindspore import context
  24. from dataset import create_dataset
  25. context.set_context(mode=context.GRAPH_MODE, save_graphs=False, device_target="GPU")
  26. def conv(in_channels, out_channels, kernel_size, stride=1, padding=0):
  27. """weight initial for conv layer"""
  28. weight = weight_variable()
  29. return nn.Conv2d(in_channels, out_channels,
  30. kernel_size=kernel_size, stride=stride, padding=padding,
  31. weight_init=weight, has_bias=False, pad_mode="valid")
  32. def fc_with_initialize(input_channels, out_channels):
  33. """weight initial for fc layer"""
  34. weight = weight_variable()
  35. bias = weight_variable()
  36. return nn.Dense(input_channels, out_channels, weight, bias)
  37. def weight_variable():
  38. """weight initial"""
  39. return TruncatedNormal(0.02)
  40. class BNNLeNet5(nn.Cell):
  41. """
  42. bayesian Lenet network
  43. Args:
  44. num_class (int): Num classes. Default: 10.
  45. Returns:
  46. Tensor, output tensor
  47. Examples:
  48. >>> BNNLeNet5(num_class=10)
  49. """
  50. def __init__(self, num_class=10):
  51. super(BNNLeNet5, self).__init__()
  52. self.num_class = num_class
  53. self.conv1 = bnn_layers.ConvReparam(1, 6, 5, stride=1, padding=0, has_bias=False, pad_mode="valid")
  54. self.conv2 = conv(6, 16, 5)
  55. self.fc1 = bnn_layers.DenseReparam(16 * 5 * 5, 120)
  56. self.fc2 = fc_with_initialize(120, 84)
  57. self.fc3 = fc_with_initialize(84, self.num_class)
  58. self.relu = nn.ReLU()
  59. self.max_pool2d = nn.MaxPool2d(kernel_size=2, stride=2)
  60. self.flatten = nn.Flatten()
  61. self.reshape = P.Reshape()
  62. def construct(self, x):
  63. x = self.conv1(x)
  64. x = self.relu(x)
  65. x = self.max_pool2d(x)
  66. x = self.conv2(x)
  67. x = self.relu(x)
  68. x = self.max_pool2d(x)
  69. x = self.flatten(x)
  70. x = self.fc1(x)
  71. x = self.relu(x)
  72. x = self.fc2(x)
  73. x = self.relu(x)
  74. x = self.fc3(x)
  75. return x
  76. def train_model(train_net, net, dataset):
  77. accs = []
  78. loss_sum = 0
  79. for _, data in enumerate(dataset.create_dict_iterator()):
  80. train_x = Tensor(data['image'].astype(np.float32))
  81. label = Tensor(data['label'].astype(np.int32))
  82. loss = train_net(train_x, label)
  83. output = net(train_x)
  84. log_output = P.LogSoftmax(axis=1)(output)
  85. acc = np.mean(log_output.asnumpy().argmax(axis=1) == label.asnumpy())
  86. accs.append(acc)
  87. loss_sum += loss.asnumpy()
  88. loss_sum = loss_sum / len(accs)
  89. acc_mean = np.mean(accs)
  90. return loss_sum, acc_mean
  91. def validate_model(net, dataset):
  92. accs = []
  93. for _, data in enumerate(dataset.create_dict_iterator()):
  94. train_x = Tensor(data['image'].astype(np.float32))
  95. label = Tensor(data['label'].astype(np.int32))
  96. output = net(train_x)
  97. log_output = P.LogSoftmax(axis=1)(output)
  98. acc = np.mean(log_output.asnumpy().argmax(axis=1) == label.asnumpy())
  99. accs.append(acc)
  100. acc_mean = np.mean(accs)
  101. return acc_mean
  102. if __name__ == "__main__":
  103. network = BNNLeNet5()
  104. criterion = nn.SoftmaxCrossEntropyWithLogits(is_grad=False, sparse=True, reduction="mean")
  105. optimizer = nn.AdamWeightDecay(params=network.trainable_params(), learning_rate=0.0001)
  106. net_with_loss = bnn_layers.WithBNNLossCell(network, criterion, 60000, 0.000001)
  107. train_bnn_network = TrainOneStepCell(net_with_loss, optimizer)
  108. train_bnn_network.set_train()
  109. train_set = create_dataset('/home/workspace/mindspore_dataset/mnist_data/train', 64, 1)
  110. test_set = create_dataset('/home/workspace/mindspore_dataset/mnist_data/test', 64, 1)
  111. epoch = 100
  112. for i in range(epoch):
  113. train_loss, train_acc = train_model(train_bnn_network, network, test_set)
  114. valid_acc = validate_model(network, test_set)
  115. print('Epoch: {} \tTraining Loss: {:.4f} \tTraining Accuracy: {:.4f} \tvalidation Accuracy: {:.4f}'.format(
  116. i, train_loss, train_acc, valid_acc))