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

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

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