PyTorch torch.nn.MSELoss Function
PyTorch torch.nn Reference Manual
torch.nn.MSELoss is the mean squared error loss function in PyTorch.
It computes the mean of the squared differences between predicted and target values, and is commonly used for regression tasks.
Function definition
torch.nn.MSELoss(reduction='mean')
Parameter Description:
reduction(str): Loss reduction method. Options include'mean','sum','none'. Defaults to'mean'.
Mathematical principle
MSE loss formula:
MSE = (1/n) * Σ(y_pred - y_true)²
Usage examples
Example 1: Basic usage
Compute the regression loss:
Example
import
torch
import
torch.
nn
as
nn
Create the MSE loss
criterion
=
nn.
MSELoss
(
)
Predicted and true values
predictions
=
torch.
tensor
(
[
3.0
,
4.0
,
5.0
]
)
targets
=
torch.
tensor
(
[
2.8
,
4.2
,
4.9
]
)
Compute the loss
loss
=
criterion
(
predictions
,
targets
)
(
"Predicted value:"
,
predictions.
tolist
(
)
)
(
"Target value:"
,
targets.
tolist
(
)
)
(
"MSE loss:"
,
loss.
item
(
)
)
Manual verification
manual_mse
=
(
(
predictions - targets
)
**
2
)
.
mean
(
)
(
"Manual calculation:"
,
manual_mse.
item
(
)
)
Example 2: Complete regression training
Training workflow for a regression task:
Example
import
torch
import
torch.
nn
as
nn
import
torch.
optim
as
optim
Simple regression model
class
RegressionNet
(
nn.
Module
)
:
def
init
(
self
)
:
super
(
RegressionNet
,
self
)
.
init
(
)
self
.
fc
=
nn.
Linear
(
10
,
1
)
def
forward
(
self
,
x
)
:
return
self
.
fc
(
x
)
model
=
RegressionNet
(
)
criterion
=
nn.
MSELoss
(
)
optimizer
=
optim.
Adam
(
model.
parameters
(
)
,
lr
=
0.01
)
Training data
X
=
torch.
randn
(
100
,
10
)
y
=
torch.
randn
(
100
,
1
)
Training step
model.
train
(
)
optimizer.
zero_grad
(
)
predictions
=
model
(
X
)
loss
=
criterion
(
predictions
,
y
)
loss.
backward
(
)
optimizer.
step
(
)
(
"Training loss:"
,
loss.
item
(
)
)
Example 3: The reduction parameter
Different aggregation methods:
Example
import
torch
import
torch.
nn
as
nn
pred
=
torch.
tensor
(
[
3.0
,
4.0
,
5.0
,
6.0
]
)
target
=
torch.
tensor
(
[
3.5
,
3.8
,
5.2
,
5.5
]
)
mean: average loss
loss_mean
=
nn.
MSELoss
(
reduction
=
'mean'
)
(
pred
,
target
)
sum: total loss
loss_sum
=
nn.
MSELoss
(
reduction
=
'sum'
)
(
pred
,
target
)
none: no aggregation
loss_none
=
nn.
MSELoss
(
reduction
=
'none'
)
(
pred
,
target
)
(
"Mean:"
,
loss_mean.
item
(
)
)
(
"Sum:"
,
loss_sum.
item
(
)
)
(
"None:"
,
loss_none.
tolist
(
)
)
Example 4: Handling multi-dimensional output
Multi-dimensional regression:
Example
import
torch
import
torch.
nn
as
nn
Multi-dimensional output
pred
=
torch.
randn
(
4
,
3
)
batch=4, 3 outputs
target
=
torch.
randn
(
4
,
3
)
criterion
=
nn.
MSELoss
(
)
loss
=
criterion
(
pred
,
target
)
(
"Predicted shape:"
,
pred.
shape
)
(
"Target shape:"
,
target.
shape
)
(
"MSE loss:"
,
loss.
item
(
)
)
Common questions
Q1: Which is better, MSE or MAE?
- MSE: sensitive to outliers, stable gradients
- MAE (L1): robust to outliers, unstable gradients
Q2: Can MSE be used when outputs have negative values?
Yes, MSE does not restrict the output range.
Q3: What loss should be used for classification tasks?
Use CrossEntropyLoss for classification tasks.
Use Cases
nn.MSELoss Main application scenarios include:
- Regression tasks: House price prediction, numerical estimation
- Continuous value prediction: Object tracking
- Generative models: Certain losses in VAEs and GANs