We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Imagefolder none descriptive error message
## 🐛 Bug

You get an weird python error:
`TypeError: can only join an iterable`

If you make an Imagefolder dataset with no samples in the directory and a is_valid_file. Because the extensions variable is set to none because is_valid_file which causes the TypeError.

## To Reproduce

Steps to reproduce the behavior:

1. Use Imagefolder in torchvision.datasets with no samples in the directory and a is_valid_file function.


<!-- If you have a code sample, error messages, stack traces, please provide it here as well -->
```
 is_type = lambda x: x.startswith(name)
    print(dir_in)
    data_set = datasets.ImageFolder(root=dir_in,
                                    transform=transforms.Compose([transforms.CenterCrop(IMG_SIZE),
                                               # transforms.Resize(IMAGE_SIZE),
                                               transforms.ToTensor(),
                                               transforms.Normalize(0.5, 0.5)]),
                                    is_valid_file=is_type)
```

## Expected behavior

Should display an RunTimeError saying that no samples were found.

## Environment

Please copy and paste the output from our
[environment collection script](https://raw.githubusercontent.com/pytorch/pytorch/master/torch/utils/collect_env.py)
(or fill out the checklist below manually).
PyTorch version: 1.5.0
Is debug build: No
CUDA used to build PyTorch: 10.2

OS: Manjaro Linux
GCC version: (Arch Linux 9.3.0-1) 9.3.0
CMake version: version 3.17.1

Python version: 3.8
Is CUDA available: Yes
CUDA runtime version: 10.0.130
GPU models and configuration: GPU 0: Quadro M1200
Nvidia driver version: 440.82
cuDNN version: /usr/lib/libcudnn.so.7.6.5

Versions of relevant libraries:
[pip3] numpy==1.18.3
[pip3] torch==1.5.0
[pip3] torch-utils==0.1.2
[pip3] torchvision==0.5.0
[conda] Could not collect

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `torchvision/datasets/folder.py`
Content:
```
1 from .vision import VisionDataset
2 
3 from PIL import Image
4 
5 import os
6 import os.path
7 
8 
9 def has_file_allowed_extension(filename, extensions):
10     """Checks if a file is an allowed extension.
11 
12     Args:
13         filename (string): path to a file
14         extensions (tuple of strings): extensions to consider (lowercase)
15 
16     Returns:
17         bool: True if the filename ends with one of given extensions
18     """
19     return filename.lower().endswith(extensions)
20 
21 
22 def is_image_file(filename):
23     """Checks if a file is an allowed image extension.
24 
25     Args:
26         filename (string): path to a file
27 
28     Returns:
29         bool: True if the filename ends with a known image extension
30     """
31     return has_file_allowed_extension(filename, IMG_EXTENSIONS)
32 
33 
34 def make_dataset(directory, class_to_idx, extensions=None, is_valid_file=None):
35     instances = []
36     directory = os.path.expanduser(directory)
37     both_none = extensions is None and is_valid_file is None
38     both_something = extensions is not None and is_valid_file is not None
39     if both_none or both_something:
40         raise ValueError("Both extensions and is_valid_file cannot be None or not None at the same time")
41     if extensions is not None:
42         def is_valid_file(x):
43             return has_file_allowed_extension(x, extensions)
44     for target_class in sorted(class_to_idx.keys()):
45         class_index = class_to_idx[target_class]
46         target_dir = os.path.join(directory, target_class)
47         if not os.path.isdir(target_dir):
48             continue
49         for root, _, fnames in sorted(os.walk(target_dir, followlinks=True)):
50             for fname in sorted(fnames):
51                 path = os.path.join(root, fname)
52                 if is_valid_file(path):
53                     item = path, class_index
54                     instances.append(item)
55     return instances
56 
57 
58 class DatasetFolder(VisionDataset):
59     """A generic data loader where the samples are arranged in this way: ::
60 
61         root/class_x/xxx.ext
62         root/class_x/xxy.ext
63         root/class_x/xxz.ext
64 
65         root/class_y/123.ext
66         root/class_y/nsdf3.ext
67         root/class_y/asd932_.ext
68 
69     Args:
70         root (string): Root directory path.
71         loader (callable): A function to load a sample given its path.
72         extensions (tuple[string]): A list of allowed extensions.
73             both extensions and is_valid_file should not be passed.
74         transform (callable, optional): A function/transform that takes in
75             a sample and returns a transformed version.
76             E.g, ``transforms.RandomCrop`` for images.
77         target_transform (callable, optional): A function/transform that takes
78             in the target and transforms it.
79         is_valid_file (callable, optional): A function that takes path of a file
80             and check if the file is a valid file (used to check of corrupt files)
81             both extensions and is_valid_file should not be passed.
82 
83      Attributes:
84         classes (list): List of the class names sorted alphabetically.
85         class_to_idx (dict): Dict with items (class_name, class_index).
86         samples (list): List of (sample path, class_index) tuples
87         targets (list): The class_index value for each image in the dataset
88     """
89 
90     def __init__(self, root, loader, extensions=None, transform=None,
91                  target_transform=None, is_valid_file=None):
92         super(DatasetFolder, self).__init__(root, transform=transform,
93                                             target_transform=target_transform)
94         classes, class_to_idx = self._find_classes(self.root)
95         samples = make_dataset(self.root, class_to_idx, extensions, is_valid_file)
96         if len(samples) == 0:
97             raise (RuntimeError("Found 0 files in subfolders of: " + self.root + "\n"
98                                 "Supported extensions are: " + ",".join(extensions)))
99 
100         self.loader = loader
101         self.extensions = extensions
102 
103         self.classes = classes
104         self.class_to_idx = class_to_idx
105         self.samples = samples
106         self.targets = [s[1] for s in samples]
107 
108     def _find_classes(self, dir):
109         """
110         Finds the class folders in a dataset.
111 
112         Args:
113             dir (string): Root directory path.
114 
115         Returns:
116             tuple: (classes, class_to_idx) where classes are relative to (dir), and class_to_idx is a dictionary.
117 
118         Ensures:
119             No class is a subdirectory of another.
120         """
121         classes = [d.name for d in os.scandir(dir) if d.is_dir()]
122         classes.sort()
123         class_to_idx = {classes[i]: i for i in range(len(classes))}
124         return classes, class_to_idx
125 
126     def __getitem__(self, index):
127         """
128         Args:
129             index (int): Index
130 
131         Returns:
132             tuple: (sample, target) where target is class_index of the target class.
133         """
134         path, target = self.samples[index]
135         sample = self.loader(path)
136         if self.transform is not None:
137             sample = self.transform(sample)
138         if self.target_transform is not None:
139             target = self.target_transform(target)
140 
141         return sample, target
142 
143     def __len__(self):
144         return len(self.samples)
145 
146 
147 IMG_EXTENSIONS = ('.jpg', '.jpeg', '.png', '.ppm', '.bmp', '.pgm', '.tif', '.tiff', '.webp')
148 
149 
150 def pil_loader(path):
151     # open path as file to avoid ResourceWarning (https://github.com/python-pillow/Pillow/issues/835)
152     with open(path, 'rb') as f:
153         img = Image.open(f)
154         return img.convert('RGB')
155 
156 
157 def accimage_loader(path):
158     import accimage
159     try:
160         return accimage.Image(path)
161     except IOError:
162         # Potentially a decoding problem, fall back to PIL.Image
163         return pil_loader(path)
164 
165 
166 def default_loader(path):
167     from torchvision import get_image_backend
168     if get_image_backend() == 'accimage':
169         return accimage_loader(path)
170     else:
171         return pil_loader(path)
172 
173 
174 class ImageFolder(DatasetFolder):
175     """A generic data loader where the images are arranged in this way: ::
176 
177         root/dog/xxx.png
178         root/dog/xxy.png
179         root/dog/xxz.png
180 
181         root/cat/123.png
182         root/cat/nsdf3.png
183         root/cat/asd932_.png
184 
185     Args:
186         root (string): Root directory path.
187         transform (callable, optional): A function/transform that  takes in an PIL image
188             and returns a transformed version. E.g, ``transforms.RandomCrop``
189         target_transform (callable, optional): A function/transform that takes in the
190             target and transforms it.
191         loader (callable, optional): A function to load an image given its path.
192         is_valid_file (callable, optional): A function that takes path of an Image file
193             and check if the file is a valid file (used to check of corrupt files)
194 
195      Attributes:
196         classes (list): List of the class names sorted alphabetically.
197         class_to_idx (dict): Dict with items (class_name, class_index).
198         imgs (list): List of (image path, class_index) tuples
199     """
200 
201     def __init__(self, root, transform=None, target_transform=None,
202                  loader=default_loader, is_valid_file=None):
203         super(ImageFolder, self).__init__(root, loader, IMG_EXTENSIONS if is_valid_file is None else None,
204                                           transform=transform,
205                                           target_transform=target_transform,
206                                           is_valid_file=is_valid_file)
207         self.imgs = self.samples
208
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/torchvision/datasets/folder.py b/torchvision/datasets/folder.py
--- a/torchvision/datasets/folder.py
+++ b/torchvision/datasets/folder.py
@@ -94,8 +94,10 @@
         classes, class_to_idx = self._find_classes(self.root)
         samples = make_dataset(self.root, class_to_idx, extensions, is_valid_file)
         if len(samples) == 0:
-            raise (RuntimeError("Found 0 files in subfolders of: " + self.root + "\n"
-                                "Supported extensions are: " + ",".join(extensions)))
+            msg = "Found 0 files in subfolders of: {}\n".format(self.root)
+            if extensions is not None:
+                msg += "Supported extensions are: {}".format(",".join(extensions))
+            raise RuntimeError(msg)
 
         self.loader = loader
         self.extensions = extensions

{"golden_diff": "diff --git a/torchvision/datasets/folder.py b/torchvision/datasets/folder.py\n--- a/torchvision/datasets/folder.py\n+++ b/torchvision/datasets/folder.py\n@@ -94,8 +94,10 @@\n         classes, class_to_idx = self._find_classes(self.root)\n         samples = make_dataset(self.root, class_to_idx, extensions, is_valid_file)\n         if len(samples) == 0:\n-            raise (RuntimeError(\"Found 0 files in subfolders of: \" + self.root + \"\\n\"\n-                                \"Supported extensions are: \" + \",\".join(extensions)))\n+            msg = \"Found 0 files in subfolders of: {}\\n\".format(self.root)\n+            if extensions is not None:\n+                msg += \"Supported extensions are: {}\".format(\",\".join(extensions))\n+            raise RuntimeError(msg)\n \n         self.loader = loader\n         self.extensions = extensions\n", "issue": "Imagefolder none descriptive error message\n## \ud83d\udc1b Bug\r\n\r\nYou get an weird python error:\r\n`TypeError: can only join an iterable`\r\n\r\nIf you make an Imagefolder dataset with no samples in the directory and a is_valid_file. Because the extensions variable is set to none because is_valid_file which causes the TypeError.\r\n\r\n## To Reproduce\r\n\r\nSteps to reproduce the behavior:\r\n\r\n1. Use Imagefolder in torchvision.datasets with no samples in the directory and a is_valid_file function.\r\n\r\n\r\n<!-- If you have a code sample, error messages, stack traces, please provide it here as well -->\r\n```\r\n is_type = lambda x: x.startswith(name)\r\n    print(dir_in)\r\n    data_set = datasets.ImageFolder(root=dir_in,\r\n                                    transform=transforms.Compose([transforms.CenterCrop(IMG_SIZE),\r\n                                               # transforms.Resize(IMAGE_SIZE),\r\n                                               transforms.ToTensor(),\r\n                                               transforms.Normalize(0.5, 0.5)]),\r\n                                    is_valid_file=is_type)\r\n```\r\n\r\n## Expected behavior\r\n\r\nShould display an RunTimeError saying that no samples were found.\r\n\r\n## Environment\r\n\r\nPlease copy and paste the output from our\r\n[environment collection script](https://raw.githubusercontent.com/pytorch/pytorch/master/torch/utils/collect_env.py)\r\n(or fill out the checklist below manually).\r\nPyTorch version: 1.5.0\r\nIs debug build: No\r\nCUDA used to build PyTorch: 10.2\r\n\r\nOS: Manjaro Linux\r\nGCC version: (Arch Linux 9.3.0-1) 9.3.0\r\nCMake version: version 3.17.1\r\n\r\nPython version: 3.8\r\nIs CUDA available: Yes\r\nCUDA runtime version: 10.0.130\r\nGPU models and configuration: GPU 0: Quadro M1200\r\nNvidia driver version: 440.82\r\ncuDNN version: /usr/lib/libcudnn.so.7.6.5\r\n\r\nVersions of relevant libraries:\r\n[pip3] numpy==1.18.3\r\n[pip3] torch==1.5.0\r\n[pip3] torch-utils==0.1.2\r\n[pip3] torchvision==0.5.0\r\n[conda] Could not collect\n", "before_files": [{"content": "from .vision import VisionDataset\n\nfrom PIL import Image\n\nimport os\nimport os.path\n\n\ndef has_file_allowed_extension(filename, extensions):\n    \"\"\"Checks if a file is an allowed extension.\n\n    Args:\n        filename (string): path to a file\n        extensions (tuple of strings): extensions to consider (lowercase)\n\n    Returns:\n        bool: True if the filename ends with one of given extensions\n    \"\"\"\n    return filename.lower().endswith(extensions)\n\n\ndef is_image_file(filename):\n    \"\"\"Checks if a file is an allowed image extension.\n\n    Args:\n        filename (string): path to a file\n\n    Returns:\n        bool: True if the filename ends with a known image extension\n    \"\"\"\n    return has_file_allowed_extension(filename, IMG_EXTENSIONS)\n\n\ndef make_dataset(directory, class_to_idx, extensions=None, is_valid_file=None):\n    instances = []\n    directory = os.path.expanduser(directory)\n    both_none = extensions is None and is_valid_file is None\n    both_something = extensions is not None and is_valid_file is not None\n    if both_none or both_something:\n        raise ValueError(\"Both extensions and is_valid_file cannot be None or not None at the same time\")\n    if extensions is not None:\n        def is_valid_file(x):\n            return has_file_allowed_extension(x, extensions)\n    for target_class in sorted(class_to_idx.keys()):\n        class_index = class_to_idx[target_class]\n        target_dir = os.path.join(directory, target_class)\n        if not os.path.isdir(target_dir):\n            continue\n        for root, _, fnames in sorted(os.walk(target_dir, followlinks=True)):\n            for fname in sorted(fnames):\n                path = os.path.join(root, fname)\n                if is_valid_file(path):\n                    item = path, class_index\n                    instances.append(item)\n    return instances\n\n\nclass DatasetFolder(VisionDataset):\n    \"\"\"A generic data loader where the samples are arranged in this way: ::\n\n        root/class_x/xxx.ext\n        root/class_x/xxy.ext\n        root/class_x/xxz.ext\n\n        root/class_y/123.ext\n        root/class_y/nsdf3.ext\n        root/class_y/asd932_.ext\n\n    Args:\n        root (string): Root directory path.\n        loader (callable): A function to load a sample given its path.\n        extensions (tuple[string]): A list of allowed extensions.\n            both extensions and is_valid_file should not be passed.\n        transform (callable, optional): A function/transform that takes in\n            a sample and returns a transformed version.\n            E.g, ``transforms.RandomCrop`` for images.\n        target_transform (callable, optional): A function/transform that takes\n            in the target and transforms it.\n        is_valid_file (callable, optional): A function that takes path of a file\n            and check if the file is a valid file (used to check of corrupt files)\n            both extensions and is_valid_file should not be passed.\n\n     Attributes:\n        classes (list): List of the class names sorted alphabetically.\n        class_to_idx (dict): Dict with items (class_name, class_index).\n        samples (list): List of (sample path, class_index) tuples\n        targets (list): The class_index value for each image in the dataset\n    \"\"\"\n\n    def __init__(self, root, loader, extensions=None, transform=None,\n                 target_transform=None, is_valid_file=None):\n        super(DatasetFolder, self).__init__(root, transform=transform,\n                                            target_transform=target_transform)\n        classes, class_to_idx = self._find_classes(self.root)\n        samples = make_dataset(self.root, class_to_idx, extensions, is_valid_file)\n        if len(samples) == 0:\n            raise (RuntimeError(\"Found 0 files in subfolders of: \" + self.root + \"\\n\"\n                                \"Supported extensions are: \" + \",\".join(extensions)))\n\n        self.loader = loader\n        self.extensions = extensions\n\n        self.classes = classes\n        self.class_to_idx = class_to_idx\n        self.samples = samples\n        self.targets = [s[1] for s in samples]\n\n    def _find_classes(self, dir):\n        \"\"\"\n        Finds the class folders in a dataset.\n\n        Args:\n            dir (string): Root directory path.\n\n        Returns:\n            tuple: (classes, class_to_idx) where classes are relative to (dir), and class_to_idx is a dictionary.\n\n        Ensures:\n            No class is a subdirectory of another.\n        \"\"\"\n        classes = [d.name for d in os.scandir(dir) if d.is_dir()]\n        classes.sort()\n        class_to_idx = {classes[i]: i for i in range(len(classes))}\n        return classes, class_to_idx\n\n    def __getitem__(self, index):\n        \"\"\"\n        Args:\n            index (int): Index\n\n        Returns:\n            tuple: (sample, target) where target is class_index of the target class.\n        \"\"\"\n        path, target = self.samples[index]\n        sample = self.loader(path)\n        if self.transform is not None:\n            sample = self.transform(sample)\n        if self.target_transform is not None:\n            target = self.target_transform(target)\n\n        return sample, target\n\n    def __len__(self):\n        return len(self.samples)\n\n\nIMG_EXTENSIONS = ('.jpg', '.jpeg', '.png', '.ppm', '.bmp', '.pgm', '.tif', '.tiff', '.webp')\n\n\ndef pil_loader(path):\n    # open path as file to avoid ResourceWarning (https://github.com/python-pillow/Pillow/issues/835)\n    with open(path, 'rb') as f:\n        img = Image.open(f)\n        return img.convert('RGB')\n\n\ndef accimage_loader(path):\n    import accimage\n    try:\n        return accimage.Image(path)\n    except IOError:\n        # Potentially a decoding problem, fall back to PIL.Image\n        return pil_loader(path)\n\n\ndef default_loader(path):\n    from torchvision import get_image_backend\n    if get_image_backend() == 'accimage':\n        return accimage_loader(path)\n    else:\n        return pil_loader(path)\n\n\nclass ImageFolder(DatasetFolder):\n    \"\"\"A generic data loader where the images are arranged in this way: ::\n\n        root/dog/xxx.png\n        root/dog/xxy.png\n        root/dog/xxz.png\n\n        root/cat/123.png\n        root/cat/nsdf3.png\n        root/cat/asd932_.png\n\n    Args:\n        root (string): Root directory path.\n        transform (callable, optional): A function/transform that  takes in an PIL image\n            and returns a transformed version. E.g, ``transforms.RandomCrop``\n        target_transform (callable, optional): A function/transform that takes in the\n            target and transforms it.\n        loader (callable, optional): A function to load an image given its path.\n        is_valid_file (callable, optional): A function that takes path of an Image file\n            and check if the file is a valid file (used to check of corrupt files)\n\n     Attributes:\n        classes (list): List of the class names sorted alphabetically.\n        class_to_idx (dict): Dict with items (class_name, class_index).\n        imgs (list): List of (image path, class_index) tuples\n    \"\"\"\n\n    def __init__(self, root, transform=None, target_transform=None,\n                 loader=default_loader, is_valid_file=None):\n        super(ImageFolder, self).__init__(root, loader, IMG_EXTENSIONS if is_valid_file is None else None,\n                                          transform=transform,\n                                          target_transform=target_transform,\n                                          is_valid_file=is_valid_file)\n        self.imgs = self.samples\n", "path": "torchvision/datasets/folder.py"}], "after_files": [{"content": "from .vision import VisionDataset\n\nfrom PIL import Image\n\nimport os\nimport os.path\n\n\ndef has_file_allowed_extension(filename, extensions):\n    \"\"\"Checks if a file is an allowed extension.\n\n    Args:\n        filename (string): path to a file\n        extensions (tuple of strings): extensions to consider (lowercase)\n\n    Returns:\n        bool: True if the filename ends with one of given extensions\n    \"\"\"\n    return filename.lower().endswith(extensions)\n\n\ndef is_image_file(filename):\n    \"\"\"Checks if a file is an allowed image extension.\n\n    Args:\n        filename (string): path to a file\n\n    Returns:\n        bool: True if the filename ends with a known image extension\n    \"\"\"\n    return has_file_allowed_extension(filename, IMG_EXTENSIONS)\n\n\ndef make_dataset(directory, class_to_idx, extensions=None, is_valid_file=None):\n    instances = []\n    directory = os.path.expanduser(directory)\n    both_none = extensions is None and is_valid_file is None\n    both_something = extensions is not None and is_valid_file is not None\n    if both_none or both_something:\n        raise ValueError(\"Both extensions and is_valid_file cannot be None or not None at the same time\")\n    if extensions is not None:\n        def is_valid_file(x):\n            return has_file_allowed_extension(x, extensions)\n    for target_class in sorted(class_to_idx.keys()):\n        class_index = class_to_idx[target_class]\n        target_dir = os.path.join(directory, target_class)\n        if not os.path.isdir(target_dir):\n            continue\n        for root, _, fnames in sorted(os.walk(target_dir, followlinks=True)):\n            for fname in sorted(fnames):\n                path = os.path.join(root, fname)\n                if is_valid_file(path):\n                    item = path, class_index\n                    instances.append(item)\n    return instances\n\n\nclass DatasetFolder(VisionDataset):\n    \"\"\"A generic data loader where the samples are arranged in this way: ::\n\n        root/class_x/xxx.ext\n        root/class_x/xxy.ext\n        root/class_x/xxz.ext\n\n        root/class_y/123.ext\n        root/class_y/nsdf3.ext\n        root/class_y/asd932_.ext\n\n    Args:\n        root (string): Root directory path.\n        loader (callable): A function to load a sample given its path.\n        extensions (tuple[string]): A list of allowed extensions.\n            both extensions and is_valid_file should not be passed.\n        transform (callable, optional): A function/transform that takes in\n            a sample and returns a transformed version.\n            E.g, ``transforms.RandomCrop`` for images.\n        target_transform (callable, optional): A function/transform that takes\n            in the target and transforms it.\n        is_valid_file (callable, optional): A function that takes path of a file\n            and check if the file is a valid file (used to check of corrupt files)\n            both extensions and is_valid_file should not be passed.\n\n     Attributes:\n        classes (list): List of the class names sorted alphabetically.\n        class_to_idx (dict): Dict with items (class_name, class_index).\n        samples (list): List of (sample path, class_index) tuples\n        targets (list): The class_index value for each image in the dataset\n    \"\"\"\n\n    def __init__(self, root, loader, extensions=None, transform=None,\n                 target_transform=None, is_valid_file=None):\n        super(DatasetFolder, self).__init__(root, transform=transform,\n                                            target_transform=target_transform)\n        classes, class_to_idx = self._find_classes(self.root)\n        samples = make_dataset(self.root, class_to_idx, extensions, is_valid_file)\n        if len(samples) == 0:\n            msg = \"Found 0 files in subfolders of: {}\\n\".format(self.root)\n            if extensions is not None:\n                msg += \"Supported extensions are: {}\".format(\",\".join(extensions))\n            raise RuntimeError(msg)\n\n        self.loader = loader\n        self.extensions = extensions\n\n        self.classes = classes\n        self.class_to_idx = class_to_idx\n        self.samples = samples\n        self.targets = [s[1] for s in samples]\n\n    def _find_classes(self, dir):\n        \"\"\"\n        Finds the class folders in a dataset.\n\n        Args:\n            dir (string): Root directory path.\n\n        Returns:\n            tuple: (classes, class_to_idx) where classes are relative to (dir), and class_to_idx is a dictionary.\n\n        Ensures:\n            No class is a subdirectory of another.\n        \"\"\"\n        classes = [d.name for d in os.scandir(dir) if d.is_dir()]\n        classes.sort()\n        class_to_idx = {classes[i]: i for i in range(len(classes))}\n        return classes, class_to_idx\n\n    def __getitem__(self, index):\n        \"\"\"\n        Args:\n            index (int): Index\n\n        Returns:\n            tuple: (sample, target) where target is class_index of the target class.\n        \"\"\"\n        path, target = self.samples[index]\n        sample = self.loader(path)\n        if self.transform is not None:\n            sample = self.transform(sample)\n        if self.target_transform is not None:\n            target = self.target_transform(target)\n\n        return sample, target\n\n    def __len__(self):\n        return len(self.samples)\n\n\nIMG_EXTENSIONS = ('.jpg', '.jpeg', '.png', '.ppm', '.bmp', '.pgm', '.tif', '.tiff', '.webp')\n\n\ndef pil_loader(path):\n    # open path as file to avoid ResourceWarning (https://github.com/python-pillow/Pillow/issues/835)\n    with open(path, 'rb') as f:\n        img = Image.open(f)\n        return img.convert('RGB')\n\n\ndef accimage_loader(path):\n    import accimage\n    try:\n        return accimage.Image(path)\n    except IOError:\n        # Potentially a decoding problem, fall back to PIL.Image\n        return pil_loader(path)\n\n\ndef default_loader(path):\n    from torchvision import get_image_backend\n    if get_image_backend() == 'accimage':\n        return accimage_loader(path)\n    else:\n        return pil_loader(path)\n\n\nclass ImageFolder(DatasetFolder):\n    \"\"\"A generic data loader where the images are arranged in this way: ::\n\n        root/dog/xxx.png\n        root/dog/xxy.png\n        root/dog/xxz.png\n\n        root/cat/123.png\n        root/cat/nsdf3.png\n        root/cat/asd932_.png\n\n    Args:\n        root (string): Root directory path.\n        transform (callable, optional): A function/transform that  takes in an PIL image\n            and returns a transformed version. E.g, ``transforms.RandomCrop``\n        target_transform (callable, optional): A function/transform that takes in the\n            target and transforms it.\n        loader (callable, optional): A function to load an image given its path.\n        is_valid_file (callable, optional): A function that takes path of an Image file\n            and check if the file is a valid file (used to check of corrupt files)\n\n     Attributes:\n        classes (list): List of the class names sorted alphabetically.\n        class_to_idx (dict): Dict with items (class_name, class_index).\n        imgs (list): List of (image path, class_index) tuples\n    \"\"\"\n\n    def __init__(self, root, transform=None, target_transform=None,\n                 loader=default_loader, is_valid_file=None):\n        super(ImageFolder, self).__init__(root, loader, IMG_EXTENSIONS if is_valid_file is None else None,\n                                          transform=transform,\n                                          target_transform=target_transform,\n                                          is_valid_file=is_valid_file)\n        self.imgs = self.samples\n", "path": "torchvision/datasets/folder.py"}]}