1
0
Fork 0

Learning about Transforms

main
Nigel Barink 2023-03-30 20:08:49 +02:00
parent a2dcfcf8e9
commit a05849a344
1 changed files with 78 additions and 0 deletions

View File

@ -0,0 +1,78 @@
{
"cells": [
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"Data does not always come in its final processed form that is required for training machine learning algorithms. We use transforms to perform some manipulation of the data and make it suitable for training.\n",
"\n",
"All TorchVision datasets have two parameters -transform to modify the features and target_transform to modify the labels - that accept callables containing the transformation logic. The torchvision.transforms module offers several commonly-used transforms out of the box.\n",
"\n",
"The FashionMNIST features are in PIL Image format, and the labels are integers. For training, we need the features as normalized tensors, and the labels as one-hot encoded tensors. To make these transformations, we use ToTensor and Lambda"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [],
"source": [
"import torch\n",
"from torchvision import datasets\n",
"from torchvision.transforms import ToTensor, Lambda\n",
"\n",
"ds = datasets.FashionMNIST(\n",
" root=\"data\",\n",
" train=True,\n",
" download=True,\n",
" transform=ToTensor(),\n",
" target_transform=Lambda(lambda y: torch.zeros(10, dtype=torch.float).scatter_(0, torch.tensor(y),value=1))\n",
")"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"ToTensor converts a PIL image or NumPy ndarray into a FloatTensor. and scales the images pixel intensity values in the range [0., 1.]"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"Lambda transforms apply any user-defined lambda function. Here, we define a function to turn the integer into a one-hot encoded tensor. It first creates a zero tensor of size 10 (the number of labels in our dataset) and calls scatter_ which assigns a value=1 on the index as given by the label y."
]
}
],
"metadata": {
"kernelspec": {
"display_name": ".venv",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.10.10"
},
"orig_nbformat": 4,
"vscode": {
"interpreter": {
"hash": "4944a85e4459d92b06dc1c94852b4e8e8e6d0531f16bd543c843a0ca37cdfcdb"
}
}
},
"nbformat": 4,
"nbformat_minor": 2
}