svhn.py 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130
  1. import os.path
  2. from pathlib import Path
  3. from typing import Any, Callable, Optional, Union
  4. import numpy as np
  5. from PIL import Image
  6. from .utils import check_integrity, download_url, verify_str_arg
  7. from .vision import VisionDataset
  8. class SVHN(VisionDataset):
  9. """`SVHN <http://ufldl.stanford.edu/housenumbers/>`_ Dataset.
  10. Note: The SVHN dataset assigns the label `10` to the digit `0`. However, in this Dataset,
  11. we assign the label `0` to the digit `0` to be compatible with PyTorch loss functions which
  12. expect the class labels to be in the range `[0, C-1]`
  13. .. warning::
  14. This class needs `scipy <https://docs.scipy.org/doc/>`_ to load data from `.mat` format.
  15. Args:
  16. root (str or ``pathlib.Path``): Root directory of the dataset where the data is stored.
  17. split (string): One of {'train', 'test', 'extra'}.
  18. Accordingly dataset is selected. 'extra' is Extra training set.
  19. transform (callable, optional): A function/transform that takes in a PIL image
  20. and returns a transformed version. E.g, ``transforms.RandomCrop``
  21. target_transform (callable, optional): A function/transform that takes in the
  22. target and transforms it.
  23. download (bool, optional): If true, downloads the dataset from the internet and
  24. puts it in root directory. If dataset is already downloaded, it is not
  25. downloaded again.
  26. """
  27. split_list = {
  28. "train": [
  29. "http://ufldl.stanford.edu/housenumbers/train_32x32.mat",
  30. "train_32x32.mat",
  31. "e26dedcc434d2e4c54c9b2d4a06d8373",
  32. ],
  33. "test": [
  34. "http://ufldl.stanford.edu/housenumbers/test_32x32.mat",
  35. "test_32x32.mat",
  36. "eb5a983be6a315427106f1b164d9cef3",
  37. ],
  38. "extra": [
  39. "http://ufldl.stanford.edu/housenumbers/extra_32x32.mat",
  40. "extra_32x32.mat",
  41. "a93ce644f1a588dc4d68dda5feec44a7",
  42. ],
  43. }
  44. def __init__(
  45. self,
  46. root: Union[str, Path],
  47. split: str = "train",
  48. transform: Optional[Callable] = None,
  49. target_transform: Optional[Callable] = None,
  50. download: bool = False,
  51. ) -> None:
  52. super().__init__(root, transform=transform, target_transform=target_transform)
  53. self.split = verify_str_arg(split, "split", tuple(self.split_list.keys()))
  54. self.url = self.split_list[split][0]
  55. self.filename = self.split_list[split][1]
  56. self.file_md5 = self.split_list[split][2]
  57. if download:
  58. self.download()
  59. if not self._check_integrity():
  60. raise RuntimeError("Dataset not found or corrupted. You can use download=True to download it")
  61. # import here rather than at top of file because this is
  62. # an optional dependency for torchvision
  63. import scipy.io as sio
  64. # reading(loading) mat file as array
  65. loaded_mat = sio.loadmat(os.path.join(self.root, self.filename))
  66. self.data = loaded_mat["X"]
  67. # loading from the .mat file gives an np.ndarray of type np.uint8
  68. # converting to np.int64, so that we have a LongTensor after
  69. # the conversion from the numpy array
  70. # the squeeze is needed to obtain a 1D tensor
  71. self.labels = loaded_mat["y"].astype(np.int64).squeeze()
  72. # the svhn dataset assigns the class label "10" to the digit 0
  73. # this makes it inconsistent with several loss functions
  74. # which expect the class labels to be in the range [0, C-1]
  75. np.place(self.labels, self.labels == 10, 0)
  76. self.data = np.transpose(self.data, (3, 2, 0, 1))
  77. def __getitem__(self, index: int) -> tuple[Any, Any]:
  78. """
  79. Args:
  80. index (int): Index
  81. Returns:
  82. tuple: (image, target) where target is index of the target class.
  83. """
  84. img, target = self.data[index], int(self.labels[index])
  85. # doing this so that it is consistent with all other datasets
  86. # to return a PIL Image
  87. img = Image.fromarray(np.transpose(img, (1, 2, 0)))
  88. if self.transform is not None:
  89. img = self.transform(img)
  90. if self.target_transform is not None:
  91. target = self.target_transform(target)
  92. return img, target
  93. def __len__(self) -> int:
  94. return len(self.data)
  95. def _check_integrity(self) -> bool:
  96. root = self.root
  97. md5 = self.split_list[self.split][2]
  98. fpath = os.path.join(root, self.filename)
  99. return check_integrity(fpath, md5)
  100. def download(self) -> None:
  101. md5 = self.split_list[self.split][2]
  102. download_url(self.url, self.root, self.filename, md5)
  103. def extra_repr(self) -> str:
  104. return "Split: {split}".format(**self.__dict__)