Skip to content

Commit e6c3161

Browse files
committed
Automated tutorials push
1 parent fca5998 commit e6c3161

File tree

179 files changed

+487986
-494175
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

179 files changed

+487986
-494175
lines changed

_downloads/6042bacf7948939030769777afe22e55/data_loading_tutorial.py

Lines changed: 21 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -124,7 +124,7 @@ class FaceLandmarksDataset(Dataset):
124124

125125
def __init__(self, csv_file, root_dir, transform=None):
126126
"""
127-
Args:
127+
Arguments:
128128
csv_file (string): Path to the csv file with annotations.
129129
root_dir (string): Directory with all the images.
130130
transform (callable, optional): Optional transform to be applied
@@ -197,7 +197,7 @@ def __getitem__(self, idx):
197197
# swap axes).
198198
#
199199
# We will write them as callable classes instead of simple functions so
200-
# that parameters of the transform need not be passed everytime it's
200+
# that parameters of the transform need not be passed every time it's
201201
# called. For this, we just need to implement ``__call__`` method and
202202
# if required, ``__init__`` method. We can then use a transform like this:
203203
#
@@ -291,12 +291,12 @@ def __call__(self, sample):
291291
image = image.transpose((2, 0, 1))
292292
return {'image': torch.from_numpy(image),
293293
'landmarks': torch.from_numpy(landmarks)}
294-
294+
295295
######################################################################
296296
# .. note::
297297
# In the example above, `RandomCrop` uses an external library's random number generator
298-
# (in this case, Numpy's `np.random.int`). This can result in unexpected behavior with `DataLoader`
299-
# (see https://pytorch.org/docs/stable/notes/faq.html#my-data-loader-workers-return-identical-random-numbers).
298+
# (in this case, Numpy's `np.random.int`). This can result in unexpected behavior with `DataLoader`
299+
# (see `here <https://pytorch.org/docs/stable/notes/faq.html#my-data-loader-workers-return-identical-random-numbers>`_).
300300
# In practice, it is safer to stick to PyTorch's random number generator, e.g. by using `torch.randint` instead.
301301

302302
######################################################################
@@ -404,7 +404,7 @@ def show_landmarks_batch(sample_batched):
404404
plt.title('Batch from dataloader')
405405

406406
# if you are using Windows, uncomment the next line and indent the for loop.
407-
# you might need to go back and change "num_workers" to 0.
407+
# you might need to go back and change ``num_workers`` to 0.
408408

409409
# if __name__ == '__main__':
410410
for i_batch, sample_batched in enumerate(dataloader):
@@ -444,21 +444,21 @@ def show_landmarks_batch(sample_batched):
444444
# which operate on ``PIL.Image`` like ``RandomHorizontalFlip``, ``Scale``,
445445
# are also available. You can use these to write a dataloader like this: ::
446446
#
447-
# import torch
448-
# from torchvision import transforms, datasets
449-
#
450-
# data_transform = transforms.Compose([
451-
# transforms.RandomSizedCrop(224),
452-
# transforms.RandomHorizontalFlip(),
453-
# transforms.ToTensor(),
454-
# transforms.Normalize(mean=[0.485, 0.456, 0.406],
455-
# std=[0.229, 0.224, 0.225])
456-
# ])
457-
# hymenoptera_dataset = datasets.ImageFolder(root='hymenoptera_data/train',
458-
# transform=data_transform)
459-
# dataset_loader = torch.utils.data.DataLoader(hymenoptera_dataset,
460-
# batch_size=4, shuffle=True,
461-
# num_workers=4)
447+
# import torch
448+
# from torchvision import transforms, datasets
449+
#
450+
# data_transform = transforms.Compose([
451+
# transforms.RandomSizedCrop(224),
452+
# transforms.RandomHorizontalFlip(),
453+
# transforms.ToTensor(),
454+
# transforms.Normalize(mean=[0.485, 0.456, 0.406],
455+
# std=[0.229, 0.224, 0.225])
456+
# ])
457+
# hymenoptera_dataset = datasets.ImageFolder(root='hymenoptera_data/train',
458+
# transform=data_transform)
459+
# dataset_loader = torch.utils.data.DataLoader(hymenoptera_dataset,
460+
# batch_size=4, shuffle=True,
461+
# num_workers=4)
462462
#
463463
# For an example with training code, please see
464464
# :doc:`transfer_learning_tutorial`.

_downloads/f498e3bcd9b6159ecfb1a07d6551287d/data_loading_tutorial.ipynb

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -80,7 +80,7 @@
8080
},
8181
"outputs": [],
8282
"source": [
83-
"class FaceLandmarksDataset(Dataset):\n \"\"\"Face Landmarks dataset.\"\"\"\n\n def __init__(self, csv_file, root_dir, transform=None):\n \"\"\"\n Args:\n csv_file (string): Path to the csv file with annotations.\n root_dir (string): Directory with all the images.\n transform (callable, optional): Optional transform to be applied\n on a sample.\n \"\"\"\n self.landmarks_frame = pd.read_csv(csv_file)\n self.root_dir = root_dir\n self.transform = transform\n\n def __len__(self):\n return len(self.landmarks_frame)\n\n def __getitem__(self, idx):\n if torch.is_tensor(idx):\n idx = idx.tolist()\n\n img_name = os.path.join(self.root_dir,\n self.landmarks_frame.iloc[idx, 0])\n image = io.imread(img_name)\n landmarks = self.landmarks_frame.iloc[idx, 1:]\n landmarks = np.array([landmarks])\n landmarks = landmarks.astype('float').reshape(-1, 2)\n sample = {'image': image, 'landmarks': landmarks}\n\n if self.transform:\n sample = self.transform(sample)\n\n return sample"
83+
"class FaceLandmarksDataset(Dataset):\n \"\"\"Face Landmarks dataset.\"\"\"\n\n def __init__(self, csv_file, root_dir, transform=None):\n \"\"\"\n Arguments:\n csv_file (string): Path to the csv file with annotations.\n root_dir (string): Directory with all the images.\n transform (callable, optional): Optional transform to be applied\n on a sample.\n \"\"\"\n self.landmarks_frame = pd.read_csv(csv_file)\n self.root_dir = root_dir\n self.transform = transform\n\n def __len__(self):\n return len(self.landmarks_frame)\n\n def __getitem__(self, idx):\n if torch.is_tensor(idx):\n idx = idx.tolist()\n\n img_name = os.path.join(self.root_dir,\n self.landmarks_frame.iloc[idx, 0])\n image = io.imread(img_name)\n landmarks = self.landmarks_frame.iloc[idx, 1:]\n landmarks = np.array([landmarks])\n landmarks = landmarks.astype('float').reshape(-1, 2)\n sample = {'image': image, 'landmarks': landmarks}\n\n if self.transform:\n sample = self.transform(sample)\n\n return sample"
8484
]
8585
},
8686
{
@@ -105,7 +105,7 @@
105105
"cell_type": "markdown",
106106
"metadata": {},
107107
"source": [
108-
"## Transforms\n\nOne issue we can see from the above is that the samples are not of the\nsame size. Most neural networks expect the images of a fixed size.\nTherefore, we will need to write some preprocessing code.\nLet's create three transforms:\n\n- ``Rescale``: to scale the image\n- ``RandomCrop``: to crop from image randomly. This is data\n augmentation.\n- ``ToTensor``: to convert the numpy images to torch images (we need to\n swap axes).\n\nWe will write them as callable classes instead of simple functions so\nthat parameters of the transform need not be passed everytime it's\ncalled. For this, we just need to implement ``__call__`` method and\nif required, ``__init__`` method. We can then use a transform like this:\n\n::\n\n tsfm = Transform(params)\n transformed_sample = tsfm(sample)\n\nObserve below how these transforms had to be applied both on the image and\nlandmarks.\n\n\n"
108+
"## Transforms\n\nOne issue we can see from the above is that the samples are not of the\nsame size. Most neural networks expect the images of a fixed size.\nTherefore, we will need to write some preprocessing code.\nLet's create three transforms:\n\n- ``Rescale``: to scale the image\n- ``RandomCrop``: to crop from image randomly. This is data\n augmentation.\n- ``ToTensor``: to convert the numpy images to torch images (we need to\n swap axes).\n\nWe will write them as callable classes instead of simple functions so\nthat parameters of the transform need not be passed every time it's\ncalled. For this, we just need to implement ``__call__`` method and\nif required, ``__init__`` method. We can then use a transform like this:\n\n::\n\n tsfm = Transform(params)\n transformed_sample = tsfm(sample)\n\nObserve below how these transforms had to be applied both on the image and\nlandmarks.\n\n\n"
109109
]
110110
},
111111
{
@@ -123,7 +123,7 @@
123123
"cell_type": "markdown",
124124
"metadata": {},
125125
"source": [
126-
"<div class=\"alert alert-info\"><h4>Note</h4><p>In the example above, `RandomCrop` uses an external library's random number generator \n (in this case, Numpy's `np.random.int`). This can result in unexpected behavior with `DataLoader` \n (see https://pytorch.org/docs/stable/notes/faq.html#my-data-loader-workers-return-identical-random-numbers). \n In practice, it is safer to stick to PyTorch's random number generator, e.g. by using `torch.randint` instead.</p></div>\n\n"
126+
"<div class=\"alert alert-info\"><h4>Note</h4><p>In the example above, `RandomCrop` uses an external library's random number generator \n (in this case, Numpy's `np.random.int`). This can result in unexpected behavior with `DataLoader`\n (see [here](https://pytorch.org/docs/stable/notes/faq.html#my-data-loader-workers-return-identical-random-numbers)).\n In practice, it is safer to stick to PyTorch's random number generator, e.g. by using `torch.randint` instead.</p></div>\n\n"
127127
]
128128
},
129129
{
@@ -177,14 +177,14 @@
177177
},
178178
"outputs": [],
179179
"source": [
180-
"dataloader = DataLoader(transformed_dataset, batch_size=4,\n shuffle=True, num_workers=0)\n\n\n# Helper function to show a batch\ndef show_landmarks_batch(sample_batched):\n \"\"\"Show image with landmarks for a batch of samples.\"\"\"\n images_batch, landmarks_batch = \\\n sample_batched['image'], sample_batched['landmarks']\n batch_size = len(images_batch)\n im_size = images_batch.size(2)\n grid_border_size = 2\n\n grid = utils.make_grid(images_batch)\n plt.imshow(grid.numpy().transpose((1, 2, 0)))\n\n for i in range(batch_size):\n plt.scatter(landmarks_batch[i, :, 0].numpy() + i * im_size + (i + 1) * grid_border_size,\n landmarks_batch[i, :, 1].numpy() + grid_border_size,\n s=10, marker='.', c='r')\n\n plt.title('Batch from dataloader')\n\n# if you are using Windows, uncomment the next line and indent the for loop.\n# you might need to go back and change \"num_workers\" to 0. \n\n# if __name__ == '__main__':\nfor i_batch, sample_batched in enumerate(dataloader):\n print(i_batch, sample_batched['image'].size(),\n sample_batched['landmarks'].size())\n\n # observe 4th batch and stop.\n if i_batch == 3:\n plt.figure()\n show_landmarks_batch(sample_batched)\n plt.axis('off')\n plt.ioff()\n plt.show()\n break"
180+
"dataloader = DataLoader(transformed_dataset, batch_size=4,\n shuffle=True, num_workers=0)\n\n\n# Helper function to show a batch\ndef show_landmarks_batch(sample_batched):\n \"\"\"Show image with landmarks for a batch of samples.\"\"\"\n images_batch, landmarks_batch = \\\n sample_batched['image'], sample_batched['landmarks']\n batch_size = len(images_batch)\n im_size = images_batch.size(2)\n grid_border_size = 2\n\n grid = utils.make_grid(images_batch)\n plt.imshow(grid.numpy().transpose((1, 2, 0)))\n\n for i in range(batch_size):\n plt.scatter(landmarks_batch[i, :, 0].numpy() + i * im_size + (i + 1) * grid_border_size,\n landmarks_batch[i, :, 1].numpy() + grid_border_size,\n s=10, marker='.', c='r')\n\n plt.title('Batch from dataloader')\n\n# if you are using Windows, uncomment the next line and indent the for loop.\n# you might need to go back and change ``num_workers`` to 0.\n\n# if __name__ == '__main__':\nfor i_batch, sample_batched in enumerate(dataloader):\n print(i_batch, sample_batched['image'].size(),\n sample_batched['landmarks'].size())\n\n # observe 4th batch and stop.\n if i_batch == 3:\n plt.figure()\n show_landmarks_batch(sample_batched)\n plt.axis('off')\n plt.ioff()\n plt.show()\n break"
181181
]
182182
},
183183
{
184184
"cell_type": "markdown",
185185
"metadata": {},
186186
"source": [
187-
"## Afterword: torchvision\n\nIn this tutorial, we have seen how to write and use datasets, transforms\nand dataloader. ``torchvision`` package provides some common datasets and\ntransforms. You might not even have to write custom classes. One of the\nmore generic datasets available in torchvision is ``ImageFolder``.\nIt assumes that images are organized in the following way: ::\n\n root/ants/xxx.png\n root/ants/xxy.jpeg\n root/ants/xxz.png\n .\n .\n .\n root/bees/123.jpg\n root/bees/nsdf3.png\n root/bees/asd932_.png\n\nwhere 'ants', 'bees' etc. are class labels. Similarly generic transforms\nwhich operate on ``PIL.Image`` like ``RandomHorizontalFlip``, ``Scale``,\nare also available. You can use these to write a dataloader like this: ::\n\n import torch\n from torchvision import transforms, datasets\n\n data_transform = transforms.Compose([\n transforms.RandomSizedCrop(224),\n transforms.RandomHorizontalFlip(),\n transforms.ToTensor(),\n transforms.Normalize(mean=[0.485, 0.456, 0.406],\n std=[0.229, 0.224, 0.225])\n ])\n hymenoptera_dataset = datasets.ImageFolder(root='hymenoptera_data/train',\n transform=data_transform)\n dataset_loader = torch.utils.data.DataLoader(hymenoptera_dataset,\n batch_size=4, shuffle=True,\n num_workers=4)\n\nFor an example with training code, please see\n:doc:`transfer_learning_tutorial`.\n\n"
187+
"## Afterword: torchvision\n\nIn this tutorial, we have seen how to write and use datasets, transforms\nand dataloader. ``torchvision`` package provides some common datasets and\ntransforms. You might not even have to write custom classes. One of the\nmore generic datasets available in torchvision is ``ImageFolder``.\nIt assumes that images are organized in the following way: ::\n\n root/ants/xxx.png\n root/ants/xxy.jpeg\n root/ants/xxz.png\n .\n .\n .\n root/bees/123.jpg\n root/bees/nsdf3.png\n root/bees/asd932_.png\n\nwhere 'ants', 'bees' etc. are class labels. Similarly generic transforms\nwhich operate on ``PIL.Image`` like ``RandomHorizontalFlip``, ``Scale``,\nare also available. You can use these to write a dataloader like this: ::\n\n import torch\n from torchvision import transforms, datasets\n\n data_transform = transforms.Compose([\n transforms.RandomSizedCrop(224),\n transforms.RandomHorizontalFlip(),\n transforms.ToTensor(),\n transforms.Normalize(mean=[0.485, 0.456, 0.406],\n std=[0.229, 0.224, 0.225])\n ])\n hymenoptera_dataset = datasets.ImageFolder(root='hymenoptera_data/train',\n transform=data_transform)\n dataset_loader = torch.utils.data.DataLoader(hymenoptera_dataset,\n batch_size=4, shuffle=True,\n num_workers=4)\n\nFor an example with training code, please see\n:doc:`transfer_learning_tutorial`.\n\n"
188188
]
189189
}
190190
],
Loading
Loading
Loading
1.29 KB
Loading
464 Bytes
Loading
-13.6 KB
Loading
-703 Bytes
Loading
-488 Bytes
Loading
-808 Bytes
Loading
-24.6 KB
Loading
-16.6 KB
Loading
926 Bytes
Loading
52 Bytes
Loading
598 Bytes
Loading
-1.77 KB
Loading
Loading
Loading
Loading
Loading
Loading
Loading
Loading
-666 Bytes
Loading

_images/sphx_glr_trainingyt_001.png

-522 Bytes
Loading

_images/sphx_glr_trainingyt_thumb.png

-899 Bytes
Loading
Loading
Loading
Loading

_sources/advanced/dynamic_quantization_tutorial.rst.txt

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -516,9 +516,9 @@ models run single threaded.
516516
.. code-block:: none
517517
518518
loss: 5.167
519-
elapsed time (seconds): 174.8
519+
elapsed time (seconds): 184.6
520520
loss: 5.168
521-
elapsed time (seconds): 105.4
521+
elapsed time (seconds): 107.0
522522
523523
524524
@@ -540,7 +540,7 @@ Thanks for reading! As always, we welcome any feedback, so please create an issu
540540

541541
.. rst-class:: sphx-glr-timing
542542

543-
**Total running time of the script:** ( 4 minutes 49.111 seconds)
543+
**Total running time of the script:** ( 5 minutes 0.415 seconds)
544544

545545

546546
.. _sphx_glr_download_advanced_dynamic_quantization_tutorial.py:

0 commit comments

Comments
 (0)