Merge pull request !319 from 张澍坤/mastertags/v1.8.0
@@ -49,11 +49,6 @@ class Attack: | |||||
Returns: | Returns: | ||||
numpy.ndarray, generated adversarial examples | numpy.ndarray, generated adversarial examples | ||||
Examples: | |||||
>>> inputs = np.array([[0.2, 0.4, 0.5, 0.2], [0.7, 0.2, 0.4, 0.3]]) | |||||
>>> labels = np.array([3, 0]) | |||||
>>> advs = attack.batch_generate(inputs, labels, batch_size=2) | |||||
""" | """ | ||||
inputs_image, inputs, labels = check_inputs_labels(inputs, labels) | inputs_image, inputs, labels = check_inputs_labels(inputs, labels) | ||||
arr_x = inputs | arr_x = inputs | ||||
@@ -69,7 +69,6 @@ class GeneticAttack(Attack): | |||||
c (Union[int, float]): Weight of perturbation loss. Default: 0.1. | c (Union[int, float]): Weight of perturbation loss. Default: 0.1. | ||||
Examples: | Examples: | ||||
>>> import numpy as np | |||||
>>> import mindspore.ops.operations as M | >>> import mindspore.ops.operations as M | ||||
>>> from mindspore import Tensor | >>> from mindspore import Tensor | ||||
>>> from mindspore.nn import Cell | >>> from mindspore.nn import Cell | ||||
@@ -75,7 +75,6 @@ class HopSkipJumpAttack(Attack): | |||||
ValueError: If constraint not in ['l2', 'linf'] | ValueError: If constraint not in ['l2', 'linf'] | ||||
Examples: | Examples: | ||||
>>> import numpy as np | |||||
>>> from mindspore import Tensor | >>> from mindspore import Tensor | ||||
>>> from mindarmour import BlackModel | >>> from mindarmour import BlackModel | ||||
>>> from mindarmour.adv_robustness.attacks import HopSkipJumpAttack | >>> from mindarmour.adv_robustness.attacks import HopSkipJumpAttack | ||||
@@ -79,7 +79,6 @@ class NES(Attack): | |||||
input labels are one-hot-encoded. Default: True. | input labels are one-hot-encoded. Default: True. | ||||
Examples: | Examples: | ||||
>>> import numpy as np | |||||
>>> from mindspore import Tensor | >>> from mindspore import Tensor | ||||
>>> from mindarmour import BlackModel | >>> from mindarmour import BlackModel | ||||
>>> from mindarmour.adv_robustness.attacks import NES | >>> from mindarmour.adv_robustness.attacks import NES | ||||
@@ -47,7 +47,6 @@ class PointWiseAttack(Attack): | |||||
Default: True. | Default: True. | ||||
Examples: | Examples: | ||||
>>> import numpy as np | |||||
>>> from mindspore import Tensor | >>> from mindspore import Tensor | ||||
>>> from mindarmour import BlackModel | >>> from mindarmour import BlackModel | ||||
>>> from mindarmour.adv_robustness.attacks import PointWiseAttack | >>> from mindarmour.adv_robustness.attacks import PointWiseAttack | ||||
@@ -64,7 +64,6 @@ class PSOAttack(Attack): | |||||
specifically for model_type='detection'. Reserve_ratio should be in the range of (0, 1). Default: 0.3. | specifically for model_type='detection'. Reserve_ratio should be in the range of (0, 1). Default: 0.3. | ||||
Examples: | Examples: | ||||
>>> import numpy as np | |||||
>>> import mindspore.nn as nn | >>> import mindspore.nn as nn | ||||
>>> from mindspore import Tensor | >>> from mindspore import Tensor | ||||
>>> from mindspore.nn import Cell | >>> from mindspore.nn import Cell | ||||
@@ -40,7 +40,6 @@ class SaltAndPepperNoiseAttack(Attack): | |||||
Default: True. | Default: True. | ||||
Examples: | Examples: | ||||
>>> import numpy as np | |||||
>>> from mindspore import Tensor | >>> from mindspore import Tensor | ||||
>>> from mindarmour import BlackModel | >>> from mindarmour import BlackModel | ||||
>>> from mindarmour.adv_robustness.attacks import SaltAndPepperNoiseAttack | >>> from mindarmour.adv_robustness.attacks import SaltAndPepperNoiseAttack | ||||
@@ -95,7 +95,6 @@ class CarliniWagnerL2Attack(Attack): | |||||
input labels are onehot-coded. Default: True. | input labels are onehot-coded. Default: True. | ||||
Examples: | Examples: | ||||
>>> import numpy as np | |||||
>>> import mindspore.ops.operations as M | >>> import mindspore.ops.operations as M | ||||
>>> from mindspore.nn import Cell | >>> from mindspore.nn import Cell | ||||
>>> from mindarmour.adv_robustness.attacks import CarliniWagnerL2Attack | >>> from mindarmour.adv_robustness.attacks import CarliniWagnerL2Attack | ||||
@@ -117,7 +117,6 @@ class DeepFool(Attack): | |||||
input labels are onehot-coded. Default: True. | input labels are onehot-coded. Default: True. | ||||
Examples: | Examples: | ||||
>>> import numpy as np | |||||
>>> import mindspore.ops.operations as P | >>> import mindspore.ops.operations as P | ||||
>>> from mindspore.nn import Cell | >>> from mindspore.nn import Cell | ||||
>>> from mindspore import Tensor | >>> from mindspore import Tensor | ||||
@@ -149,8 +149,6 @@ class FastGradientMethod(GradientMethod): | |||||
is already equipped with loss function. Default: None. | is already equipped with loss function. Default: None. | ||||
Examples: | Examples: | ||||
>>> import numpy as np | |||||
>>> import mindspore.nn as nn | |||||
>>> from mindspore.nn import Cell, SoftmaxCrossEntropyWithLogits | >>> from mindspore.nn import Cell, SoftmaxCrossEntropyWithLogits | ||||
>>> from mindarmour.adv_robustness.attacks import FastGradientMethod | >>> from mindarmour.adv_robustness.attacks import FastGradientMethod | ||||
>>> class Net(Cell): | >>> class Net(Cell): | ||||
@@ -230,8 +228,6 @@ class RandomFastGradientMethod(FastGradientMethod): | |||||
ValueError: eps is smaller than alpha! | ValueError: eps is smaller than alpha! | ||||
Examples: | Examples: | ||||
>>> import numpy as np | |||||
>>> import mindspore.nn as nn | |||||
>>> from mindspore.nn import Cell, SoftmaxCrossEntropyWithLogits | >>> from mindspore.nn import Cell, SoftmaxCrossEntropyWithLogits | ||||
>>> from mindarmour.adv_robustness.attacks import RandomFastGradientMethod | >>> from mindarmour.adv_robustness.attacks import RandomFastGradientMethod | ||||
>>> class Net(Cell): | >>> class Net(Cell): | ||||
@@ -285,8 +281,6 @@ class FastGradientSignMethod(GradientMethod): | |||||
is already equipped with loss function. Default: None. | is already equipped with loss function. Default: None. | ||||
Examples: | Examples: | ||||
>>> import numpy as np | |||||
>>> import mindspore.nn as nn | |||||
>>> from mindspore.nn import Cell, SoftmaxCrossEntropyWithLogits | >>> from mindspore.nn import Cell, SoftmaxCrossEntropyWithLogits | ||||
>>> from mindarmour.adv_robustness.attacks import FastGradientSignMethod | >>> from mindarmour.adv_robustness.attacks import FastGradientSignMethod | ||||
>>> class Net(Cell): | >>> class Net(Cell): | ||||
@@ -362,8 +356,6 @@ class RandomFastGradientSignMethod(FastGradientSignMethod): | |||||
ValueError: eps is smaller than alpha! | ValueError: eps is smaller than alpha! | ||||
Examples: | Examples: | ||||
>>> import numpy as np | |||||
>>> import mindspore.nn as nn | |||||
>>> from mindspore.nn import Cell, SoftmaxCrossEntropyWithLogits | >>> from mindspore.nn import Cell, SoftmaxCrossEntropyWithLogits | ||||
>>> from mindarmour.adv_robustness.attacks import RandomFastGradientSignMethod | >>> from mindarmour.adv_robustness.attacks import RandomFastGradientSignMethod | ||||
>>> class Net(Cell): | >>> class Net(Cell): | ||||
@@ -412,8 +404,6 @@ class LeastLikelyClassMethod(FastGradientSignMethod): | |||||
is already equipped with loss function. Default: None. | is already equipped with loss function. Default: None. | ||||
Examples: | Examples: | ||||
>>> import numpy as np | |||||
>>> import mindspore.nn as nn | |||||
>>> from mindspore.nn import Cell, SoftmaxCrossEntropyWithLogits | >>> from mindspore.nn import Cell, SoftmaxCrossEntropyWithLogits | ||||
>>> from mindarmour.adv_robustness.attacks import LeastLikelyClassMethod | >>> from mindarmour.adv_robustness.attacks import LeastLikelyClassMethod | ||||
>>> class Net(Cell): | >>> class Net(Cell): | ||||
@@ -463,8 +453,6 @@ class RandomLeastLikelyClassMethod(FastGradientSignMethod): | |||||
ValueError: eps is smaller than alpha! | ValueError: eps is smaller than alpha! | ||||
Examples: | Examples: | ||||
>>> import numpy as np | |||||
>>> import mindspore.nn as nn | |||||
>>> from mindspore.nn import Cell, SoftmaxCrossEntropyWithLogits | >>> from mindspore.nn import Cell, SoftmaxCrossEntropyWithLogits | ||||
>>> from mindarmour.adv_robustness.attacks import RandomLeastLikelyClassMethod | >>> from mindarmour.adv_robustness.attacks import RandomLeastLikelyClassMethod | ||||
>>> class Net(Cell): | >>> class Net(Cell): | ||||
@@ -178,8 +178,6 @@ class BasicIterativeMethod(IterativeGradientMethod): | |||||
is already equipped with loss function. Default: None. | is already equipped with loss function. Default: None. | ||||
Examples: | Examples: | ||||
>>> import numpy as np | |||||
>>> import mindspore.nn as nn | |||||
>>> from mindspore.ops import operations as P | >>> from mindspore.ops import operations as P | ||||
>>> from mindspore.nn import Cell, SoftmaxCrossEntropyWithLogits | >>> from mindspore.nn import Cell, SoftmaxCrossEntropyWithLogits | ||||
>>> from mindarmour.adv_robustness.attacks import BasicIterativeMethod | >>> from mindarmour.adv_robustness.attacks import BasicIterativeMethod | ||||
@@ -282,8 +280,6 @@ class MomentumIterativeMethod(IterativeGradientMethod): | |||||
is already equipped with loss function. Default: None. | is already equipped with loss function. Default: None. | ||||
Examples: | Examples: | ||||
>>> import numpy as np | |||||
>>> import mindspore.nn as nn | |||||
>>> from mindspore.ops import operations as P | >>> from mindspore.ops import operations as P | ||||
>>> from mindspore.nn import Cell, SoftmaxCrossEntropyWithLogits | >>> from mindspore.nn import Cell, SoftmaxCrossEntropyWithLogits | ||||
>>> from mindarmour.adv_robustness.attacks import MomentumIterativeMethod | >>> from mindarmour.adv_robustness.attacks import MomentumIterativeMethod | ||||
@@ -428,8 +424,6 @@ class ProjectedGradientDescent(BasicIterativeMethod): | |||||
is already equipped with loss function. Default: None. | is already equipped with loss function. Default: None. | ||||
Examples: | Examples: | ||||
>>> import numpy as np | |||||
>>> import mindspore.nn as nn | |||||
>>> from mindspore.ops import operations as P | >>> from mindspore.ops import operations as P | ||||
>>> from mindspore.nn import Cell, SoftmaxCrossEntropyWithLogits | >>> from mindspore.nn import Cell, SoftmaxCrossEntropyWithLogits | ||||
>>> from mindarmour.adv_robustness.attacks import ProjectedGradientDescent | >>> from mindarmour.adv_robustness.attacks import ProjectedGradientDescent | ||||
@@ -526,8 +520,6 @@ class DiverseInputIterativeMethod(BasicIterativeMethod): | |||||
is already equipped with loss function. Default: None. | is already equipped with loss function. Default: None. | ||||
Examples: | Examples: | ||||
>>> import numpy as np | |||||
>>> import mindspore.nn as nn | |||||
>>> from mindspore.ops import operations as P | >>> from mindspore.ops import operations as P | ||||
>>> from mindspore.nn import Cell, SoftmaxCrossEntropyWithLogits | >>> from mindspore.nn import Cell, SoftmaxCrossEntropyWithLogits | ||||
>>> from mindarmour.adv_robustness.attacks import DiverseInputIterativeMethod | >>> from mindarmour.adv_robustness.attacks import DiverseInputIterativeMethod | ||||
@@ -583,8 +575,6 @@ class MomentumDiverseInputIterativeMethod(MomentumIterativeMethod): | |||||
is already equipped with loss function. Default: None. | is already equipped with loss function. Default: None. | ||||
Examples: | Examples: | ||||
>>> import numpy as np | |||||
>>> import mindspore.nn as nn | |||||
>>> from mindspore.ops import operations as P | >>> from mindspore.ops import operations as P | ||||
>>> from mindspore.nn import Cell, SoftmaxCrossEntropyWithLogits | >>> from mindspore.nn import Cell, SoftmaxCrossEntropyWithLogits | ||||
>>> from mindarmour.adv_robustness.attacks import MomentumDiverseInputIterativeMethod | >>> from mindarmour.adv_robustness.attacks import MomentumDiverseInputIterativeMethod | ||||
@@ -54,8 +54,6 @@ class JSMAAttack(Attack): | |||||
input labels are onehot-coded. Default: True. | input labels are onehot-coded. Default: True. | ||||
Examples: | Examples: | ||||
>>> import numpy as np | |||||
>>> import mindspore.nn as nn | |||||
>>> from mindspore.nn import Cell | >>> from mindspore.nn import Cell | ||||
>>> from mindarmour.adv_robustness.attacks import JSMAAttack | >>> from mindarmour.adv_robustness.attacks import JSMAAttack | ||||
>>> class Net(Cell): | >>> class Net(Cell): | ||||
@@ -54,7 +54,6 @@ class LBFGS(Attack): | |||||
input labels are onehot-coded. Default: False. | input labels are onehot-coded. Default: False. | ||||
Examples: | Examples: | ||||
>>> import numpy as np | |||||
>>> from mindarmour.adv_robustness.attacks import LBFGS | >>> from mindarmour.adv_robustness.attacks import LBFGS | ||||
>>> from tests.ut.python.utils.mock_net import Net | >>> from tests.ut.python.utils.mock_net import Net | ||||
>>> net = Net() | >>> net = Net() | ||||
@@ -36,10 +36,8 @@ class AdversarialDefense(Defense): | |||||
optimizer (Cell): Optimizer used to train the network. Default: None. | optimizer (Cell): Optimizer used to train the network. Default: None. | ||||
Examples: | Examples: | ||||
>>> import numpy as np | |||||
>>> from mindspore.nn.optim.momentum import Momentum | >>> from mindspore.nn.optim.momentum import Momentum | ||||
>>> from mindarmour.adv_robustness.defenses import AdversarialDefense | >>> from mindarmour.adv_robustness.defenses import AdversarialDefense | ||||
>>> from mindspore import nn | |||||
>>> from tests.ut.python.utils.mock_net import Net | >>> from tests.ut.python.utils.mock_net import Net | ||||
>>> net = Net() | >>> net = Net() | ||||
>>> lr = 0.001 | >>> lr = 0.001 | ||||
@@ -109,12 +107,10 @@ class AdversarialDefenseWithAttacks(AdversarialDefense): | |||||
ValueError: If replace_ratio is not between 0 and 1. | ValueError: If replace_ratio is not between 0 and 1. | ||||
Examples: | Examples: | ||||
>>> import numpy as np | |||||
>>> from mindspore.nn.optim.momentum import Momentum | >>> from mindspore.nn.optim.momentum import Momentum | ||||
>>> from mindarmour.adv_robustness.attacks import FastGradientSignMethod | >>> from mindarmour.adv_robustness.attacks import FastGradientSignMethod | ||||
>>> from mindarmour.adv_robustness.attacks import ProjectedGradientDescent | >>> from mindarmour.adv_robustness.attacks import ProjectedGradientDescent | ||||
>>> from mindarmour.adv_robustness.defenses import AdversarialDefenseWithAttacks | >>> from mindarmour.adv_robustness.defenses import AdversarialDefenseWithAttacks | ||||
>>> from mindspore import nn | |||||
>>> from tests.ut.python.utils.mock_net import Net | >>> from tests.ut.python.utils.mock_net import Net | ||||
>>> net = Net() | >>> net = Net() | ||||
>>> lr = 0.001 | >>> lr = 0.001 | ||||
@@ -157,9 +153,6 @@ class AdversarialDefenseWithAttacks(AdversarialDefense): | |||||
Returns: | Returns: | ||||
numpy.ndarray, loss of adversarial defense operation. | numpy.ndarray, loss of adversarial defense operation. | ||||
Examples: | |||||
>>> adv_defense.defense(inputs, labels) | |||||
""" | """ | ||||
inputs, labels = check_pair_numpy_param('inputs', inputs, 'labels', | inputs, labels = check_pair_numpy_param('inputs', inputs, 'labels', | ||||
labels) | labels) | ||||
@@ -200,12 +193,10 @@ class EnsembleAdversarialDefense(AdversarialDefenseWithAttacks): | |||||
ValueError: If replace_ratio is not between 0 and 1. | ValueError: If replace_ratio is not between 0 and 1. | ||||
Examples: | Examples: | ||||
>>> import numpy as np | |||||
>>> from mindspore.nn.optim.momentum import Momentum | >>> from mindspore.nn.optim.momentum import Momentum | ||||
>>> from mindarmour.adv_robustness.attacks import FastGradientSignMethod | >>> from mindarmour.adv_robustness.attacks import FastGradientSignMethod | ||||
>>> from mindarmour.adv_robustness.attacks import ProjectedGradientDescent | >>> from mindarmour.adv_robustness.attacks import ProjectedGradientDescent | ||||
>>> from mindarmour.adv_robustness.defenses import EnsembleAdversarialDefense | >>> from mindarmour.adv_robustness.defenses import EnsembleAdversarialDefense | ||||
>>> from mindspore import nn | |||||
>>> from tests.ut.python.utils.mock_net import Net | >>> from tests.ut.python.utils.mock_net import Net | ||||
>>> net = Net() | >>> net = Net() | ||||
>>> lr = 0.001 | >>> lr = 0.001 | ||||
@@ -36,10 +36,8 @@ class NaturalAdversarialDefense(AdversarialDefenseWithAttacks): | |||||
eps (float): Step size of the attack method(FGSM). Default: 0.1. | eps (float): Step size of the attack method(FGSM). Default: 0.1. | ||||
Examples: | Examples: | ||||
>>> import numpy as np | |||||
>>> from mindspore.nn.optim.momentum import Momentum | >>> from mindspore.nn.optim.momentum import Momentum | ||||
>>> from mindarmour.adv_robustness.defenses import NaturalAdversarialDefense | >>> from mindarmour.adv_robustness.defenses import NaturalAdversarialDefense | ||||
>>> from mindspore import nn | |||||
>>> from tests.ut.python.utils.mock_net import Net | >>> from tests.ut.python.utils.mock_net import Net | ||||
>>> net = Net() | >>> net = Net() | ||||
>>> lr = 0.001 | >>> lr = 0.001 | ||||
@@ -41,10 +41,8 @@ class ProjectedAdversarialDefense(AdversarialDefenseWithAttacks): | |||||
norm_level (str): Norm type. 'inf' or 'l2'. Default: 'inf'. | norm_level (str): Norm type. 'inf' or 'l2'. Default: 'inf'. | ||||
Examples: | Examples: | ||||
>>> import numpy as np | |||||
>>> from mindspore.nn.optim.momentum import Momentum | >>> from mindspore.nn.optim.momentum import Momentum | ||||
>>> from mindarmour.adv_robustness.defenses import ProjectedAdversarialDefense | >>> from mindarmour.adv_robustness.defenses import ProjectedAdversarialDefense | ||||
>>> from mindspore import nn | |||||
>>> from tests.ut.python.utils.mock_net import Net | >>> from tests.ut.python.utils.mock_net import Net | ||||
>>> net = Net() | >>> net = Net() | ||||
>>> lr = 0.001 | >>> lr = 0.001 | ||||
@@ -73,11 +73,9 @@ class SimilarityDetector(Detector): | |||||
Default: 0.001 | Default: 0.001 | ||||
Examples: | Examples: | ||||
>>> import numpy as np | |||||
>>> from mindspore.ops.operations import Add | >>> from mindspore.ops.operations import Add | ||||
>>> from mindspore.nn import Cell | >>> from mindspore.nn import Cell | ||||
>>> from mindspore import Model | >>> from mindspore import Model | ||||
>>> from mindspore import context | |||||
>>> from mindarmour.adv_robustness.detectors import SimilarityDetector | >>> from mindarmour.adv_robustness.detectors import SimilarityDetector | ||||
>>> class EncoderNet(Cell): | >>> class EncoderNet(Cell): | ||||
... def __init__(self, encode_dim): | ... def __init__(self, encode_dim): | ||||
@@ -34,11 +34,9 @@ class EnsembleDetector(Detector): | |||||
policy (str): Decision policy, could be 'vote', 'all' or 'any'. | policy (str): Decision policy, could be 'vote', 'all' or 'any'. | ||||
Default: 'vote' | Default: 'vote' | ||||
Examples: | Examples: | ||||
>>> import numpy as np | |||||
>>> from mindspore.ops.operations import Add | >>> from mindspore.ops.operations import Add | ||||
>>> from mindspore.nn import Cell | >>> from mindspore.nn import Cell | ||||
>>> from mindspore import Model | >>> from mindspore import Model | ||||
>>> from mindspore import context | |||||
>>> from mindarmour.adv_robustness.detectors import ErrorBasedDetector | >>> from mindarmour.adv_robustness.detectors import ErrorBasedDetector | ||||
>>> from mindarmour.adv_robustness.detectors import RegionBasedDetector | >>> from mindarmour.adv_robustness.detectors import RegionBasedDetector | ||||
>>> from mindarmour.adv_robustness.detectors import EnsembleDetector | >>> from mindarmour.adv_robustness.detectors import EnsembleDetector | ||||
@@ -48,11 +48,9 @@ class ErrorBasedDetector(Detector): | |||||
bounds (tuple): (clip_min, clip_max). Default: (0.0, 1.0). | bounds (tuple): (clip_min, clip_max). Default: (0.0, 1.0). | ||||
Examples: | Examples: | ||||
>>> import numpy as np | |||||
>>> from mindspore.ops.operations import Add | >>> from mindspore.ops.operations import Add | ||||
>>> from mindspore.nn import Cell | >>> from mindspore.nn import Cell | ||||
>>> from mindspore import Model | >>> from mindspore import Model | ||||
>>> from mindspore import context | |||||
>>> from mindarmour.adv_robustness.detectors import ErrorBasedDetector | >>> from mindarmour.adv_robustness.detectors import ErrorBasedDetector | ||||
>>> class Net(Cell): | >>> class Net(Cell): | ||||
... def __init__(self): | ... def __init__(self): | ||||
@@ -183,11 +181,9 @@ class DivergenceBasedDetector(ErrorBasedDetector): | |||||
In form of (clip_min, clip_max). Default: (0.0, 1.0). | In form of (clip_min, clip_max). Default: (0.0, 1.0). | ||||
Examples: | Examples: | ||||
>>> import numpy as np | |||||
>>> import mindspore.ops.operations as P | >>> import mindspore.ops.operations as P | ||||
>>> from mindspore.nn import Cell | >>> from mindspore.nn import Cell | ||||
>>> from mindspore import Model | >>> from mindspore import Model | ||||
>>> from mindspore import context | |||||
>>> from mindarmour.adv_robustness.detectors import DivergenceBasedDetector | >>> from mindarmour.adv_robustness.detectors import DivergenceBasedDetector | ||||
>>> class PredNet(Cell): | >>> class PredNet(Cell): | ||||
... def __init__(self): | ... def __init__(self): | ||||
@@ -52,11 +52,9 @@ class RegionBasedDetector(Detector): | |||||
input labels are one-hot-encoded. Default: False. | input labels are one-hot-encoded. Default: False. | ||||
Examples: | Examples: | ||||
>>> import numpy as np | |||||
>>> from mindspore.ops.operations import Add | >>> from mindspore.ops.operations import Add | ||||
>>> from mindspore.nn import Cell | >>> from mindspore.nn import Cell | ||||
>>> from mindspore import Model | >>> from mindspore import Model | ||||
>>> from mindspore import context | |||||
>>> from mindarmour.adv_robustness.detectors import RegionBasedDetector | >>> from mindarmour.adv_robustness.detectors import RegionBasedDetector | ||||
>>> class Net(Cell): | >>> class Net(Cell): | ||||
... def __init__(self): | ... def __init__(self): | ||||
@@ -49,11 +49,9 @@ class SpatialSmoothing(Detector): | |||||
benign samples. Default: 0.05. | benign samples. Default: 0.05. | ||||
Examples: | Examples: | ||||
>>> import numpy as np | |||||
>>> import mindspore.ops.operations as P | >>> import mindspore.ops.operations as P | ||||
>>> from mindspore.nn import Cell | >>> from mindspore.nn import Cell | ||||
>>> from mindspore import Model | >>> from mindspore import Model | ||||
>>> from mindspore import context | |||||
>>> from mindarmour.adv_robustness.detectors import SpatialSmoothing | >>> from mindarmour.adv_robustness.detectors import SpatialSmoothing | ||||
>>> class Net(Cell): | >>> class Net(Cell): | ||||
... def __init__(self): | ... def __init__(self): | ||||
@@ -47,7 +47,6 @@ class AttackEvaluate: | |||||
ValueError: If target_label is None when targeted is True. | ValueError: If target_label is None when targeted is True. | ||||
Examples: | Examples: | ||||
>>> import numpy as np | |||||
>>> from mindarmour.adv_robustness.evaluations import AttackEvaluate | >>> from mindarmour.adv_robustness.evaluations import AttackEvaluate | ||||
>>> x = np.random.normal(size=(3, 512, 512, 3)) | >>> x = np.random.normal(size=(3, 512, 512, 3)) | ||||
>>> adv_x = np.random.normal(size=(3, 512, 512, 3)) | >>> adv_x = np.random.normal(size=(3, 512, 512, 3)) | ||||
@@ -57,7 +57,6 @@ class BlackDefenseEvaluate: | |||||
max_queries (int): Attack budget, the maximum number of queries. | max_queries (int): Attack budget, the maximum number of queries. | ||||
Examples: | Examples: | ||||
>>> import numpy as np | |||||
>>> from mindarmour.adv_robustness.evaluations import BlackDefenseEvaluate | >>> from mindarmour.adv_robustness.evaluations import BlackDefenseEvaluate | ||||
>>> raw_preds = np.array([[0.1, 0.1, 0.2, 0.6], | >>> raw_preds = np.array([[0.1, 0.1, 0.2, 0.6], | ||||
... [0.1, 0.7, 0.0, 0.2], | ... [0.1, 0.7, 0.0, 0.2], | ||||
@@ -39,9 +39,7 @@ class DefenseEvaluate: | |||||
one-dimension array whose size is raw_preds.shape[0]. | one-dimension array whose size is raw_preds.shape[0]. | ||||
Examples: | Examples: | ||||
>>> import numpy as np | |||||
>>> from mindarmour.adv_robustness.evaluations import DefenseEvaluate | >>> from mindarmour.adv_robustness.evaluations import DefenseEvaluate | ||||
>>> raw_preds = np.array([[0.1, 0.1, 0.2, 0.6], | >>> raw_preds = np.array([[0.1, 0.1, 0.2, 0.6], | ||||
... [0.1, 0.7, 0.0, 0.2], | ... [0.1, 0.7, 0.0, 0.2], | ||||
... [0.8, 0.1, 0.0, 0.1]]) | ... [0.8, 0.1, 0.0, 0.1]]) | ||||
@@ -46,7 +46,6 @@ class RadarMetric: | |||||
ValueError: If scale not in ['hide', 'norm', 'sparse', 'dense']. | ValueError: If scale not in ['hide', 'norm', 'sparse', 'dense']. | ||||
Examples: | Examples: | ||||
>>> import numpy as np | |||||
>>> from mindarmour.adv_robustness.evaluations import RadarMetric | >>> from mindarmour.adv_robustness.evaluations import RadarMetric | ||||
>>> metrics_name = ['MR', 'ACAC', 'ASS', 'NTE', 'ACTC'] | >>> metrics_name = ['MR', 'ACAC', 'ASS', 'NTE', 'ACTC'] | ||||
>>> def_metrics = [0.9, 0.85, 0.6, 0.7, 0.8] | >>> def_metrics = [0.9, 0.85, 0.6, 0.7, 0.8] | ||||
@@ -34,7 +34,12 @@ TAG = 'NoiseMechanism' | |||||
class ClipMechanismsFactory: | class ClipMechanismsFactory: | ||||
""" Factory class of clip mechanisms""" | |||||
""" | |||||
Factory class of clip mechanisms | |||||
For details, please check `Tutorial <https://mindspore.cn/mindarmour/docs/zh-CN/master/protect_user_privacy_with_differential_privacy.html#%E5%B7%AE%E5%88%86%E9%9A%90%E7%A7%81>`_ | |||||
""" | |||||
def __init__(self): | def __init__(self): | ||||
pass | pass | ||||
@@ -63,6 +68,9 @@ class ClipMechanismsFactory: | |||||
Mechanisms, class of noise generated Mechanism. | Mechanisms, class of noise generated Mechanism. | ||||
Examples: | Examples: | ||||
>>> from mindspore import Tensor | |||||
>>> from mindspore.common import dtype as mstype | |||||
>>> from mindarmour.privacy.diff_privacy import ClipMechanismsFactory | |||||
>>> decay_policy = 'Linear' | >>> decay_policy = 'Linear' | ||||
>>> beta = Tensor(0.5, mstype.float32) | >>> beta = Tensor(0.5, mstype.float32) | ||||
>>> norm_bound = Tensor(1.0, mstype.float32) | >>> norm_bound = Tensor(1.0, mstype.float32) | ||||
@@ -71,10 +79,10 @@ class ClipMechanismsFactory: | |||||
>>> target_unclipped_quantile = 0.9 | >>> target_unclipped_quantile = 0.9 | ||||
>>> clip_mechanism = ClipMechanismsFactory() | >>> clip_mechanism = ClipMechanismsFactory() | ||||
>>> ada_clip = clip_mechanism.create('Gaussian', | >>> ada_clip = clip_mechanism.create('Gaussian', | ||||
... decay_policy=decay_policy, | |||||
... learning_rate=learning_rate, | |||||
... target_unclipped_quantile=target_unclipped_quantile, | |||||
... fraction_stddev=beta_stddev) | |||||
... decay_policy=decay_policy, | |||||
... learning_rate=learning_rate, | |||||
... target_unclipped_quantile=target_unclipped_quantile, | |||||
... fraction_stddev=beta_stddev) | |||||
>>> next_norm_bound = ada_clip(beta, norm_bound) | >>> next_norm_bound = ada_clip(beta, norm_bound) | ||||
""" | """ | ||||
@@ -86,8 +94,11 @@ class ClipMechanismsFactory: | |||||
class NoiseMechanismsFactory: | class NoiseMechanismsFactory: | ||||
""" Factory class of noise mechanisms""" | |||||
""" Factory class of noise mechanisms | |||||
For details, please check `Tutorial <https://mindspore.cn/mindarmour/docs/zh-CN/master/protect_user_privacy_with_differential_privacy.html#%E5%B7%AE%E5%88%86%E9%9A%90%E7%A7%81>`_ | |||||
""" | |||||
def __init__(self): | def __init__(self): | ||||
pass | pass | ||||
@@ -117,34 +128,13 @@ class NoiseMechanismsFactory: | |||||
Mechanisms, class of noise generated Mechanism. | Mechanisms, class of noise generated Mechanism. | ||||
Examples: | Examples: | ||||
>>> from mindarmour.privacy.diff_privacy import NoiseMechanismsFactory | |||||
>>> norm_bound = 1.0 | >>> norm_bound = 1.0 | ||||
>>> initial_noise_multiplier = 1.0 | >>> initial_noise_multiplier = 1.0 | ||||
>>> network = LeNet5() | |||||
>>> batch_size = 32 | |||||
>>> batches = 128 | |||||
>>> epochs = 1 | |||||
>>> loss = nn.SoftmaxCrossEntropyWithLogits(sparse=True) | |||||
>>> noise_mech = NoiseMechanismsFactory().create('Gaussian', | |||||
... norm_bound=norm_bound, | |||||
... initial_noise_multiplier=initial_noise_multiplier) | |||||
>>> clip_mech = ClipMechanismsFactory().create('Gaussian', | |||||
... decay_policy='Linear', | |||||
... learning_rate=0.001, | |||||
... target_unclipped_quantile=0.9, | |||||
... fraction_stddev=0.01) | |||||
>>> net_opt = nn.Momentum(network.trainable_params(), learning_rate=0.1, | |||||
... momentum=0.9) | |||||
>>> model = DPModel(micro_batches=2, | |||||
... clip_mech=clip_mech, | |||||
... norm_bound=norm_bound, | |||||
... noise_mech=noise_mech, | |||||
... network=network, | |||||
... loss_fn=loss, | |||||
... optimizer=net_opt, | |||||
... metrics=None) | |||||
>>> ms_ds = ds.GeneratorDataset(dataset_generator, | |||||
... ['data', 'label']) | |||||
>>> model.train(epochs, ms_ds, dataset_sink_mode=False) | |||||
>>> noise_mechanism = NoiseMechanismsFactory() | |||||
>>> clip = noise_mechanism.create('Gaussian', | |||||
... norm_bound=norm_bound, | |||||
... initial_noise_multiplier=initial_noise_multiplier) | |||||
""" | """ | ||||
if mech_name == 'Gaussian': | if mech_name == 'Gaussian': | ||||
return NoiseGaussianRandom(norm_bound=norm_bound, | return NoiseGaussianRandom(norm_bound=norm_bound, | ||||
@@ -192,6 +182,9 @@ class NoiseGaussianRandom(_Mechanisms): | |||||
Tensor, generated noise with shape like given gradients. | Tensor, generated noise with shape like given gradients. | ||||
Examples: | Examples: | ||||
>>> from mindspore import Tensor | |||||
>>> from mindspore.common import dtype as mstype | |||||
>>> from mindarmour.privacy.diff_privacy import NoiseGaussianRandom | |||||
>>> gradients = Tensor([0.2, 0.9], mstype.float32) | >>> gradients = Tensor([0.2, 0.9], mstype.float32) | ||||
>>> norm_bound = 0.1 | >>> norm_bound = 0.1 | ||||
>>> initial_noise_multiplier = 1.0 | >>> initial_noise_multiplier = 1.0 | ||||
@@ -199,7 +192,6 @@ class NoiseGaussianRandom(_Mechanisms): | |||||
>>> decay_policy = None | >>> decay_policy = None | ||||
>>> net = NoiseGaussianRandom(norm_bound, initial_noise_multiplier, seed, decay_policy) | >>> net = NoiseGaussianRandom(norm_bound, initial_noise_multiplier, seed, decay_policy) | ||||
>>> res = net(gradients) | >>> res = net(gradients) | ||||
>>> print(res) | |||||
""" | """ | ||||
def __init__(self, norm_bound=1.0, initial_noise_multiplier=1.0, seed=0, decay_policy=None): | def __init__(self, norm_bound=1.0, initial_noise_multiplier=1.0, seed=0, decay_policy=None): | ||||
@@ -259,6 +251,9 @@ class NoiseAdaGaussianRandom(NoiseGaussianRandom): | |||||
Tensor, generated noise with shape like given gradients. | Tensor, generated noise with shape like given gradients. | ||||
Examples: | Examples: | ||||
>>> from mindspore import Tensor | |||||
>>> from mindspore.common import dtype as mstype | |||||
>>> from mindarmour.privacy.diff_privacy import NoiseAdaGaussianRandom | |||||
>>> gradients = Tensor([0.2, 0.9], mstype.float32) | >>> gradients = Tensor([0.2, 0.9], mstype.float32) | ||||
>>> norm_bound = 1.0 | >>> norm_bound = 1.0 | ||||
>>> initial_noise_multiplier = 1.0 | >>> initial_noise_multiplier = 1.0 | ||||
@@ -267,7 +262,6 @@ class NoiseAdaGaussianRandom(NoiseGaussianRandom): | |||||
>>> decay_policy = "Exp" | >>> decay_policy = "Exp" | ||||
>>> net = NoiseAdaGaussianRandom(norm_bound, initial_noise_multiplier, seed, noise_decay_rate, decay_policy) | >>> net = NoiseAdaGaussianRandom(norm_bound, initial_noise_multiplier, seed, noise_decay_rate, decay_policy) | ||||
>>> res = net(gradients) | >>> res = net(gradients) | ||||
>>> print(res) | |||||
""" | """ | ||||
def __init__(self, norm_bound=1.0, initial_noise_multiplier=1.0, seed=0, noise_decay_rate=6e-6, decay_policy='Exp'): | def __init__(self, norm_bound=1.0, initial_noise_multiplier=1.0, seed=0, noise_decay_rate=6e-6, decay_policy='Exp'): | ||||
@@ -379,6 +373,9 @@ class AdaClippingWithGaussianRandom(Cell): | |||||
Tensor, undated norm clip . | Tensor, undated norm clip . | ||||
Examples: | Examples: | ||||
>>> from mindspore import Tensor | |||||
>>> from mindspore.common import dtype as mstype | |||||
>>> from mindarmour.privacy.diff_privacy import AdaClippingWithGaussianRandom | |||||
>>> decay_policy = 'Linear' | >>> decay_policy = 'Linear' | ||||
>>> beta = Tensor(0.5, mstype.float32) | >>> beta = Tensor(0.5, mstype.float32) | ||||
>>> norm_bound = Tensor(1.0, mstype.float32) | >>> norm_bound = Tensor(1.0, mstype.float32) | ||||
@@ -38,6 +38,8 @@ class PrivacyMonitorFactory: | |||||
""" | """ | ||||
Create a privacy monitor class. | Create a privacy monitor class. | ||||
For details, please check `Tutorial <https://mindspore.cn/mindarmour/docs/zh-CN/master/protect_user_privacy_with_differential_privacy.html#%E5%B7%AE%E5%88%86%E9%9A%90%E7%A7%81>`_ | |||||
Args: | Args: | ||||
policy (str): Monitor policy, 'rdp' and 'zcdp' are supported | policy (str): Monitor policy, 'rdp' and 'zcdp' are supported | ||||
by now. If policy is 'rdp', the monitor will compute the | by now. If policy is 'rdp', the monitor will compute the | ||||
@@ -55,8 +57,8 @@ class PrivacyMonitorFactory: | |||||
Callback, a privacy monitor. | Callback, a privacy monitor. | ||||
Examples: | Examples: | ||||
>>> rdp = PrivacyMonitorFactory.create(policy='rdp', | |||||
>>> num_samples=60000, batch_size=32) | |||||
>>> from mindarmour.privacy.diff_privacy import PrivacyMonitorFactory | |||||
>>> rdp = PrivacyMonitorFactory.create(policy='rdp', num_samples=60000, batch_size=32) | |||||
""" | """ | ||||
if policy == 'rdp': | if policy == 'rdp': | ||||
return RDPMonitor(*args, **kwargs) | return RDPMonitor(*args, **kwargs) | ||||
@@ -72,6 +74,8 @@ class RDPMonitor(Callback): | |||||
mechanism is said to have ε'-Renyi differential privacy of order α, it | mechanism is said to have ε'-Renyi differential privacy of order α, it | ||||
also satisfies conventional differential privacy (ε, δ) as below: | also satisfies conventional differential privacy (ε, δ) as below: | ||||
For details, please check `Tutorial <https://mindspore.cn/mindarmour/docs/zh-CN/master/protect_user_privacy_with_differential_privacy.html#%E5%B7%AE%E5%88%86%E9%9A%90%E7%A7%81>`_ | |||||
.. math:: | .. math:: | ||||
(ε'+\frac{log(1/δ)}{α-1}, δ) | (ε'+\frac{log(1/δ)}{α-1}, δ) | ||||
@@ -114,20 +118,8 @@ class RDPMonitor(Callback): | |||||
to device after each step training. Default: False. | to device after each step training. Default: False. | ||||
Examples: | Examples: | ||||
>>> network = Net() | |||||
>>> net_loss = nn.SoftmaxCrossEntropyWithLogits() | |||||
>>> epochs = 2 | |||||
>>> norm_clip = 1.0 | |||||
>>> initial_noise_multiplier = 1.5 | |||||
>>> mech = NoiseMechanismsFactory().create('AdaGaussian', | |||||
>>> norm_bound=norm_clip, initial_noise_multiplier=initial_noise_multiplier) | |||||
>>> net_opt = nn.Momentum(network.trainable_params(), 0.01, 0.9) | |||||
>>> model = DPModel(micro_batches=2, norm_clip=norm_clip, | |||||
>>> mech=mech, network=network, loss_fn=loss, optimizer=net_opt, metrics=None) | |||||
>>> rdp = PrivacyMonitorFactory.create(policy='rdp', | |||||
>>> num_samples=60000, batch_size=256, | |||||
>>> initial_noise_multiplier=initial_noise_multiplier) | |||||
>>> model.train(epochs, ds, callbacks=[rdp], dataset_sink_mode=False) | |||||
>>> from mindarmour.privacy.diff_privacy import PrivacyMonitorFactory | |||||
>>> rdp = PrivacyMonitorFactory.create(policy='rdp', num_samples=100, batch_size=32) | |||||
""" | """ | ||||
def __init__(self, num_samples, batch_size, initial_noise_multiplier=1.5, | def __init__(self, num_samples, batch_size, initial_noise_multiplier=1.5, | ||||
@@ -206,8 +198,7 @@ class RDPMonitor(Callback): | |||||
int, the recommended maximum training epochs. | int, the recommended maximum training epochs. | ||||
Examples: | Examples: | ||||
>>> rdp = PrivacyMonitorFactory.create(policy='rdp', | |||||
>>> num_samples=60000, batch_size=32) | |||||
>>> rdp = PrivacyMonitorFactory.create(policy='rdp', num_samples=100, batch_size=32) | |||||
>>> suggest_epoch = rdp.max_epoch_suggest() | >>> suggest_epoch = rdp.max_epoch_suggest() | ||||
""" | """ | ||||
if self._target_delta is not None and self._max_eps is None: | if self._target_delta is not None and self._max_eps is None: | ||||
@@ -376,6 +367,8 @@ class ZCDPMonitor(Callback): | |||||
if a randomized mechanism is said to have ρ-zCDP, it also satisfies | if a randomized mechanism is said to have ρ-zCDP, it also satisfies | ||||
conventional differential privacy (ε, δ) as below: | conventional differential privacy (ε, δ) as below: | ||||
For details, please check `Tutorial <https://mindspore.cn/mindarmour/docs/zh-CN/master/protect_user_privacy_with_differential_privacy.html#%E5%B7%AE%E5%88%86%E9%9A%90%E7%A7%81>`_ | |||||
.. math:: | .. math:: | ||||
(ρ+2\sqrt{ρ*log(1/δ)}, δ) | (ρ+2\sqrt{ρ*log(1/δ)}, δ) | ||||
@@ -407,20 +400,11 @@ class ZCDPMonitor(Callback): | |||||
to device after each step training. Default: False. | to device after each step training. Default: False. | ||||
Examples: | Examples: | ||||
>>> network = Net() | |||||
>>> net_loss = nn.SoftmaxCrossEntropyWithLogits() | |||||
>>> epochs = 2 | |||||
>>> norm_clip = 1.0 | |||||
>>> initial_noise_multiplier = 1.5 | |||||
>>> mech = NoiseMechanismsFactory().create('AdaGaussian', | |||||
>>> norm_bound=norm_clip, initial_noise_multiplier=initial_noise_multiplier) | |||||
>>> net_opt = nn.Momentum(network.trainable_params(), 0.01, 0.9) | |||||
>>> model = DPModel(micro_batches=2, norm_clip=norm_clip, | |||||
>>> mech=mech, network=network, loss_fn=loss, optimizer=net_opt, metrics=None) | |||||
>>> from mindarmour.privacy.diff_privacy import PrivacyMonitorFactory | |||||
>>> zcdp = PrivacyMonitorFactory.create(policy='zcdp', | >>> zcdp = PrivacyMonitorFactory.create(policy='zcdp', | ||||
>>> num_samples=60000, batch_size=256, | |||||
>>> initial_noise_multiplier=initial_noise_multiplier) | |||||
>>> model.train(epochs, ds, callbacks=[zcdp], dataset_sink_mode=False) | |||||
... num_samples=100, | |||||
... batch_size=32, | |||||
... initial_noise_multiplier=1.5) | |||||
""" | """ | ||||
def __init__(self, num_samples, batch_size, initial_noise_multiplier=1.5, | def __init__(self, num_samples, batch_size, initial_noise_multiplier=1.5, | ||||
@@ -62,6 +62,9 @@ class DPOptimizerClassFactory: | |||||
Optimizer, Optimizer class. | Optimizer, Optimizer class. | ||||
Examples: | Examples: | ||||
>>> from mindarmour.privacy.diff_privacy import DPOptimizerClassFactory | |||||
>>> from tests.ut.python.utils.mock_net import Net | |||||
>>> network = Net() | |||||
>>> GaussianSGD = DPOptimizerClassFactory(micro_batches=2) | >>> GaussianSGD = DPOptimizerClassFactory(micro_batches=2) | ||||
>>> GaussianSGD.set_mechanisms('Gaussian', norm_bound=1.0, initial_noise_multiplier=1.5) | >>> GaussianSGD.set_mechanisms('Gaussian', norm_bound=1.0, initial_noise_multiplier=1.5) | ||||
>>> net_opt = GaussianSGD.create('Momentum')(params=network.trainable_params(), | >>> net_opt = GaussianSGD.create('Momentum')(params=network.trainable_params(), | ||||
@@ -69,6 +69,8 @@ class DPModel(Model): | |||||
""" | """ | ||||
This class is overload mindspore.train.model.Model. | This class is overload mindspore.train.model.Model. | ||||
For details, please check `Tutorial <https://mindspore.cn/mindarmour/docs/zh-CN/master/protect_user_privacy_with_differential_privacy.html#%E5%B7%AE%E5%88%86%E9%9A%90%E7%A7%81>`_ | |||||
Args: | Args: | ||||
micro_batches (int): The number of small batches split from an original | micro_batches (int): The number of small batches split from an original | ||||
batch. Default: 2. | batch. Default: 2. | ||||
@@ -83,37 +85,6 @@ class DPModel(Model): | |||||
ValueError: If DPOptimizer and noise_mecn are both None or not None. | ValueError: If DPOptimizer and noise_mecn are both None or not None. | ||||
ValueError: If noise_mech or DPOtimizer's mech method is adaptive while clip_mech is not None. | ValueError: If noise_mech or DPOtimizer's mech method is adaptive while clip_mech is not None. | ||||
Examples: | |||||
>>> norm_bound = 1.0 | |||||
>>> initial_noise_multiplier = 0.01 | |||||
>>> network = LeNet5() | |||||
>>> batch_size = 32 | |||||
>>> batches = 128 | |||||
>>> epochs = 1 | |||||
>>> micro_batches = 2 | |||||
>>> loss = nn.SoftmaxCrossEntropyWithLogits(sparse=True) | |||||
>>> factory_opt = DPOptimizerClassFactory(micro_batches=micro_batches) | |||||
>>> factory_opt.set_mechanisms('Gaussian', | |||||
... norm_bound=norm_bound, | |||||
... initial_noise_multiplier=initial_noise_multiplier) | |||||
>>> net_opt = factory_opt.create('Momentum')(network.trainable_params(), | |||||
... learning_rate=0.1, momentum=0.9) | |||||
>>> clip_mech = ClipMechanismsFactory().create('Gaussian', | |||||
... decay_policy='Linear', | |||||
... learning_rate=0.01, | |||||
... target_unclipped_quantile=0.9, | |||||
... fraction_stddev=0.01) | |||||
>>> model = DPModel(micro_batches=micro_batches, | |||||
... norm_bound=norm_bound, | |||||
... clip_mech=clip_mech, | |||||
... noise_mech=None, | |||||
... network=network, | |||||
... loss_fn=loss, | |||||
... optimizer=net_opt, | |||||
... metrics=None) | |||||
>>> ms_ds = ds.GeneratorDataset(dataset_generator, | |||||
... ['data', 'label']) | |||||
>>> model.train(epochs, ms_ds, dataset_sink_mode=False) | |||||
""" | """ | ||||
def __init__(self, micro_batches=2, norm_bound=1.0, noise_mech=None, | def __init__(self, micro_batches=2, norm_bound=1.0, noise_mech=None, | ||||