📅  最后修改于: 2023-12-03 15:19:37.041000             🧑  作者: Mango
PyTorch is a popular deep learning framework that offers a variety of loss functions for training machine learning models. Two of the most commonly used loss functions are the Mean Squared Error (MSE) and Mean Absolute Error (MAE). In this article, we will cover how to use MSE and MAE in PyTorch.
MSE is a loss function that measures the average squared difference between the predicted and actual values. It is commonly used in regression problems.
In PyTorch, we can calculate the MSE using the nn.MSELoss()
function. Here's an example:
import torch
import torch.nn as nn
# Define the predicted and actual values
y_pred = torch.tensor([1.0, 2.0, 3.0, 4.0])
y_actual = torch.tensor([0.0, 4.0, 2.0, 3.0])
# Calculate the MSE
criterion = nn.MSELoss()
loss = criterion(y_pred, y_actual)
print(loss)
Output:
tensor(3.2500)
In the above example, the MSE is 3.25.
MAE is another loss function that measures the average absolute difference between the predicted and actual values. It is commonly used in regression problems.
In PyTorch, we can calculate the MAE using the nn.L1Loss()
function. Here's an example:
import torch
import torch.nn as nn
# Define the predicted and actual values
y_pred = torch.tensor([1.0, 2.0, 3.0, 4.0])
y_actual = torch.tensor([0.0, 4.0, 2.0, 3.0])
# Calculate the MAE
criterion = nn.L1Loss()
loss = criterion(y_pred, y_actual)
print(loss)
Output:
tensor(1.5000)
In the above example, the MAE is 1.5.
MSE and MAE are commonly used loss functions in regression problems. In PyTorch, we can easily calculate these loss functions using the nn.MSELoss()
and nn.L1Loss()
functions, respectively.