PyTorch / Tensor, gradient, and module foundations / Lesson 7
Boolean Masks and Selection
Use Boolean masks deliberately and distinguish selecting values from preserving a tensor shape.
On this page
Lesson goals
- Build a Boolean condition for a tensor.
- Compare selected values with shape-preserving replacement.
- Validate mask meaning, shape, and device.
Define the mask contract
A Boolean mask states which elements satisfy a condition. Before applying it, define whether true means include, ignore, or replace; different APIs and tasks can use different conventions. Record the tensor axes and expected mask shape, especially when a mask is broadcast across a batch or feature dimension.
A mask can be valid syntactically yet refer to the wrong records. Use a small fixture with recognizable values and inspect the Boolean condition directly. Keep sample identifiers or row order available when selected values need to be traced back to their source.
Select matching values
In a local lab with a compatible PyTorch installation, the following example marks values at least five and selects those entries. Selection returns the matching values rather than a tensor with the original four positions. This code requires an external library and is illustrative; the public reader does not execute it.
import torch
values = torch.tensor([2, 5, 8, 1])
mask = values >= 5
print(mask)
print(values[mask])
The condition is false, true, true, false; the selected values are 5 and 8.
Preserve positions when needed
A conditional choice can preserve the original positions while substituting a value where the condition is false. In this lab, zeros fill the excluded positions. A zero is a chosen replacement, not automatically a missing value; downstream calculations must know how those positions should be treated.
import torch
values = torch.tensor([2, 5, 8, 1])
mask = values >= 5
print(torch.where(mask, values, torch.zeros_like(values)))
The result retains four positions with values 0, 5, 8, and 0.
Check shape and alignment
Inspect mask shape, dtype, and device before applying it. When broadcasting is intended, verify which axes expand and compare a small example with a manual calculation. Test a batch size different from the feature count so accidental equality does not hide an axis mistake. Check empty and all-true masks as well.
Count eligible values in reductions
For a masked loss or mean, specify whether excluded elements are removed from both numerator and denominator. Replacing excluded values with zero and then averaging over all positions answers a different question from averaging only included values. Handle an empty eligible set explicitly instead of silently dividing by zero.
Common errors and fixes
The selected tensor has fewer positions than expected.
- Why it happens
- Boolean selection was used where shape-preserving replacement was intended.
- How to fix it
- Use a documented conditional operation when original positions are required.
- Prevent it next time
- State the expected output shape before applying the mask.
A masked average is too small.
- Why it happens
- Excluded positions were zeroed but remained in the denominator.
- How to fix it
- Use the intended eligible count and handle an empty mask.
- Prevent it next time
- Document numerator and denominator for masked reductions.
A valid mask selects the wrong axis.
- Why it happens
- Broadcasting aligned the mask differently from the intended semantics.
- How to fix it
- Reshape or construct the mask for the correct axis and verify values.
- Prevent it next time
- Test unequal dimensions and recognizable fixtures.
2 practice exercises
1. For values 2, 5, 8, 1 and condition at least 5, what is selected?
Show worked solution
The mask is false, true, true, false and the selected values are 5 and 8. Selection retains only matching entries.
2. Why does averaging 0, 5, 8, 0 differ from averaging selected values 5 and 8?
Show worked solution
The first mean divides 13 by four positions; the second divides by two eligible values. Choose the denominator that matches the metric and handle a mask with no eligible values.
Key takeaways
- A mask needs an explicit true/false meaning.
- Selection and replacement have different output shapes.
- Masked reductions require a deliberate denominator.