Using the MSELoss
For regression problems, you often use Mean Squared Error (MSE) as a loss function instead of cross-entropy. MSE calculates the squared difference between predicted values (y_pred
) and actual values (y
). Now, you'll compute MSE loss using both NumPy and PyTorch.
torch
, numpy
(as np
), and torch.nn
(as nn
) packages are already imported.
This exercise is part of the course
Introduction to Deep Learning with PyTorch
Exercise instructions
- Calculate the MSE loss using NumPy.
- Create an MSE loss function using PyTorch.
- Convert
y_pred
andy
to tensors, then calculate the MSE loss asmse_pytorch
.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
y_pred = np.array([3, 5.0, 2.5, 7.0])
y = np.array([3.0, 4.5, 2.0, 8.0])
# Calculate MSE using NumPy
mse_numpy = ____
# Create the MSELoss function in PyTorch
criterion = ____
# Calculate MSE using PyTorch
mse_pytorch = ____(torch.tensor(____), ____)
print("MSE (NumPy):", mse_numpy)
print("MSE (PyTorch):", mse_pytorch)