cifar.py 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167
  1. import os.path
  2. import pickle
  3. from pathlib import Path
  4. from typing import Any, Callable, Optional, Union
  5. import numpy as np
  6. from PIL import Image
  7. from .utils import check_integrity, download_and_extract_archive
  8. from .vision import VisionDataset
  9. class CIFAR10(VisionDataset):
  10. """`CIFAR10 <https://www.cs.toronto.edu/~kriz/cifar.html>`_ Dataset.
  11. Args:
  12. root (str or ``pathlib.Path``): Root directory of dataset where directory
  13. ``cifar-10-batches-py`` exists or will be saved to if download is set to True.
  14. train (bool, optional): If True, creates dataset from training set, otherwise
  15. creates from test set.
  16. transform (callable, optional): A function/transform that takes in a PIL image
  17. and returns a transformed version. E.g, ``transforms.RandomCrop``
  18. target_transform (callable, optional): A function/transform that takes in the
  19. target and transforms it.
  20. download (bool, optional): If true, downloads the dataset from the internet and
  21. puts it in root directory. If dataset is already downloaded, it is not
  22. downloaded again.
  23. """
  24. base_folder = "cifar-10-batches-py"
  25. url = "https://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz"
  26. filename = "cifar-10-python.tar.gz"
  27. tgz_md5 = "c58f30108f718f92721af3b95e74349a"
  28. train_list = [
  29. ["data_batch_1", "c99cafc152244af753f735de768cd75f"],
  30. ["data_batch_2", "d4bba439e000b95fd0a9bffe97cbabec"],
  31. ["data_batch_3", "54ebc095f3ab1f0389bbae665268c751"],
  32. ["data_batch_4", "634d18415352ddfa80567beed471001a"],
  33. ["data_batch_5", "482c414d41f54cd18b22e5b47cb7c3cb"],
  34. ]
  35. test_list = [
  36. ["test_batch", "40351d587109b95175f43aff81a1287e"],
  37. ]
  38. meta = {
  39. "filename": "batches.meta",
  40. "key": "label_names",
  41. "md5": "5ff9c542aee3614f3951f8cda6e48888",
  42. }
  43. def __init__(
  44. self,
  45. root: Union[str, Path],
  46. train: bool = True,
  47. transform: Optional[Callable] = None,
  48. target_transform: Optional[Callable] = None,
  49. download: bool = False,
  50. ) -> None:
  51. super().__init__(root, transform=transform, target_transform=target_transform)
  52. self.train = train # training set or test set
  53. if download:
  54. self.download()
  55. if not self._check_integrity():
  56. raise RuntimeError("Dataset not found or corrupted. You can use download=True to download it")
  57. if self.train:
  58. downloaded_list = self.train_list
  59. else:
  60. downloaded_list = self.test_list
  61. self.data: Any = []
  62. self.targets = []
  63. # now load the picked numpy arrays
  64. for file_name, checksum in downloaded_list:
  65. file_path = os.path.join(self.root, self.base_folder, file_name)
  66. with open(file_path, "rb") as f:
  67. entry = pickle.load(f, encoding="latin1")
  68. self.data.append(entry["data"])
  69. if "labels" in entry:
  70. self.targets.extend(entry["labels"])
  71. else:
  72. self.targets.extend(entry["fine_labels"])
  73. self.data = np.vstack(self.data).reshape(-1, 3, 32, 32)
  74. self.data = self.data.transpose((0, 2, 3, 1)) # convert to HWC
  75. self._load_meta()
  76. def _load_meta(self) -> None:
  77. path = os.path.join(self.root, self.base_folder, self.meta["filename"])
  78. if not check_integrity(path, self.meta["md5"]):
  79. raise RuntimeError("Dataset metadata file not found or corrupted. You can use download=True to download it")
  80. with open(path, "rb") as infile:
  81. data = pickle.load(infile, encoding="latin1")
  82. self.classes = data[self.meta["key"]]
  83. self.class_to_idx = {_class: i for i, _class in enumerate(self.classes)}
  84. def __getitem__(self, index: int) -> tuple[Any, Any]:
  85. """
  86. Args:
  87. index (int): Index
  88. Returns:
  89. tuple: (image, target) where target is index of the target class.
  90. """
  91. img, target = self.data[index], self.targets[index]
  92. # doing this so that it is consistent with all other datasets
  93. # to return a PIL Image
  94. img = Image.fromarray(img)
  95. if self.transform is not None:
  96. img = self.transform(img)
  97. if self.target_transform is not None:
  98. target = self.target_transform(target)
  99. return img, target
  100. def __len__(self) -> int:
  101. return len(self.data)
  102. def _check_integrity(self) -> bool:
  103. for filename, md5 in self.train_list + self.test_list:
  104. fpath = os.path.join(self.root, self.base_folder, filename)
  105. if not check_integrity(fpath, md5):
  106. return False
  107. return True
  108. def download(self) -> None:
  109. if self._check_integrity():
  110. return
  111. download_and_extract_archive(self.url, self.root, filename=self.filename, md5=self.tgz_md5)
  112. def extra_repr(self) -> str:
  113. split = "Train" if self.train is True else "Test"
  114. return f"Split: {split}"
  115. class CIFAR100(CIFAR10):
  116. """`CIFAR100 <https://www.cs.toronto.edu/~kriz/cifar.html>`_ Dataset.
  117. This is a subclass of the `CIFAR10` Dataset.
  118. """
  119. base_folder = "cifar-100-python"
  120. url = "https://www.cs.toronto.edu/~kriz/cifar-100-python.tar.gz"
  121. filename = "cifar-100-python.tar.gz"
  122. tgz_md5 = "eb9058c3a382ffc7106e4002c42a8d85"
  123. train_list = [
  124. ["train", "16019d7e3df5f24257cddd939b257f8d"],
  125. ]
  126. test_list = [
  127. ["test", "f0ef6b0ae62326f3e7ffdfab6717acfc"],
  128. ]
  129. meta = {
  130. "filename": "meta",
  131. "key": "fine_label_names",
  132. "md5": "7973b15100ade9c7d40fb424638fde48",
  133. }