0
0
PyTorchml~10 mins

Loss functions (MSELoss, CrossEntropyLoss) 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 create a Mean Squared Error loss function in PyTorch.

PyTorch
import torch.nn as nn
loss_fn = nn.[1]()
Drag options to blanks, or click blank then click option'
ABCELoss
BMSELoss
CL1Loss
DCrossEntropyLoss
Attempts:
3 left
💡 Hint
Common Mistakes
Choosing CrossEntropyLoss which is for classification tasks.
Using BCELoss which is for binary classification.
2fill in blank
medium

Complete the code to create a Cross Entropy loss function in PyTorch.

PyTorch
import torch.nn as nn
loss_fn = nn.[1]()
Drag options to blanks, or click blank then click option'
AL1Loss
BMSELoss
CCrossEntropyLoss
DNLLLoss
Attempts:
3 left
💡 Hint
Common Mistakes
Using MSELoss for classification tasks.
Using NLLLoss directly without applying LogSoftmax.
3fill in blank
hard

Fix the error in the code to compute the loss between predictions and targets using MSELoss.

PyTorch
import torch
import torch.nn as nn

predictions = torch.tensor([2.5, 0.0, 2.1])
targets = torch.tensor([3.0, -0.5, 2.0])

loss_fn = nn.MSELoss()
loss = loss_fn([1], targets)
print(loss.item())
Drag options to blanks, or click blank then click option'
Atargets.detach()
Btargets
Cpredictions.detach()
Dpredictions
Attempts:
3 left
💡 Hint
Common Mistakes
Swapping predictions and targets in the loss function.
Using detached tensors which breaks gradient flow.
4fill in blank
hard

Fill both blanks to compute Cross Entropy loss for classification outputs and labels.

PyTorch
import torch
import torch.nn as nn

outputs = torch.tensor([[1.0, 2.0, 0.5], [0.5, 1.5, 1.0]])
labels = torch.tensor([1, [1]])

loss_fn = nn.CrossEntropyLoss()
loss = loss_fn(outputs, [2])
print(loss.item())
Drag options to blanks, or click blank then click option'
A0
Blabels
C2
D3
Attempts:
3 left
💡 Hint
Common Mistakes
Using label values outside the range of classes.
Passing outputs as labels or vice versa.
5fill in blank
hard

Fill all three blanks to create MSE loss and compute it between predictions and targets.

PyTorch
import torch
import torch.nn as nn

predictions = torch.tensor([[1], [2], 2.0])
targets = torch.tensor([3.0, 0.0, [3]])

loss_fn = nn.MSELoss()
loss = loss_fn(predictions, targets)
print(loss.item())
Drag options to blanks, or click blank then click option'
A2.5
B0.0
C2.1
D3.0
Attempts:
3 left
💡 Hint
Common Mistakes
Mixing up prediction and target values.
Using values not consistent with the example.