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

clevr.py 3.8 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
  1. import json
  2. import pathlib
  3. from typing import Any, Callable, List, Optional, Tuple, Union
  4. from urllib.parse import urlparse
  5. from .folder import default_loader
  6. from .utils import download_and_extract_archive, verify_str_arg
  7. from .vision import VisionDataset
  8. class CLEVRClassification(VisionDataset):
  9. """`CLEVR <https://cs.stanford.edu/people/jcjohns/clevr/>`_ classification dataset.
  10. The number of objects in a scene are used as label.
  11. Args:
  12. root (str or ``pathlib.Path``): Root directory of dataset where directory ``root/clevr`` exists or will be saved to if download is
  13. set to True.
  14. split (string, optional): The dataset split, supports ``"train"`` (default), ``"val"``, or ``"test"``.
  15. transform (callable, optional): A function/transform that takes in a PIL image or torch.Tensor, depends on the given loader,
  16. and returns a transformed version. E.g, ``transforms.RandomCrop``
  17. target_transform (callable, optional): A function/transform that takes in them target and transforms it.
  18. download (bool, optional): If true, downloads the dataset from the internet and puts it in root directory. If
  19. dataset is already downloaded, it is not downloaded again.
  20. loader (callable, optional): A function to load an image given its path.
  21. By default, it uses PIL as its image loader, but users could also pass in
  22. ``torchvision.io.decode_image`` for decoding image data into tensors directly.
  23. """
  24. _URL = "https://dl.fbaipublicfiles.com/clevr/CLEVR_v1.0.zip"
  25. _MD5 = "b11922020e72d0cd9154779b2d3d07d2"
  26. def __init__(
  27. self,
  28. root: Union[str, pathlib.Path],
  29. split: str = "train",
  30. transform: Optional[Callable] = None,
  31. target_transform: Optional[Callable] = None,
  32. download: bool = False,
  33. loader: Callable[[Union[str, pathlib.Path]], Any] = default_loader,
  34. ) -> None:
  35. self._split = verify_str_arg(split, "split", ("train", "val", "test"))
  36. super().__init__(root, transform=transform, target_transform=target_transform)
  37. self.loader = loader
  38. self._base_folder = pathlib.Path(self.root) / "clevr"
  39. self._data_folder = self._base_folder / pathlib.Path(urlparse(self._URL).path).stem
  40. if download:
  41. self._download()
  42. if not self._check_exists():
  43. raise RuntimeError("Dataset not found or corrupted. You can use download=True to download it")
  44. self._image_files = sorted(self._data_folder.joinpath("images", self._split).glob("*"))
  45. self._labels: List[Optional[int]]
  46. if self._split != "test":
  47. with open(self._data_folder / "scenes" / f"CLEVR_{self._split}_scenes.json") as file:
  48. content = json.load(file)
  49. num_objects = {scene["image_filename"]: len(scene["objects"]) for scene in content["scenes"]}
  50. self._labels = [num_objects[image_file.name] for image_file in self._image_files]
  51. else:
  52. self._labels = [None] * len(self._image_files)
  53. def __len__(self) -> int:
  54. return len(self._image_files)
  55. def __getitem__(self, idx: int) -> Tuple[Any, Any]:
  56. image_file = self._image_files[idx]
  57. label = self._labels[idx]
  58. image = self.loader(image_file)
  59. if self.transform:
  60. image = self.transform(image)
  61. if self.target_transform:
  62. label = self.target_transform(label)
  63. return image, label
  64. def _check_exists(self) -> bool:
  65. return self._data_folder.exists() and self._data_folder.is_dir()
  66. def _download(self) -> None:
  67. if self._check_exists():
  68. return
  69. download_and_extract_archive(self._URL, str(self._base_folder), md5=self._MD5)
  70. def extra_repr(self) -> str:
  71. return f"split={self._split}"
Tip!

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

Comments

Loading...