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_minddataset_padded.py 20 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444
  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. This is the test module for mindrecord
  17. """
  18. import collections
  19. import json
  20. import numpy as np
  21. import os
  22. import pytest
  23. import re
  24. import string
  25. import mindspore.dataset as ds
  26. import mindspore.dataset.transforms.vision.c_transforms as vision
  27. from mindspore import log as logger
  28. from mindspore.dataset.transforms.vision import Inter
  29. from mindspore.mindrecord import FileWriter
  30. FILES_NUM = 4
  31. CV_FILE_NAME = "../data/mindrecord/imagenet.mindrecord"
  32. CV1_FILE_NAME = "../data/mindrecord/imagenet1.mindrecord"
  33. CV2_FILE_NAME = "../data/mindrecord/imagenet2.mindrecord"
  34. CV_DIR_NAME = "../data/mindrecord/testImageNetData"
  35. NLP_FILE_NAME = "../data/mindrecord/aclImdb.mindrecord"
  36. NLP_FILE_POS = "../data/mindrecord/testAclImdbData/pos"
  37. NLP_FILE_VOCAB = "../data/mindrecord/testAclImdbData/vocab.txt"
  38. @pytest.fixture
  39. def add_and_remove_cv_file():
  40. """add/remove cv file"""
  41. paths = ["{}{}".format(CV_FILE_NAME, str(x).rjust(1, '0'))
  42. for x in range(FILES_NUM)]
  43. for x in paths:
  44. os.remove("{}".format(x)) if os.path.exists("{}".format(x)) else None
  45. os.remove("{}.db".format(x)) if os.path.exists(
  46. "{}.db".format(x)) else None
  47. writer = FileWriter(CV_FILE_NAME, FILES_NUM)
  48. data = get_data(CV_DIR_NAME)
  49. cv_schema_json = {"id": {"type": "int32"},
  50. "file_name": {"type": "string"},
  51. "label": {"type": "int32"},
  52. "data": {"type": "bytes"}}
  53. writer.add_schema(cv_schema_json, "img_schema")
  54. writer.add_index(["file_name", "label"])
  55. writer.write_raw_data(data)
  56. writer.commit()
  57. yield "yield_cv_data"
  58. for x in paths:
  59. os.remove("{}".format(x))
  60. os.remove("{}.db".format(x))
  61. @pytest.fixture
  62. def add_and_remove_nlp_file():
  63. """add/remove nlp file"""
  64. paths = ["{}{}".format(NLP_FILE_NAME, str(x).rjust(1, '0'))
  65. for x in range(FILES_NUM)]
  66. for x in paths:
  67. if os.path.exists("{}".format(x)):
  68. os.remove("{}".format(x))
  69. if os.path.exists("{}.db".format(x)):
  70. os.remove("{}.db".format(x))
  71. writer = FileWriter(NLP_FILE_NAME, FILES_NUM)
  72. data = [x for x in get_nlp_data(NLP_FILE_POS, NLP_FILE_VOCAB, 10)]
  73. nlp_schema_json = {"id": {"type": "string"}, "label": {"type": "int32"},
  74. "rating": {"type": "float32"},
  75. "input_ids": {"type": "int64",
  76. "shape": [-1]},
  77. "input_mask": {"type": "int64",
  78. "shape": [1, -1]},
  79. "segment_ids": {"type": "int64",
  80. "shape": [2, -1]}
  81. }
  82. writer.set_header_size(1 << 14)
  83. writer.set_page_size(1 << 15)
  84. writer.add_schema(nlp_schema_json, "nlp_schema")
  85. writer.add_index(["id", "rating"])
  86. writer.write_raw_data(data)
  87. writer.commit()
  88. yield "yield_nlp_data"
  89. for x in paths:
  90. os.remove("{}".format(x))
  91. os.remove("{}.db".format(x))
  92. def test_cv_minddataset_reader_basic_padded_samples(add_and_remove_cv_file):
  93. """tutorial for cv minderdataset."""
  94. columns_list = ["label", "file_name", "data"]
  95. data = get_data(CV_DIR_NAME)
  96. padded_sample = data[0]
  97. padded_sample['label'] = -1
  98. padded_sample['file_name'] = 'dummy.jpg'
  99. num_readers = 4
  100. data_set = ds.MindDataset(CV_FILE_NAME + "0", columns_list, num_readers, padded_sample=padded_sample, num_padded=5)
  101. assert data_set.get_dataset_size() == 15
  102. num_iter = 0
  103. num_padded_iter = 0
  104. for item in data_set.create_dict_iterator():
  105. logger.info("-------------- cv reader basic: {} ------------------------".format(num_iter))
  106. logger.info("-------------- item[file_name]: {} ------------------------".format(item["file_name"]))
  107. logger.info("-------------- item[label]: {} ----------------------------".format(item["label"]))
  108. if item['label'] == -1:
  109. num_padded_iter += 1
  110. assert item['file_name'] == bytes(padded_sample['file_name'],
  111. encoding='utf8')
  112. assert item['label'] == padded_sample['label']
  113. assert (item['data'] == np.array(list(padded_sample['data']))).all()
  114. num_iter += 1
  115. assert num_padded_iter ==5
  116. assert num_iter == 15
  117. def test_cv_minddataset_partition_padded_samples(add_and_remove_cv_file):
  118. """tutorial for cv minddataset."""
  119. columns_list = ["data", "file_name", "label"]
  120. data = get_data(CV_DIR_NAME)
  121. padded_sample = data[0]
  122. padded_sample['label'] = -2
  123. padded_sample['file_name'] = 'dummy.jpg'
  124. num_readers = 4
  125. def partitions(num_shards, num_padded, dataset_size):
  126. for partition_id in range(num_shards):
  127. data_set = ds.MindDataset(CV_FILE_NAME + "0", columns_list, num_readers,
  128. num_shards=num_shards,
  129. shard_id=partition_id,
  130. padded_sample=padded_sample,
  131. num_padded=num_padded)
  132. assert data_set.get_dataset_size() == dataset_size
  133. num_iter = 0
  134. num_padded_iter = 0
  135. for item in data_set.create_dict_iterator():
  136. logger.info("-------------- partition : {} ------------------------".format(partition_id))
  137. logger.info("-------------- len(item[data]): {} ------------------------".format(len(item["data"])))
  138. logger.info("-------------- item[data]: {} -----------------------------".format(item["data"]))
  139. logger.info("-------------- item[file_name]: {} ------------------------".format(item["file_name"]))
  140. logger.info("-------------- item[label]: {} -----------------------".format(item["label"]))
  141. if item['label'] == -2:
  142. num_padded_iter += 1
  143. assert item['file_name'] == bytes(padded_sample['file_name'], encoding='utf8')
  144. assert item['label'] == padded_sample['label']
  145. assert (item['data'] == np.array(list(padded_sample['data']))).all()
  146. num_iter += 1
  147. return num_iter
  148. assert partitions(4, 2, 3) == 3
  149. assert partitions(5, 5, 3) == 3
  150. assert partitions(9, 8, 2) == 2
  151. def test_cv_minddataset_partition_padded_samples_no_dividsible(add_and_remove_cv_file):
  152. """tutorial for cv minddataset."""
  153. columns_list = ["data", "file_name", "label"]
  154. data = get_data(CV_DIR_NAME)
  155. padded_sample = data[0]
  156. padded_sample['label'] = -2
  157. padded_sample['file_name'] = 'dummy.jpg'
  158. num_readers = 4
  159. def partitions(num_shards, num_padded):
  160. for partition_id in range(num_shards):
  161. data_set = ds.MindDataset(CV_FILE_NAME + "0", columns_list, num_readers,
  162. num_shards=num_shards,
  163. shard_id=partition_id,
  164. padded_sample=padded_sample,
  165. num_padded=num_padded)
  166. num_iter = 0
  167. for item in data_set.create_dict_iterator():
  168. num_iter += 1
  169. return num_iter
  170. with pytest.raises(RuntimeError):
  171. partitions(4, 1)
  172. def test_cv_minddataset_partition_padded_samples_dataset_size_no_divisible(add_and_remove_cv_file):
  173. columns_list = ["data", "file_name", "label"]
  174. data = get_data(CV_DIR_NAME)
  175. padded_sample = data[0]
  176. padded_sample['label'] = -2
  177. padded_sample['file_name'] = 'dummy.jpg'
  178. num_readers = 4
  179. def partitions(num_shards, num_padded):
  180. for partition_id in range(num_shards):
  181. data_set = ds.MindDataset(CV_FILE_NAME + "0", columns_list, num_readers,
  182. num_shards=num_shards,
  183. shard_id=partition_id,
  184. padded_sample=padded_sample,
  185. num_padded=num_padded)
  186. with pytest.raises(RuntimeError):
  187. data_set.get_dataset_size() == 3
  188. partitions(4, 1)
  189. def test_cv_minddataset_partition_padded_samples_no_equal_column_list(add_and_remove_cv_file):
  190. columns_list = ["data", "file_name", "label"]
  191. data = get_data(CV_DIR_NAME)
  192. padded_sample = data[0]
  193. padded_sample.pop('label', None)
  194. padded_sample['file_name'] = 'dummy.jpg'
  195. num_readers = 4
  196. def partitions(num_shards, num_padded):
  197. for partition_id in range(num_shards):
  198. data_set = ds.MindDataset(CV_FILE_NAME + "0", columns_list, num_readers,
  199. num_shards=num_shards,
  200. shard_id=partition_id,
  201. padded_sample=padded_sample,
  202. num_padded=num_padded)
  203. for item in data_set.create_dict_iterator():
  204. logger.info("-------------- partition : {} ------------------------".format(partition_id))
  205. logger.info("-------------- len(item[data]): {} ------------------------".format(len(item["data"])))
  206. logger.info("-------------- item[data]: {} -----------------------------".format(item["data"]))
  207. logger.info("-------------- item[file_name]: {} ------------------------".format(item["file_name"]))
  208. with pytest.raises(Exception, match="padded_sample cannot match columns_list."):
  209. partitions(4, 2)
  210. def test_cv_minddataset_partition_padded_samples_no_column_list(add_and_remove_cv_file):
  211. data = get_data(CV_DIR_NAME)
  212. padded_sample = data[0]
  213. padded_sample['label'] = -2
  214. padded_sample['file_name'] = 'dummy.jpg'
  215. num_readers = 4
  216. def partitions(num_shards, num_padded):
  217. for partition_id in range(num_shards):
  218. data_set = ds.MindDataset(CV_FILE_NAME + "0", None, num_readers,
  219. num_shards=num_shards,
  220. shard_id=partition_id,
  221. padded_sample=padded_sample,
  222. num_padded=num_padded)
  223. for item in data_set.create_dict_iterator():
  224. logger.info("-------------- partition : {} ------------------------".format(partition_id))
  225. logger.info("-------------- len(item[data]): {} ------------------------".format(len(item["data"])))
  226. logger.info("-------------- item[data]: {} -----------------------------".format(item["data"]))
  227. logger.info("-------------- item[file_name]: {} ------------------------".format(item["file_name"]))
  228. with pytest.raises(Exception, match="padded_sample is specified and requires columns_list as well."):
  229. partitions(4, 2)
  230. def test_cv_minddataset_partition_padded_samples_no_num_padded(add_and_remove_cv_file):
  231. columns_list = ["data", "file_name", "label"]
  232. data = get_data(CV_DIR_NAME)
  233. padded_sample = data[0]
  234. padded_sample['file_name'] = 'dummy.jpg'
  235. num_readers = 4
  236. def partitions(num_shards, num_padded):
  237. for partition_id in range(num_shards):
  238. data_set = ds.MindDataset(CV_FILE_NAME + "0", None, num_readers,
  239. num_shards=num_shards,
  240. shard_id=partition_id,
  241. padded_sample=padded_sample)
  242. for item in data_set.create_dict_iterator():
  243. logger.info("-------------- partition : {} ------------------------".format(partition_id))
  244. logger.info("-------------- len(item[data]): {} ------------------------".format(len(item["data"])))
  245. logger.info("-------------- item[data]: {} -----------------------------".format(item["data"]))
  246. logger.info("-------------- item[file_name]: {} ------------------------".format(item["file_name"]))
  247. with pytest.raises(Exception, match="padded_sample is specified and requires num_padded as well."):
  248. partitions(4, 2)
  249. def test_cv_minddataset_partition_padded_samples_no_padded_samples(add_and_remove_cv_file):
  250. columns_list = ["data", "file_name", "label"]
  251. data = get_data(CV_DIR_NAME)
  252. padded_sample = data[0]
  253. padded_sample['file_name'] = 'dummy.jpg'
  254. num_readers = 4
  255. def partitions(num_shards, num_padded):
  256. for partition_id in range(num_shards):
  257. data_set = ds.MindDataset(CV_FILE_NAME + "0", None, num_readers,
  258. num_shards=num_shards,
  259. shard_id=partition_id,
  260. num_padded=num_padded)
  261. for item in data_set.create_dict_iterator():
  262. logger.info("-------------- partition : {} ------------------------".format(partition_id))
  263. logger.info("-------------- len(item[data]): {} ------------------------".format(len(item["data"])))
  264. logger.info("-------------- item[data]: {} -----------------------------".format(item["data"]))
  265. logger.info("-------------- item[file_name]: {} ------------------------".format(item["file_name"]))
  266. with pytest.raises(Exception, match="num_padded is specified but padded_sample is not."):
  267. partitions(4, 2)
  268. def test_nlp_minddataset_reader_basic_padded_samples(add_and_remove_nlp_file):
  269. columns_list = ["input_ids", "id", "rating"]
  270. data = [x for x in get_nlp_data(NLP_FILE_POS, NLP_FILE_VOCAB, 10)]
  271. padded_sample = data[0]
  272. padded_sample['id'] = "-1"
  273. padded_sample['input_ids'] = np.array([-1,-1,-1,-1], dtype=np.int64)
  274. padded_sample['rating'] = 1.0
  275. num_readers = 4
  276. def partitions(num_shards, num_padded, dataset_size):
  277. for partition_id in range(num_shards):
  278. data_set = ds.MindDataset(NLP_FILE_NAME + "0", columns_list, num_readers,
  279. num_shards=num_shards,
  280. shard_id=partition_id,
  281. padded_sample=padded_sample,
  282. num_padded=num_padded)
  283. assert data_set.get_dataset_size() == dataset_size
  284. num_iter = 0
  285. for item in data_set.create_dict_iterator():
  286. logger.info("-------------- item[id]: {} ------------------------".format(item["id"]))
  287. logger.info("-------------- item[rating]: {} --------------------".format(item["rating"]))
  288. logger.info("-------------- item[input_ids]: {}, shape: {} -----------------".format(item["input_ids"], item["input_ids"].shape))
  289. if item['id'] == '-1':
  290. num_padded_iter += 1
  291. assert item['id'] == padded_sample['id']
  292. assert item['input_ids'] == padded_sample['input_ids']
  293. assert item['rating'] == padded_sample['rating']
  294. num_iter += 1
  295. return num_iter
  296. assert partitions(4, 6, 4) == 4
  297. assert partitions(5, 5, 3) == 3
  298. assert partitions(9, 8, 2) == 2
  299. def get_data(dir_name):
  300. """
  301. usage: get data from imagenet dataset
  302. params:
  303. dir_name: directory containing folder images and annotation information
  304. """
  305. if not os.path.isdir(dir_name):
  306. raise IOError("Directory {} not exists".format(dir_name))
  307. img_dir = os.path.join(dir_name, "images")
  308. ann_file = os.path.join(dir_name, "annotation.txt")
  309. with open(ann_file, "r") as file_reader:
  310. lines = file_reader.readlines()
  311. data_list = []
  312. for i, line in enumerate(lines):
  313. try:
  314. filename, label = line.split(",")
  315. label = label.strip("\n")
  316. with open(os.path.join(img_dir, filename), "rb") as file_reader:
  317. img = file_reader.read()
  318. data_json = {"id": i,
  319. "file_name": filename,
  320. "data": img,
  321. "label": int(label)}
  322. data_list.append(data_json)
  323. except FileNotFoundError:
  324. continue
  325. return data_list
  326. def get_nlp_data(dir_name, vocab_file, num):
  327. """
  328. Return raw data of aclImdb dataset.
  329. Args:
  330. dir_name (str): String of aclImdb dataset's path.
  331. vocab_file (str): String of dictionary's path.
  332. num (int): Number of sample.
  333. Returns:
  334. List
  335. """
  336. if not os.path.isdir(dir_name):
  337. raise IOError("Directory {} not exists".format(dir_name))
  338. for root, dirs, files in os.walk(dir_name):
  339. for index, file_name_extension in enumerate(files):
  340. if index < num:
  341. file_path = os.path.join(root, file_name_extension)
  342. file_name, _ = file_name_extension.split('.', 1)
  343. id_, rating = file_name.split('_', 1)
  344. with open(file_path, 'r') as f:
  345. raw_content = f.read()
  346. dictionary = load_vocab(vocab_file)
  347. vectors = [dictionary.get('[CLS]')]
  348. vectors += [dictionary.get(i) if i in dictionary
  349. else dictionary.get('[UNK]')
  350. for i in re.findall(r"[\w']+|[{}]"
  351. .format(string.punctuation),
  352. raw_content)]
  353. vectors += [dictionary.get('[SEP]')]
  354. input_, mask, segment = inputs(vectors)
  355. input_ids = np.reshape(np.array(input_), [-1])
  356. input_mask = np.reshape(np.array(mask), [1, -1])
  357. segment_ids = np.reshape(np.array(segment), [2, -1])
  358. data = {
  359. "label": 1,
  360. "id": id_,
  361. "rating": float(rating),
  362. "input_ids": input_ids,
  363. "input_mask": input_mask,
  364. "segment_ids": segment_ids
  365. }
  366. yield data
  367. def convert_to_uni(text):
  368. if isinstance(text, str):
  369. return text
  370. if isinstance(text, bytes):
  371. return text.decode('utf-8', 'ignore')
  372. raise Exception("The type %s does not convert!" % type(text))
  373. def load_vocab(vocab_file):
  374. """load vocabulary to translate statement."""
  375. vocab = collections.OrderedDict()
  376. vocab.setdefault('blank', 2)
  377. index = 0
  378. with open(vocab_file) as reader:
  379. while True:
  380. tmp = reader.readline()
  381. if not tmp:
  382. break
  383. token = convert_to_uni(tmp)
  384. token = token.strip()
  385. vocab[token] = index
  386. index += 1
  387. return vocab
  388. def inputs(vectors, maxlen=50):
  389. length = len(vectors)
  390. if length > maxlen:
  391. return vectors[0:maxlen], [1] * maxlen, [0] * maxlen
  392. input_ = vectors + [0] * (maxlen - length)
  393. mask = [1] * length + [0] * (maxlen - length)
  394. segment = [0] * maxlen
  395. return input_, mask, segment