0
0
PyTorchml~10 mins

Feature extraction strategy 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 load a pretrained ResNet model for feature extraction.

PyTorch
import torch
import torchvision.models as models

model = models.resnet18(pretrained=[1])
Drag options to blanks, or click blank then click option'
AFalse
BTrue
CNone
D0
Attempts:
3 left
💡 Hint
Common Mistakes
Setting pretrained to False loads a model without learned features.
Using None or 0 causes errors or no pretrained weights.
2fill in blank
medium

Complete the code to freeze all parameters in the model to prevent training updates.

PyTorch
for param in model.parameters():
    param.[1] = False
Drag options to blanks, or click blank then click option'
Arequires_grad
Bgrad
Cdetach
Dtrain
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'grad' or 'train' attributes which do not exist for parameters.
Calling detach() on parameters instead of setting requires_grad.
3fill in blank
hard

Fix the error in the code to replace the final fully connected layer with an identity layer for feature extraction.

PyTorch
import torch.nn as nn
model.fc = [1]()
Drag options to blanks, or click blank then click option'
Ann.Identity
Bnn.Linear
Cnn.ReLU
Dnn.Conv2d
Attempts:
3 left
💡 Hint
Common Mistakes
Using nn.Linear requires parameters and changes output size.
Using nn.ReLU or nn.Conv2d changes the output and is not identity.
4fill in blank
hard

Fill both blanks to create a feature extractor that outputs features without gradients and sets the model to evaluation mode.

PyTorch
with torch.no_grad():
    model.[1]()
    features = model(inputs)
Drag options to blanks, or click blank then click option'
Arequires_grad
Btrain
Ceval
Dzero_grad
Attempts:
3 left
💡 Hint
Common Mistakes
Using model.train() enables training mode, which is incorrect here.
Using requires_grad or zero_grad are not model methods.
5fill in blank
hard

Fill all three blanks to extract features from a batch of images using a pretrained model with frozen parameters and identity final layer.

PyTorch
import torch
import torchvision.models as models
import torch.nn as nn

model = models.resnet50(pretrained=[1])
for param in model.parameters():
    param.requires_grad = [2]
model.fc = nn.[3]()
model.eval()

with torch.no_grad():
    features = model(images)
Drag options to blanks, or click blank then click option'
ATrue
BFalse
CIdentity
DLinear
Attempts:
3 left
💡 Hint
Common Mistakes
Not freezing parameters causes training updates.
Not replacing final layer outputs class scores, not features.
Setting pretrained to False loads random weights.