vision.py 4.04 KB
Newer Older
1
import os
2
3
from typing import Any, Callable, List, Optional, Tuple

4
5
import torch.utils.data as data

6
7
from ..utils import _log_api_usage_once

8
9

class VisionDataset(data.Dataset):
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
    """
    Base Class For making datasets which are compatible with torchvision.
    It is necessary to override the ``__getitem__`` and ``__len__`` method.

    Args:
        root (string): Root directory of dataset.
        transforms (callable, optional): A function/transforms that takes in
            an image and a label and returns the transformed versions of both.
        transform (callable, optional): A function/transform that  takes in an PIL image
            and returns a transformed version. E.g, ``transforms.RandomCrop``
        target_transform (callable, optional): A function/transform that takes in the
            target and transforms it.

    .. note::

        :attr:`transforms` and the combination of :attr:`transform` and :attr:`target_transform` are mutually exclusive.
    """
27

28
29
    _repr_indent = 4

Philip Meier's avatar
Philip Meier committed
30
    def __init__(
31
32
33
34
35
        self,
        root: str,
        transforms: Optional[Callable] = None,
        transform: Optional[Callable] = None,
        target_transform: Optional[Callable] = None,
Philip Meier's avatar
Philip Meier committed
36
    ) -> None:
Kai Zhang's avatar
Kai Zhang committed
37
        _log_api_usage_once(self)
38
        if isinstance(root, str):
39
40
41
            root = os.path.expanduser(root)
        self.root = root

42
43
44
        has_transforms = transforms is not None
        has_separate_transform = transform is not None or target_transform is not None
        if has_transforms and has_separate_transform:
45
            raise ValueError("Only transforms or transform/target_transform can be passed as argument")
46
47
48
49
50
51
52
53
54

        # for backwards-compatibility
        self.transform = transform
        self.target_transform = target_transform

        if has_separate_transform:
            transforms = StandardTransform(transform, target_transform)
        self.transforms = transforms

Philip Meier's avatar
Philip Meier committed
55
    def __getitem__(self, index: int) -> Any:
56
57
58
59
60
61
62
        """
        Args:
            index (int): Index

        Returns:
            (Any): Sample and meta data, optionally transformed by the respective transforms.
        """
63
64
        raise NotImplementedError

Philip Meier's avatar
Philip Meier committed
65
    def __len__(self) -> int:
66
67
        raise NotImplementedError

Philip Meier's avatar
Philip Meier committed
68
    def __repr__(self) -> str:
69
        head = "Dataset " + self.__class__.__name__
70
        body = [f"Number of datapoints: {self.__len__()}"]
71
        if self.root is not None:
72
            body.append(f"Root location: {self.root}")
73
        body += self.extra_repr().splitlines()
Francisco Massa's avatar
Francisco Massa committed
74
        if hasattr(self, "transforms") and self.transforms is not None:
75
            body += [repr(self.transforms)]
76
        lines = [head] + [" " * self._repr_indent + line for line in body]
77
        return "\n".join(lines)
78

Philip Meier's avatar
Philip Meier committed
79
    def _format_transform_repr(self, transform: Callable, head: str) -> List[str]:
80
        lines = transform.__repr__().splitlines()
81
        return [f"{head}{lines[0]}"] + ["{}{}".format(" " * len(head), line) for line in lines[1:]]
82

Philip Meier's avatar
Philip Meier committed
83
    def extra_repr(self) -> str:
84
        return ""
85
86


87
class StandardTransform:
Philip Meier's avatar
Philip Meier committed
88
    def __init__(self, transform: Optional[Callable] = None, target_transform: Optional[Callable] = None) -> None:
89
90
91
        self.transform = transform
        self.target_transform = target_transform

Philip Meier's avatar
Philip Meier committed
92
    def __call__(self, input: Any, target: Any) -> Tuple[Any, Any]:
93
94
95
96
97
98
        if self.transform is not None:
            input = self.transform(input)
        if self.target_transform is not None:
            target = self.target_transform(target)
        return input, target

Philip Meier's avatar
Philip Meier committed
99
    def _format_transform_repr(self, transform: Callable, head: str) -> List[str]:
100
        lines = transform.__repr__().splitlines()
101
        return [f"{head}{lines[0]}"] + ["{}{}".format(" " * len(head), line) for line in lines[1:]]
102

Philip Meier's avatar
Philip Meier committed
103
    def __repr__(self) -> str:
104
105
        body = [self.__class__.__name__]
        if self.transform is not None:
106
            body += self._format_transform_repr(self.transform, "Transform: ")
107
        if self.target_transform is not None:
108
            body += self._format_transform_repr(self.target_transform, "Target transform: ")
109

110
        return "\n".join(body)