0
0
PyTorchml~10 mins

Custom transforms in PyTorch - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to define a custom transform class that converts an image to grayscale.

PyTorch
import torchvision.transforms as transforms

class ToGrayScale:
    def __call__(self, img):
        return img.[1]('L')
Drag options to blanks, or click blank then click option'
Ato_grayscale
Bconvert
Cgrayscale
Dconvert_grayscale
Attempts:
3 left
💡 Hint
Common Mistakes
Using a non-existent method like 'to_grayscale' causes errors.
Forgetting to specify the number of output channels.
2fill in blank
medium

Complete the code to apply the custom transform to an image.

PyTorch
from PIL import Image

img = Image.open('sample.jpg')
transform = ToGrayScale()
gray_img = transform.[1](img)
Drag options to blanks, or click blank then click option'
A__call__
B__call
Ctransform
Dapply
Attempts:
3 left
💡 Hint
Common Mistakes
Trying to call a non-existent method like 'apply'.
Using incorrect method names like '__call' without trailing underscores.
3fill in blank
hard

Fix the error in the custom transform that should normalize a tensor image.

PyTorch
import torch

class NormalizeTensor:
    def __init__(self, mean, std):
        self.mean = mean
        self.std = std
    def __call__(self, tensor):
        return (tensor - self.mean) / [1]
Drag options to blanks, or click blank then click option'
Aself.mean
Bmean
Cstd
Dself.std
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'mean' or 'self.mean' in the denominator causes wrong normalization.
Forgetting to use 'self.' prefix for instance variables.
4fill in blank
hard

Fill both blanks to complete a custom transform that randomly flips an image horizontally with 50% chance.

PyTorch
import random
from PIL import Image

class RandomHorizontalFlip:
    def __call__(self, img):
        if random.random() [1] 0.5:
            return img.[2](Image.FLIP_LEFT_RIGHT)
        return img
Drag options to blanks, or click blank then click option'
A>
B<
Ctranspose
Dflip
Attempts:
3 left
💡 Hint
Common Mistakes
Using '<' instead of '>' changes the flip probability.
Using a non-existent method like 'flip()' causes errors.
5fill in blank
hard

Fill all three blanks to create a custom transform that converts an image to tensor and normalizes it.

PyTorch
import torchvision.transforms.functional as F

class ToTensorNormalize:
    def __init__(self, mean, std):
        self.mean = mean
        self.std = std
    def __call__(self, img):
        tensor = F.[1](img)
        tensor = F.[2](tensor, self.mean, [3])
        return tensor
Drag options to blanks, or click blank then click option'
Ato_tensor
Bnormalize
Cself.std
Dto_tensor_normalize
Attempts:
3 left
💡 Hint
Common Mistakes
Using a non-existent function like 'to_tensor_normalize'.
Passing mean or std incorrectly without 'self.'.