fakedata.py 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. from typing import Any, Callable, Optional, Tuple
  2. import torch
  3. from .. import transforms
  4. from .vision import VisionDataset
  5. class FakeData(VisionDataset):
  6. """A fake dataset that returns randomly generated images and returns them as PIL images
  7. Args:
  8. size (int, optional): Size of the dataset. Default: 1000 images
  9. image_size(tuple, optional): Size if the returned images. Default: (3, 224, 224)
  10. num_classes(int, optional): Number of classes in the dataset. Default: 10
  11. transform (callable, optional): A function/transform that takes in an PIL image
  12. and returns a transformed version. E.g, ``transforms.RandomCrop``
  13. target_transform (callable, optional): A function/transform that takes in the
  14. target and transforms it.
  15. random_offset (int): Offsets the index-based random seed used to
  16. generate each image. Default: 0
  17. """
  18. def __init__(
  19. self,
  20. size: int = 1000,
  21. image_size: Tuple[int, int, int] = (3, 224, 224),
  22. num_classes: int = 10,
  23. transform: Optional[Callable] = None,
  24. target_transform: Optional[Callable] = None,
  25. random_offset: int = 0,
  26. ) -> None:
  27. super().__init__(None, transform=transform, target_transform=target_transform) # type: ignore[arg-type]
  28. self.size = size
  29. self.num_classes = num_classes
  30. self.image_size = image_size
  31. self.random_offset = random_offset
  32. def __getitem__(self, index: int) -> Tuple[Any, Any]:
  33. """
  34. Args:
  35. index (int): Index
  36. Returns:
  37. tuple: (image, target) where target is class_index of the target class.
  38. """
  39. # create random image that is consistent with the index id
  40. if index >= len(self):
  41. raise IndexError(f"{self.__class__.__name__} index out of range")
  42. rng_state = torch.get_rng_state()
  43. torch.manual_seed(index + self.random_offset)
  44. img = torch.randn(*self.image_size)
  45. target = torch.randint(0, self.num_classes, size=(1,), dtype=torch.long)[0]
  46. torch.set_rng_state(rng_state)
  47. # convert to PIL Image
  48. img = transforms.ToPILImage()(img)
  49. if self.transform is not None:
  50. img = self.transform(img)
  51. if self.target_transform is not None:
  52. target = self.target_transform(target)
  53. return img, target.item()
  54. def __len__(self) -> int:
  55. return self.size