secml-torch icon indicating copy to clipboard operation
secml-torch copied to clipboard

Custom Constraint that incorporates preprocessing to apply it on the input space

Open maurapintor opened this issue 1 year ago • 0 comments

A new constraint class should be defined. Specifically, when the input uses some sort of preprocessing,

$x = f(z),$

the current constraint can only be applied on $x$.

We need an additional constraint interface that inverts the preprocessing, applies the constraint to $z$, then reapplies the preprocessing.

Implementation plan:


class InputSpaceConstraint(Constraint, ABC):
    """Input space constraint.

    Reverts the preprocessing, applies the constraint, and re-applies the preprocessing.
    """

    def __init__(self, preprocessing: DataProcessing) -> None:
        """
        Create ConstraintWithPreprocessing.

        Parameters
        ----------
        preprocessing : DataProcessing
            Preprocessing to invert to apply the constraint on the input space.
        """
        self.preprocessing = preprocessing

    def __call__(self, x: torch.Tensor, *args, **kwargs) -> torch.Tensor:
        """
        Project onto the constraint.

        Parameters
        ----------
        x : torch.Tensor
            Input tensor.

        Returns
        -------
        torch.Tensor
            Tensor projected onto the constraint.
        """
        x_transformed = x.detach().clone()
        x_transformed = self.preprocessing.invert(x_transformed)
        x_transformed = self._apply_constraint(x_transformed)
        return self.preprocessing(x_transformed)

maurapintor avatar Oct 10 '24 08:10 maurapintor