vision.py 4.31 KB
Newer Older
1
2
3
import os
import torch
import torch.utils.data as data
Philip Meier's avatar
Philip Meier committed
4
from typing import Any, Callable, List, Optional, Tuple
5
6
7


class VisionDataset(data.Dataset):
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
    """
    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.
    """
25
26
    _repr_indent = 4

Philip Meier's avatar
Philip Meier committed
27
28
29
30
31
32
33
    def __init__(
            self,
            root: str,
            transforms: Optional[Callable] = None,
            transform: Optional[Callable] = None,
            target_transform: Optional[Callable] = None,
    ) -> None:
34
        torch._C._log_api_usage_once(f"torchvision.datasets.{self.__class__.__name__}")
35
36
37
38
        if isinstance(root, torch._six.string_classes):
            root = os.path.expanduser(root)
        self.root = root

39
40
41
42
43
44
45
46
47
48
49
50
51
52
        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:
            raise ValueError("Only transforms or transform/target_transform can "
                             "be passed as argument")

        # 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
53
    def __getitem__(self, index: int) -> Any:
54
55
56
57
58
59
60
        """
        Args:
            index (int): Index

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

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

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

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

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


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

Philip Meier's avatar
Philip Meier committed
91
    def __call__(self, input: Any, target: Any) -> Tuple[Any, Any]:
92
93
94
95
96
97
        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
98
    def _format_transform_repr(self, transform: Callable, head: str) -> List[str]:
99
100
101
102
        lines = transform.__repr__().splitlines()
        return (["{}{}".format(head, lines[0])] +
                ["{}{}".format(" " * len(head), line) for line in lines[1:]])

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

        return '\n'.join(body)