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.
Latihan ini adalah bagian dari kursus
Introduction to Deep Learning with PyTorch
Petunjuk latihan
- Calculate the MSE loss using NumPy.
- Create an MSE loss function using PyTorch.
- Convert
y_predandyto tensors, then calculate the MSE loss asmse_pytorch.
Latihan interaktif praktis
Cobalah latihan ini dengan menyelesaikan kode contoh berikut.
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)