stl10.py 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174
  1. import os.path
  2. from typing import Any, Callable, cast, Optional, Tuple
  3. import numpy as np
  4. from PIL import Image
  5. from .utils import check_integrity, download_and_extract_archive, verify_str_arg
  6. from .vision import VisionDataset
  7. class STL10(VisionDataset):
  8. """`STL10 <https://cs.stanford.edu/~acoates/stl10/>`_ Dataset.
  9. Args:
  10. root (string): Root directory of dataset where directory
  11. ``stl10_binary`` exists.
  12. split (string): One of {'train', 'test', 'unlabeled', 'train+unlabeled'}.
  13. Accordingly, dataset is selected.
  14. folds (int, optional): One of {0-9} or None.
  15. For training, loads one of the 10 pre-defined folds of 1k samples for the
  16. standard evaluation procedure. If no value is passed, loads the 5k samples.
  17. transform (callable, optional): A function/transform that takes in an PIL image
  18. and returns a transformed version. E.g, ``transforms.RandomCrop``
  19. target_transform (callable, optional): A function/transform that takes in the
  20. target and transforms it.
  21. download (bool, optional): If true, downloads the dataset from the internet and
  22. puts it in root directory. If dataset is already downloaded, it is not
  23. downloaded again.
  24. """
  25. base_folder = "stl10_binary"
  26. url = "http://ai.stanford.edu/~acoates/stl10/stl10_binary.tar.gz"
  27. filename = "stl10_binary.tar.gz"
  28. tgz_md5 = "91f7769df0f17e558f3565bffb0c7dfb"
  29. class_names_file = "class_names.txt"
  30. folds_list_file = "fold_indices.txt"
  31. train_list = [
  32. ["train_X.bin", "918c2871b30a85fa023e0c44e0bee87f"],
  33. ["train_y.bin", "5a34089d4802c674881badbb80307741"],
  34. ["unlabeled_X.bin", "5242ba1fed5e4be9e1e742405eb56ca4"],
  35. ]
  36. test_list = [["test_X.bin", "7f263ba9f9e0b06b93213547f721ac82"], ["test_y.bin", "36f9794fa4beb8a2c72628de14fa638e"]]
  37. splits = ("train", "train+unlabeled", "unlabeled", "test")
  38. def __init__(
  39. self,
  40. root: str,
  41. split: str = "train",
  42. folds: Optional[int] = None,
  43. transform: Optional[Callable] = None,
  44. target_transform: Optional[Callable] = None,
  45. download: bool = False,
  46. ) -> None:
  47. super().__init__(root, transform=transform, target_transform=target_transform)
  48. self.split = verify_str_arg(split, "split", self.splits)
  49. self.folds = self._verify_folds(folds)
  50. if download:
  51. self.download()
  52. elif not self._check_integrity():
  53. raise RuntimeError("Dataset not found or corrupted. You can use download=True to download it")
  54. # now load the picked numpy arrays
  55. self.labels: Optional[np.ndarray]
  56. if self.split == "train":
  57. self.data, self.labels = self.__loadfile(self.train_list[0][0], self.train_list[1][0])
  58. self.labels = cast(np.ndarray, self.labels)
  59. self.__load_folds(folds)
  60. elif self.split == "train+unlabeled":
  61. self.data, self.labels = self.__loadfile(self.train_list[0][0], self.train_list[1][0])
  62. self.labels = cast(np.ndarray, self.labels)
  63. self.__load_folds(folds)
  64. unlabeled_data, _ = self.__loadfile(self.train_list[2][0])
  65. self.data = np.concatenate((self.data, unlabeled_data))
  66. self.labels = np.concatenate((self.labels, np.asarray([-1] * unlabeled_data.shape[0])))
  67. elif self.split == "unlabeled":
  68. self.data, _ = self.__loadfile(self.train_list[2][0])
  69. self.labels = np.asarray([-1] * self.data.shape[0])
  70. else: # self.split == 'test':
  71. self.data, self.labels = self.__loadfile(self.test_list[0][0], self.test_list[1][0])
  72. class_file = os.path.join(self.root, self.base_folder, self.class_names_file)
  73. if os.path.isfile(class_file):
  74. with open(class_file) as f:
  75. self.classes = f.read().splitlines()
  76. def _verify_folds(self, folds: Optional[int]) -> Optional[int]:
  77. if folds is None:
  78. return folds
  79. elif isinstance(folds, int):
  80. if folds in range(10):
  81. return folds
  82. msg = "Value for argument folds should be in the range [0, 10), but got {}."
  83. raise ValueError(msg.format(folds))
  84. else:
  85. msg = "Expected type None or int for argument folds, but got type {}."
  86. raise ValueError(msg.format(type(folds)))
  87. def __getitem__(self, index: int) -> Tuple[Any, Any]:
  88. """
  89. Args:
  90. index (int): Index
  91. Returns:
  92. tuple: (image, target) where target is index of the target class.
  93. """
  94. target: Optional[int]
  95. if self.labels is not None:
  96. img, target = self.data[index], int(self.labels[index])
  97. else:
  98. img, target = self.data[index], None
  99. # doing this so that it is consistent with all other datasets
  100. # to return a PIL Image
  101. img = Image.fromarray(np.transpose(img, (1, 2, 0)))
  102. if self.transform is not None:
  103. img = self.transform(img)
  104. if self.target_transform is not None:
  105. target = self.target_transform(target)
  106. return img, target
  107. def __len__(self) -> int:
  108. return self.data.shape[0]
  109. def __loadfile(self, data_file: str, labels_file: Optional[str] = None) -> Tuple[np.ndarray, Optional[np.ndarray]]:
  110. labels = None
  111. if labels_file:
  112. path_to_labels = os.path.join(self.root, self.base_folder, labels_file)
  113. with open(path_to_labels, "rb") as f:
  114. labels = np.fromfile(f, dtype=np.uint8) - 1 # 0-based
  115. path_to_data = os.path.join(self.root, self.base_folder, data_file)
  116. with open(path_to_data, "rb") as f:
  117. # read whole file in uint8 chunks
  118. everything = np.fromfile(f, dtype=np.uint8)
  119. images = np.reshape(everything, (-1, 3, 96, 96))
  120. images = np.transpose(images, (0, 1, 3, 2))
  121. return images, labels
  122. def _check_integrity(self) -> bool:
  123. for filename, md5 in self.train_list + self.test_list:
  124. fpath = os.path.join(self.root, self.base_folder, filename)
  125. if not check_integrity(fpath, md5):
  126. return False
  127. return True
  128. def download(self) -> None:
  129. if self._check_integrity():
  130. print("Files already downloaded and verified")
  131. return
  132. download_and_extract_archive(self.url, self.root, filename=self.filename, md5=self.tgz_md5)
  133. self._check_integrity()
  134. def extra_repr(self) -> str:
  135. return "Split: {split}".format(**self.__dict__)
  136. def __load_folds(self, folds: Optional[int]) -> None:
  137. # loads one of the folds if specified
  138. if folds is None:
  139. return
  140. path_to_folds = os.path.join(self.root, self.base_folder, self.folds_list_file)
  141. with open(path_to_folds) as f:
  142. str_idx = f.read().splitlines()[folds]
  143. list_idx = np.fromstring(str_idx, dtype=np.int64, sep=" ")
  144. self.data = self.data[list_idx, :, :, :]
  145. if self.labels is not None:
  146. self.labels = self.labels[list_idx]