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_bias_add.py 3.0 kB

5 years ago
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. # Copyright 2019 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. import numpy as np
  15. import mindspore.nn as nn
  16. from mindspore import Tensor
  17. from mindspore import context
  18. from mindspore.ops import operations as P
  19. from mindspore.train.model import Model
  20. class CrossEntropyLoss(nn.Cell):
  21. def __init__(self, reduction='mean'):
  22. super(CrossEntropyLoss, self).__init__()
  23. self.reduce_mean = P.ReduceMean()
  24. self.cross_entropy = nn.SoftmaxCrossEntropyWithLogits()
  25. self.reduction = reduction
  26. def construct(self, logits, label):
  27. loss = self.cross_entropy(logits, label)
  28. if self.reduction == 'mean':
  29. loss = self.reduce_mean(loss, (-1,))
  30. return loss
  31. class DatasetLenet():
  32. def __init__(self, predict, label, length=3):
  33. self.predict = predict
  34. self.label = label
  35. self.index = 0
  36. self.length = length
  37. def __iter__(self):
  38. return self
  39. def __next__(self):
  40. if self.index >= self.length:
  41. raise StopIteration
  42. self.index += 1
  43. return self.predict, self.label
  44. def reset(self):
  45. self.index = 0
  46. def get_dataset_size(self):
  47. return 32
  48. def get_repeat_count(self):
  49. return 1
  50. def create_tuple_iterator(self):
  51. return self
  52. class Net(nn.Cell):
  53. def __init__(self):
  54. super().__init__()
  55. self.conv = nn.Conv2d(in_channels=3, out_channels=64, kernel_size=1, stride=1, pad_mode='valid',
  56. has_bias=True, weight_init='ones', bias_init='ones')
  57. self.reduce_mean = P.ReduceMean(keep_dims=False).set_strategy(((1, 1, 1, 8),))
  58. self.flat = nn.Flatten()
  59. def construct(self, inputs):
  60. x = self.conv(inputs)
  61. x = self.reduce_mean(x, -1)
  62. x = self.flat(x)
  63. return x
  64. def test_bias_add():
  65. context.set_context(mode=context.GRAPH_MODE)
  66. context.set_auto_parallel_context(parallel_mode="auto_parallel", device_num=8)
  67. input_np = np.ones([16, 3, 32, 32]).astype(np.float32)
  68. label_np = np.zeros([16, 2048]).astype(np.float32)
  69. dataset = DatasetLenet(Tensor(input_np), Tensor(label_np), 1)
  70. net = Net()
  71. loss = CrossEntropyLoss()
  72. opt = nn.Momentum(learning_rate=0.01, momentum=0.9, params=net.get_parameters())
  73. model = Model(network=net, loss_fn=loss, optimizer=opt)
  74. model.train(epoch=1, train_dataset=dataset, dataset_sink_mode=False)