Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

svhn.py 4.7 KB

You have to be logged in to leave a comment. Sign In
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
  1. import os.path
  2. from pathlib import Path
  3. from typing import Any, Callable, Optional, Tuple, 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__)
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...