Complete the code to create a Mean Squared Error loss function in PyTorch.
import torch.nn as nn loss_fn = nn.[1]()
The Mean Squared Error loss function in PyTorch is nn.MSELoss(). It measures the average squared difference between predicted and true values.
Complete the code to create a Cross Entropy loss function in PyTorch.
import torch.nn as nn loss_fn = nn.[1]()
The Cross Entropy loss function in PyTorch is nn.CrossEntropyLoss(). It is used for multi-class classification problems.
Fix the error in the code to compute the loss between predictions and targets using MSELoss.
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())
The first argument to the loss function should be the model's predictions. Here, predictions is correct.
Fill both blanks to compute Cross Entropy loss for classification outputs and labels.
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())
The labels tensor contains class indices. The second label is class 2. The loss function takes outputs and labels as arguments.
Fill all three blanks to create MSE loss and compute it between predictions and targets.
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())
The predictions tensor has values 2.5, 0.0, and 2.0. The targets tensor has 3.0, 0.0, and 2.1. These values match the example for computing MSE loss.