MSELoss — PyTorch 2.7 documentation (original) (raw)

class torch.nn.MSELoss(size_average=None, reduce=None, reduction='mean')[source][source]

Creates a criterion that measures the mean squared error (squared L2 norm) between each element in the input xx and target yy.

The unreduced (i.e. with reduction set to 'none') loss can be described as:

ℓ(x,y)=L={l1,…,lN}⊤,ln=(xn−yn)2,\ell(x, y) = L = \{l_1,\dots,l_N\}^\top, \quad l_n = \left( x_n - y_n \right)^2,

where NN is the batch size. If reduction is not 'none'(default 'mean'), then:

ℓ(x,y)={mean⁡(L),if reduction=‘mean’;sum⁡(L),if reduction=‘sum’.\ell(x, y) = \begin{cases} \operatorname{mean}(L), & \text{if reduction} = \text{`mean';}\\ \operatorname{sum}(L), & \text{if reduction} = \text{`sum'.} \end{cases}

xx and yy are tensors of arbitrary shapes with a total of NN elements each.

The mean operation still operates over all the elements, and divides by NN.

The division by NN can be avoided if one sets reduction = 'sum'.

Parameters

Shape:

Examples:

loss = nn.MSELoss() input = torch.randn(3, 5, requires_grad=True) target = torch.randn(3, 5) output = loss(input, target) output.backward()