IniziaInizia gratis

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.

Questo esercizio fa parte del corso

Introduction to Deep Learning with PyTorch

Visualizza il corso

Istruzioni dell'esercizio

  • Calculate the MSE loss using NumPy.
  • Create an MSE loss function using PyTorch.
  • Convert y_pred and y to tensors, then calculate the MSE loss as mse_pytorch.

Esercizio pratico interattivo

Prova a risolvere questo esercizio completando il codice di esempio.

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)
Modifica ed esegui il codice