Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 13 additions & 10 deletions beginner_source/basics/transforms_tutorial.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,35 +30,38 @@
from torchvision import datasets
from torchvision.transforms import ToTensor, Lambda

target_transform = Lambda(
lambda y: torch.zeros(10, dtype=torch.float32).scatter_(
dim=0, index=torch.tensor(y), value=1
)
)

ds = datasets.FashionMNIST(
root="data",
train=True,
download=True,
transform=ToTensor(),
target_transform=Lambda(lambda y: torch.zeros(10, dtype=torch.float).scatter_(0, torch.tensor(y), value=1))
target_transform=target_transform,
)

#################################################
# ToTensor()
# -------------------------------
#
# `ToTensor <https://pytorch.org/vision/stable/transforms.html#torchvision.transforms.ToTensor>`_
# converts a PIL image or NumPy ``ndarray`` into a ``FloatTensor``. and scales
# converts a PIL image or NumPy ``ndarray`` into a ``FloatTensor`` and scales
# the image's pixel intensity values in the range [0., 1.]
#

##############################################
# Lambda Transforms
# -------------------------------
#
# 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_ <https://pytorch.org/docs/stable/generated/torch.Tensor.scatter_.html>`_ which assigns a
# ``value=1`` on the index as given by the label ``y``.

target_transform = Lambda(lambda y: torch.zeros(
10, dtype=torch.float).scatter_(dim=0, index=torch.tensor(y), value=1))
# Lambda transforms apply any user-defined callable. Above, ``target_transform`` wraps a
# small lambda that turns each label ``y`` into a one-hot encoded tensor: it allocates a
# length-10 zero vector and uses
# `scatter_ <https://pytorch.org/docs/stable/generated/torch.Tensor.scatter_.html>`_ to write
# ``value=1`` at index ``y``.

######################################################################
# --------------
Expand Down