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 6.3 kB

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