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.

mnist.py 6.3 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197
  1. # -*- coding: utf-8 -*-
  2. # MegEngine is Licensed under the Apache License, Version 2.0 (the "License")
  3. #
  4. # Copyright (c) 2014-2020 Megvii Inc. All rights reserved.
  5. #
  6. # Unless required by applicable law or agreed to in writing,
  7. # software distributed under the License is distributed on an
  8. # "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9. import gzip
  10. import os
  11. import struct
  12. from typing import Tuple
  13. import numpy as np
  14. from tqdm import tqdm
  15. from ....logger import get_logger
  16. from .meta_vision import VisionDataset
  17. from .utils import _default_dataset_root, load_raw_data_from_url
  18. logger = get_logger(__name__)
  19. class MNIST(VisionDataset):
  20. r""" ``Dataset`` for MNIST meta data.
  21. """
  22. url_path = "http://yann.lecun.com/exdb/mnist/"
  23. """
  24. Url prefix for downloading raw file.
  25. """
  26. raw_file_name = [
  27. "train-images-idx3-ubyte.gz",
  28. "train-labels-idx1-ubyte.gz",
  29. "t10k-images-idx3-ubyte.gz",
  30. "t10k-labels-idx1-ubyte.gz",
  31. ]
  32. """
  33. Raw file names of both training set and test set (10k).
  34. """
  35. raw_file_md5 = [
  36. "f68b3c2dcbeaaa9fbdd348bbdeb94873",
  37. "d53e105ee54ea40749a09fcbcd1e9432",
  38. "9fb629c4189551a2d022fa330f9573f3",
  39. "ec29112dd5afa0611ce80d1b7f02629c",
  40. ]
  41. """
  42. Md5 for checking raw files.
  43. """
  44. def __init__(
  45. self,
  46. root: str = None,
  47. train: bool = True,
  48. download: bool = True,
  49. timeout: int = 500,
  50. ):
  51. r"""
  52. :param root: path for mnist dataset downloading or loading, if ``None``,
  53. set ``root`` to the ``_default_root``.
  54. :param train: if ``True``, loading trainingset, else loading test set.
  55. :param download: if raw files do not exists and download sets to ``True``,
  56. download raw files and process, otherwise raise ValueError, default is True.
  57. """
  58. super().__init__(root, order=("image", "image_category"))
  59. self.timeout = timeout
  60. # process the root path
  61. if root is None:
  62. self.root = self._default_root
  63. if not os.path.exists(self.root):
  64. os.makedirs(self.root)
  65. else:
  66. self.root = root
  67. if not os.path.exists(self.root):
  68. if download:
  69. logger.debug(
  70. "dir %s does not exist, will be automatically created",
  71. self.root,
  72. )
  73. os.makedirs(self.root)
  74. else:
  75. raise ValueError("dir %s does not exist" % self.root)
  76. if self._check_raw_files():
  77. self.process(train)
  78. elif download:
  79. self.download()
  80. self.process(train)
  81. else:
  82. raise ValueError(
  83. "root does not contain valid raw files, please set download=True"
  84. )
  85. def __getitem__(self, index: int) -> Tuple:
  86. return tuple(array[index] for array in self.arrays)
  87. def __len__(self) -> int:
  88. return len(self.arrays[0])
  89. @property
  90. def _default_root(self):
  91. return os.path.join(_default_dataset_root(), self.__class__.__name__)
  92. @property
  93. def meta(self):
  94. return self._meta_data
  95. def _check_raw_files(self):
  96. return all(
  97. [
  98. os.path.exists(os.path.join(self.root, path))
  99. for path in self.raw_file_name
  100. ]
  101. )
  102. def download(self):
  103. for file_name, md5 in zip(self.raw_file_name, self.raw_file_md5):
  104. url = self.url_path + file_name
  105. load_raw_data_from_url(url, file_name, md5, self.root, self.timeout)
  106. def process(self, train):
  107. # load raw files and transform them into meta data and datasets Tuple(np.array)
  108. logger.info("process the raw files of %s set...", "train" if train else "test")
  109. if train:
  110. meta_data_images, images = parse_idx3(
  111. os.path.join(self.root, self.raw_file_name[0])
  112. )
  113. meta_data_labels, labels = parse_idx1(
  114. os.path.join(self.root, self.raw_file_name[1])
  115. )
  116. else:
  117. meta_data_images, images = parse_idx3(
  118. os.path.join(self.root, self.raw_file_name[2])
  119. )
  120. meta_data_labels, labels = parse_idx1(
  121. os.path.join(self.root, self.raw_file_name[3])
  122. )
  123. self._meta_data = {
  124. "images": meta_data_images,
  125. "labels": meta_data_labels,
  126. }
  127. self.arrays = (images, labels.astype(np.int32))
  128. def parse_idx3(idx3_file):
  129. # parse idx3 file to meta data and data in numpy array (images)
  130. logger.debug("parse idx3 file %s ...", idx3_file)
  131. assert idx3_file.endswith(".gz")
  132. with gzip.open(idx3_file, "rb") as f:
  133. bin_data = f.read()
  134. # parse meta data
  135. offset = 0
  136. fmt_header = ">iiii"
  137. magic, imgs, height, width = struct.unpack_from(fmt_header, bin_data, offset)
  138. meta_data = {"magic": magic, "imgs": imgs, "height": height, "width": width}
  139. # parse images
  140. image_size = height * width
  141. offset += struct.calcsize(fmt_header)
  142. fmt_image = ">" + str(image_size) + "B"
  143. images = []
  144. bar = tqdm(total=meta_data["imgs"], ncols=80)
  145. for image in struct.iter_unpack(fmt_image, bin_data[offset:]):
  146. images.append(np.array(image, dtype=np.uint8).reshape((height, width, 1)))
  147. bar.update()
  148. bar.close()
  149. return meta_data, images
  150. def parse_idx1(idx1_file):
  151. # parse idx1 file to meta data and data in numpy array (labels)
  152. logger.debug("parse idx1 file %s ...", idx1_file)
  153. assert idx1_file.endswith(".gz")
  154. with gzip.open(idx1_file, "rb") as f:
  155. bin_data = f.read()
  156. # parse meta data
  157. offset = 0
  158. fmt_header = ">ii"
  159. magic, imgs = struct.unpack_from(fmt_header, bin_data, offset)
  160. meta_data = {"magic": magic, "imgs": imgs}
  161. # parse labels
  162. offset += struct.calcsize(fmt_header)
  163. fmt_image = ">B"
  164. labels = np.empty(imgs, dtype=int)
  165. bar = tqdm(total=meta_data["imgs"], ncols=80)
  166. for i, label in enumerate(struct.iter_unpack(fmt_image, bin_data[offset:])):
  167. labels[i] = label[0]
  168. bar.update()
  169. bar.close()
  170. return meta_data, labels

MegEngine 安装包中集成了使用 GPU 运行代码所需的 CUDA 环境,不用区分 CPU 和 GPU 版。 如果想要运行 GPU 程序,请确保机器本身配有 GPU 硬件设备并安装好驱动。 如果你想体验在云端 GPU 算力平台进行深度学习开发的感觉,欢迎访问 MegStudio 平台