Skip to content

[Transforms] ApplySomeOf  #7544

Open
@marcown

Description

@marcown

🚀 The feature

Hey,

I found it useful to have a someof class e.g. in imgaug to randomly apply a subset of transformations out of a set of transformation with a parameter "max_transforms". The number of transformations in the subset is randomly sampled with random.randint(0, max_number).

I could not found something similar in the repo so here is an example class for v2:

import torchvision
from typing import Sequence, Callable, Any, Optional, List
import random

class ApplySomeOf(torchvision.transforms.v2.Transform):
    def __init__(
        self,
        transforms: Sequence[Callable],
        max_transforms: Optional[int] = None,
        rand_shuffle: Optional[bool] = False,
    ) -> None:
        if not isinstance(transforms, Sequence):
            raise TypeError("Argument transforms should be a sequence of callables")

        if max_transforms is None:
            max_transforms = len(transforms)

        super().__init__()

        self.transforms = transforms
        self.max_transforms = max_transforms
        self.rand_shuffle =rand_shuffle

    def forward(self, *inputs: Any) -> Any:
        sample = inputs if len(inputs) > 1 else inputs[0]
        selected_transforms = random.sample(self.transforms, k=random.randint(0, self.max_transforms))

        if self.rand_shuffle:
            random.shuffle(selected_transforms)

        for transform in selected_transforms:
            sample = transform(sample)

        return sample

What do you think? Could this be integrated? Or did I miss a similar functionality?

Motivation, pitch

Imgaug has it. It is quite useful.

Alternatives

No response

Additional context

No response

cc @vfdev-5

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions