October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsWindows FixRecommendedWindows errors stealing your time? Find the fix fastScan stability, cleanup and performance issues.Fix NowOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk3 min

PyTorch MSELoss: Reduction, F.mse_loss, and Tensor Shapes

PyTorch MSELoss squares corresponding input and target values. Learn how reduction changes the output and why matching tensor shapes prevents unintended broadcasting.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

torch.nn.MSELoss squares the difference between corresponding input and target elements. Its default, reduction="mean", averages those squared differences across every element in both tensors—not just across the batch. Choose "sum" to add them or "none" to keep the elementwise losses. For the intended comparisons, make input and target the same shape; a broadcastable mismatch can produce a result that is mathematically valid but compares the wrong values.

What does PyTorch MSELoss calculate?

For each corresponding element, mean squared error is:

As an Amazon Associate I earn from qualifying purchases.

(input - target) ** 2

The PyTorch MSELoss API accepts tensors of any number of dimensions and documents the input and target as having the same shape. It then applies the selected reduction to the elementwise squared differences.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

How do the reduction options change the result?

Let N be the total number of elements in the tensors. The reduction controls what happens to the elementwise squared errors:

reduction Result Output shape
"none" Leaves every squared difference intact. Same shape as input and target.
"sum" Adds all squared differences. A scalar.
"mean" (default) Adds all squared differences and divides by N. A scalar.

For an input shaped [batch, channels, height, width], the default mean includes every batch, channel, height, and width element. It is not automatically a mean of per-sample means. If each sample should have equal weight regardless of its number of elements, calculate that aggregation explicitly rather than assuming the default reduction does it.

Reduction affects the scale and aggregation of the loss, so it can also affect the scale of gradients during training. The API lists size_average and reduce as deprecated legacy arguments; when specified, they override reduction. New code should use reduction.

Should you use nn.MSELoss or F.mse_loss?

Both provide the usual "none", "sum", and "mean" reductions. Use the module form when you want a reusable loss object, or the functional form for a direct call:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
import torch.nn as nn
import torch.nn.functional as F

criterion = nn.MSELoss(reduction="mean")
loss_from_module = criterion(prediction, target)

loss_from_function = F.mse_loss(prediction, target, reduction="mean")

The functional API documentation also lists an optional weight argument. Check the documentation for your installed PyTorch version before relying on that option, since the cited functional page is the current main documentation and can differ from a released version.

Why should input and target shapes match?

Matching shapes makes the elementwise pairing explicit: each prediction is compared with its intended target. PyTorch’s MSELoss API documents same-shaped input and target. When shapes differ, a compatible pair may trigger a warning and broadcast, while an incompatible pair may fail.

Broadcasting aligns dimensions from the trailing end. Dimensions must match, one must be size 1, or one tensor must have no dimension at that position. A size-one dimension can expand to match the other tensor. These rules are described in PyTorch’s broadcasting semantics.

A subtle [B, 1] versus [B] mismatch

Suppose predictions have shape [B, 1] and targets have shape [B]. From the right, PyTorch aligns the prediction’s size-1 dimension with the target’s size-B dimension. The tensors can therefore broadcast to [B, B]. Instead of comparing each prediction with its matching target, the resulting loss can compare each prediction with every target.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

If each row is meant to pair with one target, make the target shape [B, 1] before computing the loss. Do not infer that equal element counts make different shapes interchangeable: shape alignment determines which values are compared.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

How to check and correct shapes

  1. Inspect both shapes immediately before calculating the loss, for example with print(prediction.shape, target.shape).
  2. Confirm that each dimension represents the intended batch, channel, or feature pairing—not merely that the tensors contain the same number of elements.
  3. If dimensions should match but are arranged differently, use an intentional operation such as reshape or unsqueeze to create the target shape that reflects the intended pairing.
  4. Check the resulting shapes again. If a broadcast is deliberate, inspect the expanded dimensions and verify that they represent the comparisons you want.
  5. Pass the aligned tensors to nn.MSELoss or F.mse_loss.

PyTorch’s broadcasting documentation notes that older pointwise behavior that flattened some equal-element-count inputs was deprecated. Do not rely on flattening or accidental compatibility to define your loss; express the intended dimensions explicitly.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
PC Slower Than It Used to Be?Free scan - under a minute
Outdated Drivers Are Slowing You DownFree scan - exact matches

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.