2025, Sep 25 03:00
Fixed-Angle Rotations in Torchvision: Apply Only +45° or -45° with Equal Probability Using RandomChoice
Use Torchvision to rotate images by exactly +45° or -45° with a 50/50 probability. Skip angle ranges; apply fixed-angle RandomRotation with RandomChoice.
When augmenting image data, it is common to add random rotations to improve robustness. But sometimes you need strict control: rotate only by +45 or -45 degrees with equal probability, and never anything in between. Using a generic angle range will not meet that requirement.
Problem setup
A straightforward attempt with torchvision looks like this, but it produces any angle within the interval rather than exactly the two target angles.
import torchvision.transforms as T
pipeline = T.Compose([
    T.RandomRotation((-45, 45))
])
What actually happens
Passing an interval to RandomRotation means the transform samples a random angle anywhere between the lower and upper bounds on each call. In other words, the result will include the entire range from -45 to 45 degrees, not just -45 and +45.
A precise solution with a 50/50 choice
To guarantee only the two angles with equal probability, first make an even random choice, then apply a fixed-angle rotation. In torchvision this maps cleanly to RandomChoice, and a fixed angle is represented by a tuple where the lower and upper bounds are the same.
import torchvision.transforms as T
augment_ops = T.Compose([
    T.RandomChoice([
        T.RandomRotation((45, 45)),
        T.RandomRotation((-45, -45)),
    ], p=[0.5, 0.5])
])
This pipeline enforces a 50% chance of +45 degrees and a 50% chance of -45 degrees, with no intermediate rotations.
Why this matters
Data augmentation should follow the specification of your task. If the pipeline allows angles you did not intend, the transformed samples may stray from the desired distribution. Locking augmentation to the exact set of rotations prevents unintended variability and keeps the dataset aligned with the required constraints.
Conclusion
When you need fixed-angle rotations in torchvision, avoid providing a range that includes unwanted values. Instead, perform an explicit 50/50 selection between two fixed-angle transforms using RandomChoice, each configured with identical min and max to pin the angle. This keeps the augmentation precise and predictable.
The article is based on a question from StackOverflow by Lézard and an answer by Ahmad Abdallah.