0
0
PyTorchml~10 mins

Validation loop 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 set the model to evaluation mode before validation.

PyTorch
model.[1]()
Drag options to blanks, or click blank then click option'
Aeval
Btrain
Cfit
Dvalidate
Attempts:
3 left
💡 Hint
Common Mistakes
Using model.train() instead of model.eval() during validation.
Calling a non-existent method like model.validate().
2fill in blank
medium

Complete the code to disable gradient calculation during validation.

PyTorch
with torch.[1]():
    # validation code here
Drag options to blanks, or click blank then click option'
Ano_grad
Bgrad
Cenable_grad
Dautograd
Attempts:
3 left
💡 Hint
Common Mistakes
Not disabling gradients during validation, causing unnecessary computation.
Using torch.grad() which does not exist.
3fill in blank
hard

Fix the error in the validation loop to correctly accumulate the total loss.

PyTorch
total_loss = 0
for inputs, labels in val_loader:
    outputs = model(inputs)
    loss = criterion(outputs, labels)
    total_loss [1] loss.item()
Drag options to blanks, or click blank then click option'
A=
B*=
C-=
D+=
Attempts:
3 left
💡 Hint
Common Mistakes
Using = which overwrites total_loss each iteration.
Using -= or *= which changes the meaning incorrectly.
4fill in blank
hard

Fill both blanks to compute the average validation loss after the loop.

PyTorch
avg_loss = total_loss [1] len([2])
Drag options to blanks, or click blank then click option'
A/
B*
Cval_loader
Dtrain_loader
Attempts:
3 left
💡 Hint
Common Mistakes
Using train_loader length instead of val_loader.
Multiplying instead of dividing.
5fill in blank
hard

Fill all three blanks to complete the validation loop with accuracy calculation.

PyTorch
correct = 0
total = 0
with torch.no_grad():
    for inputs, labels in [1]:
        outputs = model(inputs)
        _, predicted = torch.max(outputs.data, [2])
        total += labels.size([3])
        correct += (predicted == labels).sum().item()
Drag options to blanks, or click blank then click option'
Aval_loader
Bdim=1
C0
Dtrain_loader
Attempts:
3 left
💡 Hint
Common Mistakes
Using train_loader instead of val_loader.
Using wrong dimension for torch.max or labels.size.