Skip to content

Conversation

@sanshi0030
Copy link

This commit addresses two potential points of confusion and error in the MNIST example, as detailed in issue #623.

1.Explicit Loss Reduction: The train() function's use of F.nll_loss implicitly defaults to reduction='mean', whereas the test() function uses reduction='sum'.

This change makes the reduction='mean' explicit in the train() function. This improves code clarity.

  1. Correct Dataset Size with Samplers: Using len(loader.dataset) to get the number of samples is incorrect when a Sampler (e.g., SubsetRandomSampler for a validation split) is used. It incorrectly reports the full dataset size, not the subset size.

The logic is updated to first check len(loader.sampler). If a sampler exists, its length is used. Otherwise, it falls back to len(loader.dataset). This ensures the correct number of samples is used for logging and calculations.

Fixes #623

…length

This commit addresses two potential points of confusion and error in the MNIST example, as detailed in issue pytorch#623.

1. Explicit Loss Reduction:
The train() function's use of F.nll_loss implicitly defaults to reduction='mean', whereas the test() function uses reduction='sum'.

This change makes the `reduction='mean'` explicit in the train() function. This improves code clarity.

2. Correct Dataset Size with Samplers:
Using `len(loader.dataset)` to get the number of samples is incorrect when a Sampler (e.g., SubsetRandomSampler for a validation split) is used. It incorrectly reports the full dataset size, not the subset size.

The logic is updated to first check `len(loader.sampler)`. If a sampler exists, its length is used. Otherwise, it falls back to `len(loader.dataset)`. This ensures the correct number of samples is used for logging and calculations.

Fixes pytorch#623
@meta-cla meta-cla bot added the cla signed label Oct 21, 2025
@netlify
Copy link

netlify bot commented Oct 21, 2025

Deploy Preview for pytorch-examples-preview canceled.

Name Link
🔨 Latest commit b9eaba9
🔍 Latest deploy log https://app.netlify.com/projects/pytorch-examples-preview/deploys/68f788371687380008fb354d

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

mnist example contains bad practices leading to wrongful results

1 participant