rendered_sst2.py 3.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. from pathlib import Path
  2. from typing import Any, Callable, Optional, Tuple
  3. import PIL.Image
  4. from .folder import make_dataset
  5. from .utils import download_and_extract_archive, verify_str_arg
  6. from .vision import VisionDataset
  7. class RenderedSST2(VisionDataset):
  8. """`The Rendered SST2 Dataset <https://github.com/openai/CLIP/blob/main/data/rendered-sst2.md>`_.
  9. Rendered SST2 is an image classification dataset used to evaluate the models capability on optical
  10. character recognition. This dataset was generated by rendering sentences in the Standford Sentiment
  11. Treebank v2 dataset.
  12. This dataset contains two classes (positive and negative) and is divided in three splits: a train
  13. split containing 6920 images (3610 positive and 3310 negative), a validation split containing 872 images
  14. (444 positive and 428 negative), and a test split containing 1821 images (909 positive and 912 negative).
  15. Args:
  16. root (string): Root directory of the dataset.
  17. split (string, optional): The dataset split, supports ``"train"`` (default), `"val"` and ``"test"``.
  18. transform (callable, optional): A function/transform that takes in an PIL image and returns a transformed
  19. version. E.g, ``transforms.RandomCrop``.
  20. target_transform (callable, optional): A function/transform that takes in the 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. Default is False.
  24. """
  25. _URL = "https://openaipublic.azureedge.net/clip/data/rendered-sst2.tgz"
  26. _MD5 = "2384d08e9dcfa4bd55b324e610496ee5"
  27. def __init__(
  28. self,
  29. root: str,
  30. split: str = "train",
  31. transform: Optional[Callable] = None,
  32. target_transform: Optional[Callable] = None,
  33. download: bool = False,
  34. ) -> None:
  35. super().__init__(root, transform=transform, target_transform=target_transform)
  36. self._split = verify_str_arg(split, "split", ("train", "val", "test"))
  37. self._split_to_folder = {"train": "train", "val": "valid", "test": "test"}
  38. self._base_folder = Path(self.root) / "rendered-sst2"
  39. self.classes = ["negative", "positive"]
  40. self.class_to_idx = {"negative": 0, "positive": 1}
  41. if download:
  42. self._download()
  43. if not self._check_exists():
  44. raise RuntimeError("Dataset not found. You can use download=True to download it")
  45. self._samples = make_dataset(str(self._base_folder / self._split_to_folder[self._split]), extensions=("png",))
  46. def __len__(self) -> int:
  47. return len(self._samples)
  48. def __getitem__(self, idx: int) -> Tuple[Any, Any]:
  49. image_file, label = self._samples[idx]
  50. image = PIL.Image.open(image_file).convert("RGB")
  51. if self.transform:
  52. image = self.transform(image)
  53. if self.target_transform:
  54. label = self.target_transform(label)
  55. return image, label
  56. def extra_repr(self) -> str:
  57. return f"split={self._split}"
  58. def _check_exists(self) -> bool:
  59. for class_label in set(self.classes):
  60. if not (self._base_folder / self._split_to_folder[self._split] / class_label).is_dir():
  61. return False
  62. return True
  63. def _download(self) -> None:
  64. if self._check_exists():
  65. return
  66. download_and_extract_archive(self._URL, download_root=self.root, md5=self._MD5)