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.2 kB

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