Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

PyTorch torch.nn.MSELoss Function

PyTorch torch.nn.MSELoss Function

PyTorch torch.nn Reference Manual 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:

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

)

print

(

"Predicted value:"

,

predictions.

tolist

(

)

)

print

(

"Target value:"

,

targets.

tolist

(

)

)

print

(

"MSE loss:"

,

loss.

item

(

)

)

Manual verification

manual_mse

=

(

(

predictions - targets

)

**

2

)

.

mean

(

)

print

(

"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

(

)

print

(

"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

)

print

(

"Mean:"

,

loss_mean.

item

(

)

)

print

(

"Sum:"

,

loss_sum.

item

(

)

)

print

(

"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

)

print

(

"Predicted shape:"

,

pred.

shape

)

print

(

"Target shape:"

,

target.

shape

)

print

(

"MSE loss:"

,

loss.

item

(

)

)


Common questions

Q1: Which is better, MSE or MAE?

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:


PyTorch torch.nn Reference Manual PyTorch torch.nn Reference Manual