rai_toolbox.perturbations.uniform_like_l2_n_ball_#
- rai_toolbox.perturbations.uniform_like_l2_n_ball_(x, epsilon=1.0, param_ndim=-1, generator=<torch._C.Generator object>)[source]#
Uniform sampling within an \(\epsilon\)-sized
n-ball for \(L^2\)-norm, wherenis controlled byx.shapeandparam_ndim. The result overwritesxin-place.- Parameters:
- x: Tensor, shape-(N, D, …)
The tensor to generate a new random tensor from, i.e., returns a tensor of similar shape and on the same device.
By default, each of the
Nshape-(D, ...)subtensors are initialized independently. Seeparam_ndimto control this behavior.- epsilonfloat, optional (default=1)
Determines the radius of the ball.
- param_ndimint | None, optional (default=-1)
Determines the dimensionality of the subtensors that are sampled by this function.
A positive number determines the dimensionality of each subtensor to be drawn and packed into the shape-
(N, D, ...)resulting tensor.A negative number determines from the dimensionality of the subtensor in terms of the offset of
x.ndim. E.g. -1 indicates thatxis arranged in a batch-style, and thatNindependent shape-(D, ...)tensors will be sampled.Nonemeans that a single tensor of shape-(N, D, ...)is sampled.
- generatortorch.Generator, optional (default=`torch.default_generator`)
Controls the RNG source.
- Returns:
- xTensor, shape-(N, D, …)
The input tensor, which has been modified in-place.
References
[1]Rauber et al., 2020, Foolbox Native: Fast adversarial attacks to benchmark the robustness of machine learning models in PyTorch, TensorFlow, and JAX https://doi.org/10.21105/joss.02607
[2]Voelker et al., 2017, Efficiently sampling vectors and coordinates from the n-sphere and n-ball http://compneuro.uwaterloo.ca/files/publications/voelker.2017.pdf
[3]Roberts, Martin, 2020, How to generate uniformly random points on n-spheres and in n-balls http://extremelearning.com.au/how-to-generate-uniformly-random-points-on-n-spheres-and-n-balls/
Examples
>>> import torch as tr >>> from rai_toolbox.perturbations.init import uniform_like_l2_n_ball_
Drawing two shape-
(3,)tensors from an \(\epsilon=2\)-sized \(L^2\) 3D-ball.>>> x = tr.zeros(2, 3) >>> uniform_like_l2_n_ball_(x, epsilon=2.0, param_ndim=1) >>> x tensor([[0.3030, 1.4269, 0.3927], [1.4015, 0.4913, 1.3028]]) >>> tr.linalg.norm(x, dim=1, ord=2) < 2.0 tensor([True, True])
Drawing one shape-
(6, )tensor from a \(\epsilon=2\)-sized \(L^2\) 6D-ball, and storing it inxas a shape-(2, 3)tensor. We specifyparam_ndim=2(orparam_ndim=None) to achieve this.>>> x = tr.zeros(2, 3) >>> uniform_like_l2_n_ball_(x, epsilon=2.0, param_ndim=2) >>> x tensor([[-0.6903, -0.8597, 0.0109], [ 0.0906, -0.2387, -0.3059]]) >>> tr.linalg.norm(x, ord=2) < 2.0 tensor(True)