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

5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683
  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 os
  20. import re
  21. import string
  22. import numpy as np
  23. import pytest
  24. import mindspore.dataset as ds
  25. from mindspore import log as logger
  26. from mindspore.mindrecord import FileWriter
  27. FILES_NUM = 4
  28. CV_FILE_NAME = "../data/mindrecord/imagenet.mindrecord"
  29. CV1_FILE_NAME = "../data/mindrecord/imagenet1.mindrecord"
  30. CV2_FILE_NAME = "../data/mindrecord/imagenet2.mindrecord"
  31. CV_DIR_NAME = "../data/mindrecord/testImageNetData"
  32. NLP_FILE_NAME = "../data/mindrecord/aclImdb.mindrecord"
  33. NLP_FILE_POS = "../data/mindrecord/testAclImdbData/pos"
  34. NLP_FILE_VOCAB = "../data/mindrecord/testAclImdbData/vocab.txt"
  35. @pytest.fixture
  36. def add_and_remove_cv_file():
  37. """add/remove cv file"""
  38. paths = ["{}{}".format(CV_FILE_NAME, str(x).rjust(1, '0'))
  39. for x in range(FILES_NUM)]
  40. try:
  41. for x in paths:
  42. os.remove("{}".format(x)) if os.path.exists("{}".format(x)) else None
  43. os.remove("{}.db".format(x)) if os.path.exists(
  44. "{}.db".format(x)) else None
  45. writer = FileWriter(CV_FILE_NAME, FILES_NUM)
  46. data = get_data(CV_DIR_NAME)
  47. cv_schema_json = {"id": {"type": "int32"},
  48. "file_name": {"type": "string"},
  49. "label": {"type": "int32"},
  50. "data": {"type": "bytes"}}
  51. writer.add_schema(cv_schema_json, "img_schema")
  52. writer.add_index(["file_name", "label"])
  53. writer.write_raw_data(data)
  54. writer.commit()
  55. yield "yield_cv_data"
  56. except Exception as error:
  57. for x in paths:
  58. os.remove("{}".format(x))
  59. os.remove("{}.db".format(x))
  60. raise error
  61. else:
  62. for x in paths:
  63. os.remove("{}".format(x))
  64. os.remove("{}.db".format(x))
  65. @pytest.fixture
  66. def add_and_remove_nlp_file():
  67. """add/remove nlp file"""
  68. paths = ["{}{}".format(NLP_FILE_NAME, str(x).rjust(1, '0'))
  69. for x in range(FILES_NUM)]
  70. try:
  71. for x in paths:
  72. if os.path.exists("{}".format(x)):
  73. os.remove("{}".format(x))
  74. if os.path.exists("{}.db".format(x)):
  75. os.remove("{}.db".format(x))
  76. writer = FileWriter(NLP_FILE_NAME, FILES_NUM)
  77. data = [x for x in get_nlp_data(NLP_FILE_POS, NLP_FILE_VOCAB, 10)]
  78. nlp_schema_json = {"id": {"type": "string"}, "label": {"type": "int32"},
  79. "rating": {"type": "float32"},
  80. "input_ids": {"type": "int64",
  81. "shape": [-1]},
  82. "input_mask": {"type": "int64",
  83. "shape": [1, -1]},
  84. "segment_ids": {"type": "int64",
  85. "shape": [2, -1]}
  86. }
  87. writer.set_header_size(1 << 14)
  88. writer.set_page_size(1 << 15)
  89. writer.add_schema(nlp_schema_json, "nlp_schema")
  90. writer.add_index(["id", "rating"])
  91. writer.write_raw_data(data)
  92. writer.commit()
  93. yield "yield_nlp_data"
  94. except Exception as error:
  95. for x in paths:
  96. os.remove("{}".format(x))
  97. os.remove("{}.db".format(x))
  98. raise error
  99. else:
  100. for x in paths:
  101. os.remove("{}".format(x))
  102. os.remove("{}.db".format(x))
  103. def test_cv_minddataset_reader_basic_padded_samples(add_and_remove_cv_file):
  104. """tutorial for cv minderdataset."""
  105. columns_list = ["label", "file_name", "data"]
  106. data = get_data(CV_DIR_NAME)
  107. padded_sample = data[0]
  108. padded_sample['label'] = -1
  109. padded_sample['file_name'] = 'dummy.jpg'
  110. num_readers = 4
  111. data_set = ds.MindDataset(CV_FILE_NAME + "0", columns_list, num_readers, padded_sample=padded_sample, num_padded=5)
  112. assert data_set.get_dataset_size() == 15
  113. num_iter = 0
  114. num_padded_iter = 0
  115. for item in data_set.create_dict_iterator(num_epochs=1, output_numpy=True):
  116. logger.info("-------------- cv reader basic: {} ------------------------".format(num_iter))
  117. logger.info("-------------- item[file_name]: {} ------------------------".format(item["file_name"]))
  118. logger.info("-------------- item[label]: {} ----------------------------".format(item["label"]))
  119. if item['label'] == -1:
  120. num_padded_iter += 1
  121. assert item['file_name'] == bytes(padded_sample['file_name'],
  122. encoding='utf8')
  123. assert item['label'] == padded_sample['label']
  124. assert (item['data'] == np.array(list(padded_sample['data']))).all()
  125. num_iter += 1
  126. assert num_padded_iter == 5
  127. assert num_iter == 15
  128. def test_cv_minddataset_partition_padded_samples(add_and_remove_cv_file):
  129. """tutorial for cv minddataset."""
  130. columns_list = ["data", "file_name", "label"]
  131. data = get_data(CV_DIR_NAME)
  132. padded_sample = data[0]
  133. padded_sample['label'] = -2
  134. padded_sample['file_name'] = 'dummy.jpg'
  135. num_readers = 4
  136. def partitions(num_shards, num_padded, dataset_size):
  137. num_padded_iter = 0
  138. num_iter = 0
  139. for partition_id in range(num_shards):
  140. data_set = ds.MindDataset(CV_FILE_NAME + "0", columns_list, num_readers,
  141. num_shards=num_shards,
  142. shard_id=partition_id,
  143. padded_sample=padded_sample,
  144. num_padded=num_padded)
  145. assert data_set.get_dataset_size() == dataset_size
  146. for item in data_set.create_dict_iterator(num_epochs=1, output_numpy=True):
  147. logger.info("-------------- partition : {} ------------------------".format(partition_id))
  148. logger.info("-------------- len(item[data]): {} ------------------------".format(len(item["data"])))
  149. logger.info("-------------- item[data]: {} -----------------------------".format(item["data"]))
  150. logger.info("-------------- item[file_name]: {} ------------------------".format(item["file_name"]))
  151. logger.info("-------------- item[label]: {} -----------------------".format(item["label"]))
  152. if item['label'] == -2:
  153. num_padded_iter += 1
  154. assert item['file_name'] == bytes(padded_sample['file_name'], encoding='utf8')
  155. assert item['label'] == padded_sample['label']
  156. assert (item['data'] == np.array(list(padded_sample['data']))).all()
  157. num_iter += 1
  158. assert num_padded_iter == num_padded
  159. return num_iter == dataset_size * num_shards
  160. partitions(4, 2, 3)
  161. partitions(5, 5, 3)
  162. partitions(9, 8, 2)
  163. def test_cv_minddataset_partition_padded_samples_multi_epoch(add_and_remove_cv_file):
  164. """tutorial for cv minddataset."""
  165. columns_list = ["data", "file_name", "label"]
  166. data = get_data(CV_DIR_NAME)
  167. padded_sample = data[0]
  168. padded_sample['label'] = -2
  169. padded_sample['file_name'] = 'dummy.jpg'
  170. num_readers = 4
  171. def partitions(num_shards, num_padded, dataset_size):
  172. repeat_size = 5
  173. num_padded_iter = 0
  174. num_iter = 0
  175. for partition_id in range(num_shards):
  176. epoch1_shuffle_result = []
  177. epoch2_shuffle_result = []
  178. epoch3_shuffle_result = []
  179. epoch4_shuffle_result = []
  180. epoch5_shuffle_result = []
  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. assert data_set.get_dataset_size() == dataset_size
  187. data_set = data_set.repeat(repeat_size)
  188. local_index = 0
  189. for item in data_set.create_dict_iterator(num_epochs=1, output_numpy=True):
  190. logger.info("-------------- partition : {} ------------------------".format(partition_id))
  191. logger.info("-------------- len(item[data]): {} ------------------------".format(len(item["data"])))
  192. logger.info("-------------- item[data]: {} -----------------------------".format(item["data"]))
  193. logger.info("-------------- item[file_name]: {} ------------------------".format(item["file_name"]))
  194. logger.info("-------------- item[label]: {} -----------------------".format(item["label"]))
  195. if item['label'] == -2:
  196. num_padded_iter += 1
  197. assert item['file_name'] == bytes(padded_sample['file_name'], encoding='utf8')
  198. assert item['label'] == padded_sample['label']
  199. assert (item['data'] == np.array(list(padded_sample['data']))).all()
  200. if local_index < dataset_size:
  201. epoch1_shuffle_result.append(item["file_name"])
  202. elif local_index < dataset_size * 2:
  203. epoch2_shuffle_result.append(item["file_name"])
  204. elif local_index < dataset_size * 3:
  205. epoch3_shuffle_result.append(item["file_name"])
  206. elif local_index < dataset_size * 4:
  207. epoch4_shuffle_result.append(item["file_name"])
  208. elif local_index < dataset_size * 5:
  209. epoch5_shuffle_result.append(item["file_name"])
  210. local_index += 1
  211. num_iter += 1
  212. assert len(epoch1_shuffle_result) == dataset_size
  213. assert len(epoch2_shuffle_result) == dataset_size
  214. assert len(epoch3_shuffle_result) == dataset_size
  215. assert len(epoch4_shuffle_result) == dataset_size
  216. assert len(epoch5_shuffle_result) == dataset_size
  217. assert local_index == dataset_size * repeat_size
  218. # When dataset_size is equal to 2, too high probability is the same result after shuffle operation
  219. if dataset_size > 2:
  220. assert epoch1_shuffle_result != epoch2_shuffle_result
  221. assert epoch2_shuffle_result != epoch3_shuffle_result
  222. assert epoch3_shuffle_result != epoch4_shuffle_result
  223. assert epoch4_shuffle_result != epoch5_shuffle_result
  224. assert num_padded_iter == num_padded * repeat_size
  225. assert num_iter == dataset_size * num_shards * repeat_size
  226. partitions(4, 2, 3)
  227. partitions(5, 5, 3)
  228. partitions(9, 8, 2)
  229. def test_cv_minddataset_partition_padded_samples_no_dividsible(add_and_remove_cv_file):
  230. """tutorial for cv minddataset."""
  231. columns_list = ["data", "file_name", "label"]
  232. data = get_data(CV_DIR_NAME)
  233. padded_sample = data[0]
  234. padded_sample['label'] = -2
  235. padded_sample['file_name'] = 'dummy.jpg'
  236. num_readers = 4
  237. def partitions(num_shards, num_padded):
  238. for partition_id in range(num_shards):
  239. data_set = ds.MindDataset(CV_FILE_NAME + "0", columns_list, num_readers,
  240. num_shards=num_shards,
  241. shard_id=partition_id,
  242. padded_sample=padded_sample,
  243. num_padded=num_padded)
  244. num_iter = 0
  245. for item in data_set.create_dict_iterator(num_epochs=1, output_numpy=True):
  246. num_iter += 1
  247. return num_iter
  248. with pytest.raises(RuntimeError):
  249. partitions(4, 1)
  250. def test_cv_minddataset_partition_padded_samples_dataset_size_no_divisible(add_and_remove_cv_file):
  251. columns_list = ["data", "file_name", "label"]
  252. data = get_data(CV_DIR_NAME)
  253. padded_sample = data[0]
  254. padded_sample['label'] = -2
  255. padded_sample['file_name'] = 'dummy.jpg'
  256. num_readers = 4
  257. def partitions(num_shards, num_padded):
  258. for partition_id in range(num_shards):
  259. data_set = ds.MindDataset(CV_FILE_NAME + "0", columns_list, num_readers,
  260. num_shards=num_shards,
  261. shard_id=partition_id,
  262. padded_sample=padded_sample,
  263. num_padded=num_padded)
  264. with pytest.raises(RuntimeError):
  265. data_set.get_dataset_size() == 3
  266. partitions(4, 1)
  267. def test_cv_minddataset_partition_padded_samples_no_equal_column_list(add_and_remove_cv_file):
  268. columns_list = ["data", "file_name", "label"]
  269. data = get_data(CV_DIR_NAME)
  270. padded_sample = data[0]
  271. padded_sample.pop('label', None)
  272. padded_sample['file_name'] = 'dummy.jpg'
  273. num_readers = 4
  274. def partitions(num_shards, num_padded):
  275. for partition_id in range(num_shards):
  276. data_set = ds.MindDataset(CV_FILE_NAME + "0", columns_list, num_readers,
  277. num_shards=num_shards,
  278. shard_id=partition_id,
  279. padded_sample=padded_sample,
  280. num_padded=num_padded)
  281. for item in data_set.create_dict_iterator(num_epochs=1, output_numpy=True):
  282. logger.info("-------------- partition : {} ------------------------".format(partition_id))
  283. logger.info("-------------- len(item[data]): {} ------------------------".format(len(item["data"])))
  284. logger.info("-------------- item[data]: {} -----------------------------".format(item["data"]))
  285. logger.info("-------------- item[file_name]: {} ------------------------".format(item["file_name"]))
  286. with pytest.raises(Exception, match="padded_sample cannot match columns_list."):
  287. partitions(4, 2)
  288. def test_cv_minddataset_partition_padded_samples_no_column_list(add_and_remove_cv_file):
  289. data = get_data(CV_DIR_NAME)
  290. padded_sample = data[0]
  291. padded_sample['label'] = -2
  292. padded_sample['file_name'] = 'dummy.jpg'
  293. num_readers = 4
  294. def partitions(num_shards, num_padded):
  295. for partition_id in range(num_shards):
  296. data_set = ds.MindDataset(CV_FILE_NAME + "0", None, num_readers,
  297. num_shards=num_shards,
  298. shard_id=partition_id,
  299. padded_sample=padded_sample,
  300. num_padded=num_padded)
  301. for item in data_set.create_dict_iterator(num_epochs=1, output_numpy=True):
  302. logger.info("-------------- partition : {} ------------------------".format(partition_id))
  303. logger.info("-------------- len(item[data]): {} ------------------------".format(len(item["data"])))
  304. logger.info("-------------- item[data]: {} -----------------------------".format(item["data"]))
  305. logger.info("-------------- item[file_name]: {} ------------------------".format(item["file_name"]))
  306. with pytest.raises(Exception, match="padded_sample is specified and requires columns_list as well."):
  307. partitions(4, 2)
  308. def test_cv_minddataset_partition_padded_samples_no_num_padded(add_and_remove_cv_file):
  309. columns_list = ["data", "file_name", "label"]
  310. data = get_data(CV_DIR_NAME)
  311. padded_sample = data[0]
  312. padded_sample['file_name'] = 'dummy.jpg'
  313. num_readers = 4
  314. def partitions(num_shards, num_padded):
  315. for partition_id in range(num_shards):
  316. data_set = ds.MindDataset(CV_FILE_NAME + "0", None, num_readers,
  317. num_shards=num_shards,
  318. shard_id=partition_id,
  319. padded_sample=padded_sample)
  320. for item in data_set.create_dict_iterator(num_epochs=1, output_numpy=True):
  321. logger.info("-------------- partition : {} ------------------------".format(partition_id))
  322. logger.info("-------------- len(item[data]): {} ------------------------".format(len(item["data"])))
  323. logger.info("-------------- item[data]: {} -----------------------------".format(item["data"]))
  324. logger.info("-------------- item[file_name]: {} ------------------------".format(item["file_name"]))
  325. with pytest.raises(Exception, match="padded_sample is specified and requires num_padded as well."):
  326. partitions(4, 2)
  327. def test_cv_minddataset_partition_padded_samples_no_padded_samples(add_and_remove_cv_file):
  328. columns_list = ["data", "file_name", "label"]
  329. data = get_data(CV_DIR_NAME)
  330. padded_sample = data[0]
  331. padded_sample['file_name'] = 'dummy.jpg'
  332. num_readers = 4
  333. def partitions(num_shards, num_padded):
  334. for partition_id in range(num_shards):
  335. data_set = ds.MindDataset(CV_FILE_NAME + "0", None, num_readers,
  336. num_shards=num_shards,
  337. shard_id=partition_id,
  338. num_padded=num_padded)
  339. for item in data_set.create_dict_iterator(num_epochs=1, output_numpy=True):
  340. logger.info("-------------- partition : {} ------------------------".format(partition_id))
  341. logger.info("-------------- len(item[data]): {} ------------------------".format(len(item["data"])))
  342. logger.info("-------------- item[data]: {} -----------------------------".format(item["data"]))
  343. logger.info("-------------- item[file_name]: {} ------------------------".format(item["file_name"]))
  344. with pytest.raises(Exception, match="num_padded is specified but padded_sample is not."):
  345. partitions(4, 2)
  346. def test_nlp_minddataset_reader_basic_padded_samples(add_and_remove_nlp_file):
  347. columns_list = ["input_ids", "id", "rating"]
  348. data = [x for x in get_nlp_data(NLP_FILE_POS, NLP_FILE_VOCAB, 10)]
  349. padded_sample = data[0]
  350. padded_sample['id'] = "-1"
  351. padded_sample['input_ids'] = np.array([-1, -1, -1, -1], dtype=np.int64)
  352. padded_sample['rating'] = 1.0
  353. num_readers = 4
  354. def partitions(num_shards, num_padded, dataset_size):
  355. num_padded_iter = 0
  356. num_iter = 0
  357. for partition_id in range(num_shards):
  358. data_set = ds.MindDataset(NLP_FILE_NAME + "0", columns_list, num_readers,
  359. num_shards=num_shards,
  360. shard_id=partition_id,
  361. padded_sample=padded_sample,
  362. num_padded=num_padded)
  363. assert data_set.get_dataset_size() == dataset_size
  364. for item in data_set.create_dict_iterator(num_epochs=1, output_numpy=True):
  365. logger.info("-------------- item[id]: {} ------------------------".format(item["id"]))
  366. logger.info("-------------- item[rating]: {} --------------------".format(item["rating"]))
  367. logger.info("-------------- item[input_ids]: {}, shape: {} -----------------".format(
  368. item["input_ids"],
  369. item["input_ids"].shape))
  370. if item['id'] == bytes('-1', encoding='utf-8'):
  371. num_padded_iter += 1
  372. assert item['id'] == bytes(padded_sample['id'], encoding='utf-8')
  373. assert (item['input_ids'] == padded_sample['input_ids']).all()
  374. assert (item['rating'] == padded_sample['rating']).all()
  375. num_iter += 1
  376. assert num_padded_iter == num_padded
  377. assert num_iter == dataset_size * num_shards
  378. partitions(4, 6, 4)
  379. partitions(5, 5, 3)
  380. partitions(9, 8, 2)
  381. def test_nlp_minddataset_reader_basic_padded_samples_multi_epoch(add_and_remove_nlp_file):
  382. columns_list = ["input_ids", "id", "rating"]
  383. data = [x for x in get_nlp_data(NLP_FILE_POS, NLP_FILE_VOCAB, 10)]
  384. padded_sample = data[0]
  385. padded_sample['id'] = "-1"
  386. padded_sample['input_ids'] = np.array([-1, -1, -1, -1], dtype=np.int64)
  387. padded_sample['rating'] = 1.0
  388. num_readers = 4
  389. repeat_size = 3
  390. def partitions(num_shards, num_padded, dataset_size):
  391. num_padded_iter = 0
  392. num_iter = 0
  393. for partition_id in range(num_shards):
  394. epoch1_shuffle_result = []
  395. epoch2_shuffle_result = []
  396. epoch3_shuffle_result = []
  397. data_set = ds.MindDataset(NLP_FILE_NAME + "0", columns_list, num_readers,
  398. num_shards=num_shards,
  399. shard_id=partition_id,
  400. padded_sample=padded_sample,
  401. num_padded=num_padded)
  402. assert data_set.get_dataset_size() == dataset_size
  403. data_set = data_set.repeat(repeat_size)
  404. local_index = 0
  405. for item in data_set.create_dict_iterator(num_epochs=1, output_numpy=True):
  406. logger.info("-------------- item[id]: {} ------------------------".format(item["id"]))
  407. logger.info("-------------- item[rating]: {} --------------------".format(item["rating"]))
  408. logger.info("-------------- item[input_ids]: {}, shape: {} -----------------".format(
  409. item["input_ids"],
  410. item["input_ids"].shape))
  411. if item['id'] == bytes('-1', encoding='utf-8'):
  412. num_padded_iter += 1
  413. assert item['id'] == bytes(padded_sample['id'], encoding='utf-8')
  414. assert (item['input_ids'] == padded_sample['input_ids']).all()
  415. assert (item['rating'] == padded_sample['rating']).all()
  416. if local_index < dataset_size:
  417. epoch1_shuffle_result.append(item['id'])
  418. elif local_index < dataset_size * 2:
  419. epoch2_shuffle_result.append(item['id'])
  420. elif local_index < dataset_size * 3:
  421. epoch3_shuffle_result.append(item['id'])
  422. local_index += 1
  423. num_iter += 1
  424. assert len(epoch1_shuffle_result) == dataset_size
  425. assert len(epoch2_shuffle_result) == dataset_size
  426. assert len(epoch3_shuffle_result) == dataset_size
  427. assert local_index == dataset_size * repeat_size
  428. # When dataset_size is equal to 2, too high probability is the same result after shuffle operation
  429. if dataset_size > 2:
  430. assert epoch1_shuffle_result != epoch2_shuffle_result
  431. assert epoch2_shuffle_result != epoch3_shuffle_result
  432. assert num_padded_iter == num_padded * repeat_size
  433. assert num_iter == dataset_size * num_shards * repeat_size
  434. partitions(4, 6, 4)
  435. partitions(5, 5, 3)
  436. partitions(9, 8, 2)
  437. def test_nlp_minddataset_reader_basic_padded_samples_check_whole_reshuffle_result_per_epoch(add_and_remove_nlp_file):
  438. columns_list = ["input_ids", "id", "rating"]
  439. padded_sample = {}
  440. padded_sample['id'] = "-1"
  441. padded_sample['input_ids'] = np.array([-1, -1, -1, -1], dtype=np.int64)
  442. padded_sample['rating'] = 1.0
  443. num_readers = 4
  444. repeat_size = 3
  445. def partitions(num_shards, num_padded, dataset_size):
  446. num_padded_iter = 0
  447. num_iter = 0
  448. epoch_result = [[["" for i in range(dataset_size)] for i in range(repeat_size)] for i in range(num_shards)]
  449. for partition_id in range(num_shards):
  450. data_set = ds.MindDataset(NLP_FILE_NAME + "0", columns_list, num_readers,
  451. num_shards=num_shards,
  452. shard_id=partition_id,
  453. padded_sample=padded_sample,
  454. num_padded=num_padded)
  455. assert data_set.get_dataset_size() == dataset_size
  456. data_set = data_set.repeat(repeat_size)
  457. inner_num_iter = 0
  458. for item in data_set.create_dict_iterator(num_epochs=1, output_numpy=True):
  459. logger.info("-------------- item[id]: {} ------------------------".format(item["id"]))
  460. logger.info("-------------- item[rating]: {} --------------------".format(item["rating"]))
  461. logger.info("-------------- item[input_ids]: {}, shape: {} -----------------"
  462. .format(item["input_ids"], item["input_ids"].shape))
  463. if item['id'] == bytes('-1', encoding='utf-8'):
  464. num_padded_iter += 1
  465. assert item['id'] == bytes(padded_sample['id'], encoding='utf-8')
  466. assert (item['input_ids'] == padded_sample['input_ids']).all()
  467. assert (item['rating'] == padded_sample['rating']).all()
  468. # save epoch result
  469. epoch_result[partition_id][int(inner_num_iter / dataset_size)][inner_num_iter % dataset_size] = item[
  470. "id"]
  471. num_iter += 1
  472. inner_num_iter += 1
  473. assert epoch_result[partition_id][0] not in (epoch_result[partition_id][1], epoch_result[partition_id][2])
  474. assert epoch_result[partition_id][1] not in (epoch_result[partition_id][0], epoch_result[partition_id][2])
  475. assert epoch_result[partition_id][2] not in (epoch_result[partition_id][1], epoch_result[partition_id][0])
  476. if dataset_size > 2:
  477. epoch_result[partition_id][0].sort()
  478. epoch_result[partition_id][1].sort()
  479. epoch_result[partition_id][2].sort()
  480. assert epoch_result[partition_id][0] != epoch_result[partition_id][1]
  481. assert epoch_result[partition_id][1] != epoch_result[partition_id][2]
  482. assert epoch_result[partition_id][2] != epoch_result[partition_id][0]
  483. assert num_padded_iter == num_padded * repeat_size
  484. assert num_iter == dataset_size * num_shards * repeat_size
  485. partitions(4, 6, 4)
  486. partitions(5, 5, 3)
  487. partitions(9, 8, 2)
  488. def get_data(dir_name):
  489. """
  490. usage: get data from imagenet dataset
  491. params:
  492. dir_name: directory containing folder images and annotation information
  493. """
  494. if not os.path.isdir(dir_name):
  495. raise IOError("Directory {} not exists".format(dir_name))
  496. img_dir = os.path.join(dir_name, "images")
  497. ann_file = os.path.join(dir_name, "annotation.txt")
  498. with open(ann_file, "r") as file_reader:
  499. lines = file_reader.readlines()
  500. data_list = []
  501. for i, line in enumerate(lines):
  502. try:
  503. filename, label = line.split(",")
  504. label = label.strip("\n")
  505. with open(os.path.join(img_dir, filename), "rb") as file_reader:
  506. img = file_reader.read()
  507. data_json = {"id": i,
  508. "file_name": filename,
  509. "data": img,
  510. "label": int(label)}
  511. data_list.append(data_json)
  512. except FileNotFoundError:
  513. continue
  514. return data_list
  515. def get_nlp_data(dir_name, vocab_file, num):
  516. """
  517. Return raw data of aclImdb dataset.
  518. Args:
  519. dir_name (str): String of aclImdb dataset's path.
  520. vocab_file (str): String of dictionary's path.
  521. num (int): Number of sample.
  522. Returns:
  523. List
  524. """
  525. if not os.path.isdir(dir_name):
  526. raise IOError("Directory {} not exists".format(dir_name))
  527. for root, dirs, files in os.walk(dir_name):
  528. for index, file_name_extension in enumerate(files):
  529. if index < num:
  530. file_path = os.path.join(root, file_name_extension)
  531. file_name, _ = file_name_extension.split('.', 1)
  532. id_, rating = file_name.split('_', 1)
  533. with open(file_path, 'r') as f:
  534. raw_content = f.read()
  535. dictionary = load_vocab(vocab_file)
  536. vectors = [dictionary.get('[CLS]')]
  537. vectors += [dictionary.get(i) if i in dictionary
  538. else dictionary.get('[UNK]')
  539. for i in re.findall(r"[\w']+|[{}]"
  540. .format(string.punctuation),
  541. raw_content)]
  542. vectors += [dictionary.get('[SEP]')]
  543. input_, mask, segment = inputs(vectors)
  544. input_ids = np.reshape(np.array(input_), [-1])
  545. input_mask = np.reshape(np.array(mask), [1, -1])
  546. segment_ids = np.reshape(np.array(segment), [2, -1])
  547. data = {
  548. "label": 1,
  549. "id": id_,
  550. "rating": float(rating),
  551. "input_ids": input_ids,
  552. "input_mask": input_mask,
  553. "segment_ids": segment_ids
  554. }
  555. yield data
  556. def convert_to_uni(text):
  557. if isinstance(text, str):
  558. return text
  559. if isinstance(text, bytes):
  560. return text.decode('utf-8', 'ignore')
  561. raise Exception("The type %s does not convert!" % type(text))
  562. def load_vocab(vocab_file):
  563. """load vocabulary to translate statement."""
  564. vocab = collections.OrderedDict()
  565. vocab.setdefault('blank', 2)
  566. index = 0
  567. with open(vocab_file) as reader:
  568. while True:
  569. tmp = reader.readline()
  570. if not tmp:
  571. break
  572. token = convert_to_uni(tmp)
  573. token = token.strip()
  574. vocab[token] = index
  575. index += 1
  576. return vocab
  577. def inputs(vectors, maxlen=50):
  578. length = len(vectors)
  579. if length > maxlen:
  580. return vectors[0:maxlen], [1] * maxlen, [0] * maxlen
  581. input_ = vectors + [0] * (maxlen - length)
  582. mask = [1] * length + [0] * (maxlen - length)
  583. segment = [0] * maxlen
  584. return input_, mask, segment
  585. if __name__ == '__main__':
  586. test_cv_minddataset_reader_basic_padded_samples(add_and_remove_cv_file)
  587. test_cv_minddataset_partition_padded_samples(add_and_remove_cv_file)
  588. test_cv_minddataset_partition_padded_samples_multi_epoch(add_and_remove_cv_file)
  589. test_cv_minddataset_partition_padded_samples_no_dividsible(add_and_remove_cv_file)
  590. test_cv_minddataset_partition_padded_samples_dataset_size_no_divisible(add_and_remove_cv_file)
  591. test_cv_minddataset_partition_padded_samples_no_equal_column_list(add_and_remove_cv_file)
  592. test_cv_minddataset_partition_padded_samples_no_column_list(add_and_remove_cv_file)
  593. test_cv_minddataset_partition_padded_samples_no_num_padded(add_and_remove_cv_file)
  594. test_cv_minddataset_partition_padded_samples_no_padded_samples(add_and_remove_cv_file)
  595. test_nlp_minddataset_reader_basic_padded_samples(add_and_remove_nlp_file)
  596. test_nlp_minddataset_reader_basic_padded_samples_multi_epoch(add_and_remove_nlp_file)
  597. test_nlp_minddataset_reader_basic_padded_samples_check_whole_reshuffle_result_per_epoch(add_and_remove_nlp_file)