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_image_summary.py 5.4 kB

5 years ago
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185
  1. # Copyright 2020-2021 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_image_summary"""
  16. import logging
  17. import os
  18. import numpy as np
  19. import mindspore.nn as nn
  20. from mindspore import Model, context
  21. from mindspore import Tensor
  22. from mindspore.nn.optim import Momentum
  23. from mindspore.train.summary.summary_record import SummaryRecord, _cache_summary_tensor_data
  24. from mindspore.train.callback import Callback
  25. from .....dataset_mock import MindData
  26. CUR_DIR = os.getcwd()
  27. SUMMARY_DIR = CUR_DIR + "/test_temp_summary_event_file/"
  28. log = logging.getLogger("test")
  29. log.setLevel(level=logging.ERROR)
  30. def make_image_tensor(shape, dtype=float):
  31. """ make_image_tensor """
  32. number = np.prod(shape)
  33. x = (np.arange(number, dtype=dtype)).reshape(shape)
  34. return x
  35. def get_test_data(step):
  36. """ get_test_data """
  37. test_data_list = []
  38. tag1 = "x1[:Image]"
  39. tag2 = "x2[:Image]"
  40. np1 = make_image_tensor([2, 3, 8, 8])
  41. np2 = make_image_tensor([step, 3, 8, 8])
  42. dict1 = {}
  43. dict1["name"] = tag1
  44. dict1["data"] = Tensor(np1)
  45. dict2 = {}
  46. dict2["name"] = tag2
  47. dict2["data"] = Tensor(np2)
  48. test_data_list.append(dict1)
  49. test_data_list.append(dict2)
  50. return test_data_list
  51. # Test: call method on parse graph code
  52. def test_image_summary_sample():
  53. """ test_image_summary_sample """
  54. with SummaryRecord(SUMMARY_DIR, file_suffix="_MS_IMAGE") as test_writer:
  55. for i in range(1, 5):
  56. test_data = get_test_data(i)
  57. _cache_summary_tensor_data(test_data)
  58. test_writer.record(i)
  59. test_writer.flush()
  60. class Net(nn.Cell):
  61. """ Net definition """
  62. def __init__(self):
  63. super(Net, self).__init__()
  64. self.conv = nn.Conv2d(3, 64, 3, has_bias=False, weight_init='normal',
  65. pad_mode='valid')
  66. self.bn = nn.BatchNorm2d(64)
  67. self.relu = nn.ReLU()
  68. self.flatten = nn.Flatten()
  69. self.fc = nn.Dense(64 * 222 * 222, 3) # padding=0
  70. def construct(self, x):
  71. x = self.conv(x)
  72. x = self.bn(x)
  73. x = self.relu(x)
  74. x = self.flatten(x)
  75. out = self.fc(x)
  76. return out
  77. class LossNet(nn.Cell):
  78. """ LossNet definition """
  79. def __init__(self):
  80. super(LossNet, self).__init__()
  81. self.conv = nn.Conv2d(3, 64, 3, has_bias=False, weight_init='normal',
  82. pad_mode='valid')
  83. self.bn = nn.BatchNorm2d(64)
  84. self.relu = nn.ReLU()
  85. self.flatten = nn.Flatten()
  86. self.fc = nn.Dense(64 * 222 * 222, 3) # padding=0
  87. self.loss = nn.SoftmaxCrossEntropyWithLogits()
  88. def construct(self, x, y):
  89. x = self.conv(x)
  90. x = self.bn(x)
  91. x = self.relu(x)
  92. x = self.flatten(x)
  93. x = self.fc(x)
  94. out = self.loss(x, y)
  95. return out
  96. def get_model():
  97. """ get_model """
  98. net = Net()
  99. loss = nn.SoftmaxCrossEntropyWithLogits()
  100. optim = Momentum(net.trainable_params(), learning_rate=0.1, momentum=0.9)
  101. context.set_context(mode=context.GRAPH_MODE)
  102. model = Model(net, loss_fn=loss, optimizer=optim, metrics=None)
  103. return model
  104. def get_dataset():
  105. """ get_dataset """
  106. dataset_types = (np.float32, np.float32)
  107. dataset_shapes = ((2, 3, 224, 224), (2, 3))
  108. dataset = MindData(size=2, batch_size=2,
  109. np_types=dataset_types,
  110. output_shapes=dataset_shapes,
  111. input_indexs=(0, 1))
  112. return dataset
  113. class ImageSummaryCallback(Callback):
  114. """Image summary callback."""
  115. def __init__(self, summary_record):
  116. self._summary_record = summary_record
  117. def __enter__(self):
  118. return self
  119. def __exit__(self, *err):
  120. self._summary_record.close()
  121. def record(self, step, train_network=None):
  122. """record data."""
  123. self._summary_record.record(step, train_network)
  124. self._summary_record.flush()
  125. def test_image_summary_train():
  126. """ test_image_summary_train """
  127. dataset = get_dataset()
  128. with SummaryRecord(SUMMARY_DIR, file_suffix="_MS_IMAGE") as test_writer:
  129. model = get_model()
  130. callback = ImageSummaryCallback(test_writer)
  131. model.train(2, dataset, callbacks=[callback])
  132. def test_image_summary_data():
  133. """ test_image_summary_data """
  134. dataset = get_dataset()
  135. test_data_list = []
  136. i = 1
  137. for next_element in dataset:
  138. tag = "image_" + str(i) + "[:Image]"
  139. dct = {}
  140. dct["name"] = tag
  141. dct["data"] = Tensor(next_element[0])
  142. test_data_list.append(dct)
  143. i += 1
  144. with SummaryRecord(SUMMARY_DIR, file_suffix="_MS_IMAGE") as test_writer:
  145. _cache_summary_tensor_data(test_data_list)
  146. test_writer.record(1)