def __init__(self, model, suppress_ctrl): super(SuppressMasker, self).__init__() self._model = check_param_type('model', model, SuppressModel) self._suppress_ctrl = check_param_type('suppress_ctrl', suppress_ctrl, SuppressCtrl)
def __init__(self, model, pop_size=6, mutation_rate=0.005, per_bounds=0.15, max_steps=1000, step_size=0.20, temp=0.3, bounds=(0, 1.0), adaptive=False, sparse=True): super(GeneticAttack, self).__init__() self._model = check_model('model', model, BlackModel) self._per_bounds = check_value_positive('per_bounds', per_bounds) self._pop_size = check_int_positive('pop_size', pop_size) self._step_size = check_value_positive('step_size', step_size) self._temp = check_value_positive('temp', temp) self._max_steps = check_int_positive('max_steps', max_steps) self._mutation_rate = check_value_positive('mutation_rate', mutation_rate) self._adaptive = check_param_type('adaptive', adaptive, bool) self._bounds = check_param_multi_types('bounds', bounds, [list, tuple]) for b in self._bounds: _ = check_param_multi_types('bound', b, [int, float]) # initial global optimum fitness value self._best_fit = -1 # count times of no progress self._plateau_times = 0 # count times of changing attack step self._adap_times = 0 self._sparse = check_param_type('sparse', sparse, bool)
def eval(self, dataset_train, dataset_test, metrics): """ Evaluate the different privacy of the target model. Evaluation indicators shall be specified by metrics. Args: dataset_train (mindspore.dataset): The training dataset for the target model. dataset_test (mindspore.dataset): The test dataset for the target model. metrics (Union[list, tuple]): Evaluation indicators. The value of metrics must be in ["precision", "accuracy", "recall"]. Default: ["precision"]. Returns: list, each element contains an evaluation indicator for the attack model. """ check_param_type("dataset_train", dataset_train, Dataset) check_param_type("dataset_test", dataset_test, Dataset) check_param_multi_types("metrics", metrics, (list, tuple)) metrics = set(metrics) metrics_list = {"precision", "accuracy", "recall"} if not metrics <= metrics_list: msg = "Element in 'metrics' must be in {}, but got {}.".format( metrics_list, metrics) LOGGER.error(TAG, msg) raise ValueError(msg) result = [] features, labels = self._transform(dataset_train, dataset_test) for attacker in self._attack_list: pred = attacker.predict(features) item = {} for option in metrics: item[option] = _eval_info(pred, labels, option) result.append(item) return result
def train(self, dataset_train, dataset_test, attack_config): """ Depending on the configuration, use the input dataset to train the attack model. Save the attack model to self._attack_list. Args: dataset_train (mindspore.dataset): The training dataset for the target model. dataset_test (mindspore.dataset): The test set for the target model. attack_config (Union[list, tuple]): Parameter setting for the attack model. The format is [{"method": "knn", "params": {"n_neighbors": [3, 5, 7]}}, {"method": "lr", "params": {"C": np.logspace(-4, 2, 10)}}]. The support methods are knn, lr, mlp and rf, and the params of each method must within the range of changeable parameters. Tips of params implement can be found below: `KNN <https://scikit-learn.org/stable/modules/generated/sklearn.neighbors.KNeighborsClassifier.html>`_, `LR <https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LogisticRegression.html>`_, `RF <https://scikit-learn.org/stable/modules/generated/sklearn.ensemble.RandomForestClassifier.html>`_, `MLP <https://scikit-learn.org/stable/modules/generated/sklearn.neural_network.MLPRegressor.html>`_. Raises: KeyError: If any config in attack_config doesn't have keys {"method", "params"}. NameError: If the method(case insensitive) in attack_config is not in ["lr", "knn", "rf", "mlp"]. """ check_param_type("dataset_train", dataset_train, Dataset) check_param_type("dataset_test", dataset_test, Dataset) check_param_multi_types("attack_config", attack_config, (list, tuple)) verify_config_params(attack_config) features, labels = self._transform(dataset_train, dataset_test) for config in attack_config: self._attack_list.append( get_attack_model(features, labels, config, n_jobs=self._n_jobs))
def __init__(self, norm_bound=1.5, initial_noise_multiplier=5.0, alpha=6e-4, decay_policy='Step'): super(AdaGaussianRandom, self).__init__() initial_noise_multiplier = check_value_positive( 'initial_noise_multiplier', initial_noise_multiplier) initial_noise_multiplier = Tensor( np.array(initial_noise_multiplier, np.float32)) self._initial_noise_multiplier = Parameter( initial_noise_multiplier, name='initial_noise_multiplier') self._noise_multiplier = Parameter(initial_noise_multiplier, name='noise_multiplier') norm_bound = check_value_positive('norm_bound', norm_bound) self._norm_bound = Tensor(np.array(norm_bound, np.float32)) alpha = check_param_type('alpha', alpha, float) self._alpha = Tensor(np.array(alpha, np.float32)) self._decay_policy = check_param_type('decay_policy', decay_policy, str) self._mean = 0.0 self._sub = P.Sub() self._mul = P.Mul() self._add = P.TensorAdd() self._div = P.Div() self._stddev = self._update_stddev() self._dtype = mstype.float32
def __init__(self, decay_policy='Linear', learning_rate=0.001, target_unclipped_quantile=0.9, fraction_stddev=0.01, seed=0): super(AdaClippingWithGaussianRandom, self).__init__() if decay_policy not in ['Linear', 'Geometric']: msg = "decay policy of adaptive clip must be in ['Linear', 'Geometric'], \ but got: {}".format(decay_policy) LOGGER.error(TAG, msg) raise ValueError(msg) self._decay_policy = decay_policy learning_rate = check_param_type('learning_rate', learning_rate, float) learning_rate = check_value_positive('learning_rate', learning_rate) self._learning_rate = Tensor(learning_rate, mstype.float32) fraction_stddev = check_param_type('fraction_stddev', fraction_stddev, float) self._fraction_stddev = Tensor(fraction_stddev, mstype.float32) target_unclipped_quantile = check_param_type('target_unclipped_quantile', target_unclipped_quantile, float) self._target_unclipped_quantile = Tensor(target_unclipped_quantile, mstype.float32) self._zero = Tensor(0, mstype.float32) self._add = P.TensorAdd() self._sub = P.Sub() self._mul = P.Mul() self._exp = P.Exp() seed = check_param_type('seed', seed, int) self._seed = check_value_non_negative('seed', seed)
def __init__(self, num_samples, batch_size, initial_noise_multiplier=1.5, max_eps=10.0, target_delta=1e-3, noise_decay_mode='Time', noise_decay_rate=6e-4, per_print_times=50, dataset_sink_mode=False): super(ZCDPMonitor, self).__init__() check_int_positive('num_samples', num_samples) check_int_positive('batch_size', batch_size) if batch_size >= num_samples: msg = 'Batch_size must be less than num_samples.' LOGGER.error(TAG, msg) raise ValueError(msg) check_value_positive('initial_noise_multiplier', initial_noise_multiplier) if noise_decay_mode is not None: if noise_decay_mode not in ('Step', 'Time', 'Exp'): msg = "Noise decay mode must be in ('Step', 'Time', 'Exp'), but got {}.".\ format(noise_decay_mode) LOGGER.error(TAG, msg) raise ValueError(msg) noise_decay_rate = check_param_type('noise_decay_rate', noise_decay_rate, float) check_param_in_range('noise_decay_rate', noise_decay_rate, 0.0, 1.0) check_int_positive('per_print_times', per_print_times) check_param_type('dataset_sink_mode', dataset_sink_mode, bool) self._num_samples = num_samples self._batch_size = batch_size self._initial_noise_multiplier = initial_noise_multiplier self._max_eps = check_value_positive('max_eps', max_eps) self._target_delta = check_param_in_range('target_delta', target_delta, 0.0, 1.0) self._noise_decay_mode = noise_decay_mode self._noise_decay_rate = noise_decay_rate # initialize zcdp self._zcdp = 0 self._per_print_times = per_print_times if dataset_sink_mode: self._per_print_times = int(self._num_samples / self._batch_size)
def __init__(self, model, step_size=0.5, per_bounds=0.6, c1=2.0, c2=2.0, c=2.0, pop_size=6, t_max=1000, pm=0.5, bounds=None, targeted=False, reduction_iters=3, sparse=True): super(PSOAttack, self).__init__() self._model = check_model('model', model, BlackModel) self._step_size = check_value_positive('step_size', step_size) self._per_bounds = check_value_positive('per_bounds', per_bounds) self._c1 = check_value_positive('c1', c1) self._c2 = check_value_positive('c2', c2) self._c = check_value_positive('c', c) self._pop_size = check_int_positive('pop_size', pop_size) self._pm = check_value_positive('pm', pm) self._bounds = check_param_multi_types('bounds', bounds, [list, tuple]) for b in self._bounds: _ = check_param_multi_types('bound', b, [int, float]) self._targeted = check_param_type('targeted', targeted, bool) self._t_max = check_int_positive('t_max', t_max) self._reduce_iters = check_int_positive('reduction_iters', reduction_iters) self._sparse = check_param_type('sparse', sparse, bool)
def __init__(self, network, eps=1e-5, bounds=(0.0, 1.0), is_targeted=True, nb_iter=150, search_iters=30, loss_fn=None, sparse=False): super(LBFGS, self).__init__() self._network = check_model('network', network, Cell) self._eps = check_value_positive('eps', eps) self._is_targeted = check_param_type('is_targeted', is_targeted, bool) self._nb_iter = check_int_positive('nb_iter', nb_iter) self._search_iters = check_int_positive('search_iters', search_iters) if loss_fn is None: loss_fn = SoftmaxCrossEntropyWithLogits(is_grad=False, sparse=False) with_loss_cell = WithLossCell(self._network, loss_fn) self._grad_all = GradWrapWithLoss(with_loss_cell) self._dtype = None self._bounds = check_param_multi_types('bounds', bounds, [list, tuple]) self._sparse = check_param_type('sparse', sparse, bool) for b in self._bounds: _ = check_param_multi_types('bound', b, [int, float]) box_max, box_min = bounds if box_max < box_min: self._box_min = box_max self._box_max = box_min else: self._box_min = box_min self._box_max = box_max
def __init__(self, model, model_type='classification', targeted=False, reserve_ratio=0.3, sparse=True, step_size=0.5, per_bounds=0.6, c1=2.0, c2=2.0, c=2.0, pop_size=6, t_max=1000, pm=0.5, bounds=None): super(PSOAttack, self).__init__() self._model = check_model('model', model, BlackModel) self._step_size = check_value_positive('step_size', step_size) self._per_bounds = check_value_positive('per_bounds', per_bounds) self._c1 = check_value_positive('c1', c1) self._c2 = check_value_positive('c2', c2) self._c = check_value_positive('c', c) self._pop_size = check_int_positive('pop_size', pop_size) self._pm = check_value_non_negative('pm', pm) if self._pm > 1: msg = "pm should not be greater than 1.0, but got {}.".format(self._pm) LOGGER.error(TAG, msg) raise ValueError(msg) self._bounds = bounds if self._bounds is not None: self._bounds = check_param_multi_types('bounds', bounds, [list, tuple]) for b in self._bounds: _ = check_param_multi_types('bound', b, [int, float]) self._targeted = check_param_type('targeted', targeted, bool) self._t_max = check_int_positive('t_max', t_max) self._sparse = check_param_type('sparse', sparse, bool) self._model_type = check_param_type('model_type', model_type, str) if self._model_type not in ('classification', 'detection'): msg = "Only 'classification' or 'detection' is supported now, but got {}.".format(self._model_type) LOGGER.error(TAG, msg) raise ValueError(msg) self._reserve_ratio = check_value_non_negative('reserve_ratio', reserve_ratio) if self._reserve_ratio > 1: msg = "reserve_ratio should not be greater than 1.0, but got {}.".format(self._reserve_ratio) LOGGER.error(TAG, msg) raise ValueError(msg)
def __init__(self, model, bounds=(0.0, 1.0), max_iter=100, is_targeted=False, sparse=True): super(SaltAndPepperNoiseAttack, self).__init__() self._model = check_model('model', model, BlackModel) self._bounds = check_param_multi_types('bounds', bounds, [tuple, list]) for b in self._bounds: _ = check_param_multi_types('bound', b, [int, float]) self._max_iter = check_int_positive('max_iter', max_iter) self._is_targeted = check_param_type('is_targeted', is_targeted, bool) self._sparse = check_param_type('sparse', sparse, bool)
def __init__(self, network, loss_fn, optimizer, **kwargs): check_param_type('network', network, Cell) check_param_type('optimizer', optimizer, SGD) self.network_end = None self._train_one_step = None super(SuppressModel, self).__init__(network, loss_fn, optimizer, **kwargs)
def __init__(self, window_size=100, rolling_window=10, step=10, threshold_index=1.5, need_label=False): self.window_size = check_param_type('window_size', window_size, int) self.rolling_window = check_param_type('rolling_window', rolling_window, int) self.step = check_param_type('step', step, int) self.threshold_index = check_param_type('threshold_index', threshold_index, float) self.need_label = check_param_type('need_label', need_label, bool) self._in_size = window_size self._out_size = window_size self._res_size = int(0.1*window_size)
def __init__(self, model, n_jobs=-1): check_param_type("n_jobs", n_jobs, int) if not (n_jobs == -1 or n_jobs > 0): msg = "Value of n_jobs must be either -1 or positive integer, but got {}.".format( n_jobs) LOGGER.error(TAG, msg) raise ValueError(msg) self._model = check_model("model", model, Model) self._n_jobs = min(n_jobs, cpu_count()) self._attack_list = []
def link_suppress_ctrl(self, suppress_pri_ctrl): """ Link self and SuppressCtrl instance. Args: suppress_pri_ctrl (SuppressCtrl): SuppressCtrl instance. """ check_param_type('suppress_pri_ctrl', suppress_pri_ctrl, SuppressCtrl) suppress_pri_ctrl.model = self if self._train_one_step is not None: self._train_one_step.link_suppress_ctrl(suppress_pri_ctrl)
def _check_config(attack_config, config_checklist): """ Verify that config_list is valid. Check_params is the valid value range of the parameter. """ for config in attack_config: check_param_type("config", config, dict) if set(config.keys()) != {"params", "method"}: msg = "Keys of each config in attack_config must be {}," \ "but got {}.".format({'method', 'params'}, set(config.keys())) LOGGER.error(TAG, msg) raise KeyError(msg) method = str.lower(config["method"]) params = config["params"] if method not in config_checklist.keys(): msg = "Method {} is not supported.".format(method) LOGGER.error(TAG, msg) raise NameError(msg) if not params.keys() <= config_checklist[method].keys(): msg = "Params in method {} is not accepted, the parameters " \ "that can be set are {}.".format(method, set(config_checklist[method].keys())) LOGGER.error(TAG, msg) raise KeyError(msg) for param_key in params.keys(): param_value = params[param_key] candidate_values = config_checklist[method][param_key] check_param_type('param_value', param_value, (list, tuple, np.ndarray)) if candidate_values is None: continue for item_value in param_value: flag = False for candidate_value in candidate_values: if isinstance(candidate_value, set) and item_value in candidate_value: flag = True break elif not isinstance(candidate_value, set) and candidate_value(item_value): flag = True break if not flag: msg = "Setting of parmeter {} in method {} is invalid".format(param_key, method) raise ValueError(msg)
def __init__(self, norm_bound=1.0, initial_noise_multiplier=1.0, seed=0, decay_policy=None): super(NoiseGaussianRandom, self).__init__() norm_bound = check_param_type('norm_bound', norm_bound, float) self._norm_bound = check_value_positive('norm_bound', norm_bound) self._norm_bound = Tensor(norm_bound, mstype.float32) initial_noise_multiplier = check_param_type('initial_noise_multiplier', initial_noise_multiplier, float) self._initial_noise_multiplier = check_value_positive('initial_noise_multiplier', initial_noise_multiplier) self._initial_noise_multiplier = Tensor(initial_noise_multiplier, mstype.float32) self._mean = Tensor(0, mstype.float32) if decay_policy is not None: raise ValueError('decay_policy must be None in GaussianRandom class, but got {}.'.format(decay_policy)) self._decay_policy = decay_policy seed = check_param_type('seed', seed, int) self._seed = check_value_non_negative('seed', seed)
def __init__(self, network, optimizer, sens=1.0, micro_batches=None, norm_clip=1.0, mech=None): super(_TrainOneStepCell, self).__init__(auto_prefix=False) self.network = network self.network.set_grad() self.network.add_flags(defer_inline=True) self.weights = optimizer.parameters self.optimizer = optimizer self.grad = C.GradOperation('grad', get_by_list=True, sens_param=True) self.sens = sens self.reducer_flag = False self.grad_reducer = None parallel_mode = _get_parallel_mode() if parallel_mode in (ParallelMode.DATA_PARALLEL, ParallelMode.HYBRID_PARALLEL): self.reducer_flag = True if self.reducer_flag: mean = _get_mirror_mean() degree = _get_device_num() self.grad_reducer = DistributedGradReducer(optimizer.parameters, mean, degree) # dp params self._micro_batches = micro_batches norm_clip = check_param_type('norm_clip', norm_clip, float) self._l2_norm = check_value_positive('norm_clip', norm_clip) self._split = P.Split(0, self._micro_batches) self._clip_by_global_norm = _ClipGradients() self._mech = mech self._tuple_add = _TupleAdd() self._hyper_map = C.HyperMap() self._micro_float = Tensor(micro_batches, mstype.float32)
def __init__(self, model, scene, max_queries=10000, top_k=-1, num_class=10, batch_size=128, epsilon=0.3, samples_per_draw=128, momentum=0.9, learning_rate=1e-3, max_lr=5e-2, min_lr=5e-4, sigma=1e-3, plateau_length=20, plateau_drop=2.0, adv_thresh=0.25, zero_iters=10, starting_eps=1.0, starting_delta_eps=0.5, label_only_sigma=1e-3, conservative=2, sparse=True): super(NES, self).__init__() self._model = check_model('model', model, BlackModel) self._scene = scene self._max_queries = check_int_positive('max_queries', max_queries) self._num_class = check_int_positive('num_class', num_class) self._batch_size = check_int_positive('batch_size', batch_size) self._samples_per_draw = check_int_positive('samples_per_draw', samples_per_draw) self._goal_epsilon = check_value_positive('epsilon', epsilon) self._momentum = check_value_positive('momentum', momentum) self._learning_rate = check_value_positive('learning_rate', learning_rate) self._max_lr = check_value_positive('max_lr', max_lr) self._min_lr = check_value_positive('min_lr', min_lr) self._sigma = check_value_positive('sigma', sigma) self._plateau_length = check_int_positive('plateau_length', plateau_length) self._plateau_drop = check_value_positive('plateau_drop', plateau_drop) # partial information arguments self._k = top_k self._adv_thresh = check_value_positive('adv_thresh', adv_thresh) # label only arguments self._zero_iters = check_int_positive('zero_iters', zero_iters) self._starting_eps = check_value_positive('starting_eps', starting_eps) self._starting_delta_eps = check_value_positive('starting_delta_eps', starting_delta_eps) self._label_only_sigma = check_value_positive('label_only_sigma', label_only_sigma) self._conservative = check_int_positive('conservative', conservative) self._sparse = check_param_type('sparse', sparse, bool) self.target_imgs = None self.target_img = None self.target_class = None
def detect(self, inputs): """ Tell whether input samples are adversarial or not. Args: inputs (numpy.ndarray): Suspicious samples to be judged. Returns: list[int], whether a sample is adversarial. if res[i]=1, then the input sample with index i is adversarial. """ LOGGER.debug(TAG, 'enter detect().') self._radius = check_param_type('radius', self._radius, float) inputs = check_numpy_param('inputs', inputs) time_start = time.time() res = [1] * inputs.shape[0] raw_preds = np.argmax(self._model.predict(Tensor(inputs)).asnumpy(), axis=1) rc_preds = self._rc_forward(inputs, self._radius) for i in range(inputs.shape[0]): if raw_preds[i] == rc_preds[i]: res[i] = 0 LOGGER.debug(TAG, 'time used to detect %d samples is : %s seconds', inputs.shape[0], time.time() - time_start) return res
def __init__(self, network, num_classes, box_min=0.0, box_max=1.0, theta=1.0, max_iteration=1000, max_count=3, increase=True, sparse=True): super(JSMAAttack).__init__() LOGGER.debug(TAG, "init jsma class.") self._network = check_model('network', network, Cell) self._min = check_value_non_negative('box_min', box_min) self._max = check_value_non_negative('box_max', box_max) self._num_classes = check_int_positive('num_classes', num_classes) self._theta = check_value_positive('theta', theta) self._max_iter = check_int_positive('max_iteration', max_iteration) self._max_count = check_int_positive('max_count', max_count) self._increase = check_param_type('increase', increase, bool) self._net_grad = GradWrap(self._network) self._bit_map = None self._sparse = check_param_type('sparse', sparse, bool)
def __init__(self, inputs, labels, adv_inputs, adv_preds, targeted=False, target_label=None): self._inputs, self._labels = check_pair_numpy_param( 'inputs', inputs, 'labels', labels) self._adv_inputs, self._adv_preds = check_pair_numpy_param( 'adv_inputs', adv_inputs, 'adv_preds', adv_preds) targeted = check_param_type('targeted', targeted, bool) self._targeted = targeted if target_label is not None: target_label = check_numpy_param('target_label', target_label) self._target_label = target_label self._true_label = np.argmax(self._labels, axis=1) self._adv_label = np.argmax(self._adv_preds, axis=1) idxes = np.arange(self._adv_preds.shape[0]) if self._targeted: if target_label is None: msg = 'targeted attack need target_label, but got None.' LOGGER.error(TAG, msg) raise ValueError(msg) self._adv_preds, self._target_label = check_pair_numpy_param( 'adv_pred', self._adv_preds, 'target_label', target_label) self._success_idxes = idxes[self._adv_label == self._target_label] else: self._success_idxes = idxes[self._adv_label != self._true_label]
def get_attack_model(features, labels, config, n_jobs=-1): """ Get trained attack model specify by config. Args: features (numpy.ndarray): Loss and logits characteristics of each sample. labels (numpy.ndarray): Labels of each sample whether belongs to training set. config (dict): Config of attacker, with key in ["method", "params"]. The format is {"method": "knn", "params": {"n_neighbors": [3, 5, 7]}}, params of each method must within the range of changeable parameters. Tips of params implement can be found in "https://scikit-learn.org/0.16/modules/generated/sklearn.grid_search.GridSearchCV.html". n_jobs (int): Number of jobs run in parallel. -1 means using all processors, otherwise the value of n_jobs must be a positive integer. Returns: sklearn.BaseEstimator, trained model specify by config["method"]. Examples: >>> features = np.random.randn(10, 10) >>> labels = np.random.randint(0, 2, 10) >>> config = {"method": "knn", "params": {"n_neighbors": [3, 5, 7]}} >>> attack_model = get_attack_model(features, labels, config) """ features, labels = check_pair_numpy_param("features", features, "labels", labels) config = check_param_type("config", config, dict) n_jobs = check_param_type("n_jobs", n_jobs, int) if not (n_jobs == -1 or n_jobs > 0): msg = "Value of n_jobs must be -1 or positive integer." raise ValueError(msg) method = str.lower(config["method"]) with warnings.catch_warnings(): warnings.filterwarnings('ignore', category=ConvergenceWarning) if method == "knn": return _attack_knn(features, labels, config["params"], n_jobs) if method == "lr": return _attack_lr(features, labels, config["params"], n_jobs) if method == "mlp": return _attack_mlpc(features, labels, config["params"], n_jobs) if method == "rf": return _attack_rf(features, labels, config["params"], n_jobs) msg = "Method {} is not supported.".format(config["method"]) LOGGER.error(TAG, msg) raise NameError(msg)
def __init__(self, model, max_iter=1000, search_iter=10, is_targeted=False, init_attack=None, sparse=True): super(PointWiseAttack, self).__init__() self._model = check_model('model', model, BlackModel) self._max_iter = check_int_positive('max_iter', max_iter) self._search_iter = check_int_positive('search_iter', search_iter) self._is_targeted = check_param_type('is_targeted', is_targeted, bool) if init_attack is None: self._init_attack = SaltAndPepperNoiseAttack( model, is_targeted=self._is_targeted) else: self._init_attack = init_attack self._sparse = check_param_type('sparse', sparse, bool)
def __init__(self, network, weights): super(InversionLoss, self).__init__() self._network = check_param_type('network', network, Cell) self._mse_loss = MSELoss() self._weights = check_param_multi_types('weights', weights, [list, tuple]) self._get_shape = P.Shape() self._zeros = P.ZerosLike() self._device_target = context.get_context("device_target")
def __init__(self, network, input_shape, input_bound, loss_weights=(1, 0.2, 5)): self._network = check_param_type('network', network, Cell) for sub_loss_weight in loss_weights: check_value_positive('sub_loss_weight', sub_loss_weight) self._loss = InversionLoss(self._network, loss_weights) self._input_shape = check_param_type('input_shape', input_shape, tuple) for shape_dim in input_shape: check_int_positive('shape_dim', shape_dim) self._input_bound = check_param_multi_types('input_bound', input_bound, [list, tuple]) for value_bound in self._input_bound: check_param_multi_types('value_bound', value_bound, [float, int]) if self._input_bound[0] > self._input_bound[1]: msg = 'input_bound[0] should not be larger than input_bound[1], but got them as {} and {}'.format( self._input_bound[0], self._input_bound[1]) raise ValueError(msg)
def __init__(self, network, eps=0.3, eps_iter=0.1, bounds=(0.0, 1.0), is_targeted=False, nb_iter=5, decay_factor=1.0, norm_level='inf', loss_fn=None): super(MomentumIterativeMethod, self).__init__(network, eps=eps, eps_iter=eps_iter, bounds=bounds, nb_iter=nb_iter, loss_fn=loss_fn) self._is_targeted = check_param_type('is_targeted', is_targeted, bool) self._decay_factor = check_value_positive('decay_factor', decay_factor) self._norm_level = check_norm_level(norm_level)
def __init__(self, model, model_type='classification', targeted=True, reserve_ratio=0.3, sparse=True, pop_size=6, mutation_rate=0.005, per_bounds=0.15, max_steps=1000, step_size=0.20, temp=0.3, bounds=(0, 1.0), adaptive=False, c=0.1): super(GeneticAttack, self).__init__() self._model = check_model('model', model, BlackModel) self._model_type = check_param_type('model_type', model_type, str) if self._model_type not in ('classification', 'detection'): msg = "Only 'classification' or 'detection' is supported now, but got {}.".format(self._model_type) LOGGER.error(TAG, msg) raise ValueError(msg) self._targeted = check_param_type('targeted', targeted, bool) self._reserve_ratio = check_value_non_negative('reserve_ratio', reserve_ratio) if self._reserve_ratio > 1: msg = "reserve_ratio should not be greater than 1.0, but got {}.".format(self._reserve_ratio) LOGGER.error(TAG, msg) raise ValueError(msg) self._sparse = check_param_type('sparse', sparse, bool) self._per_bounds = check_value_positive('per_bounds', per_bounds) self._pop_size = check_int_positive('pop_size', pop_size) self._step_size = check_value_positive('step_size', step_size) self._temp = check_value_positive('temp', temp) self._max_steps = check_int_positive('max_steps', max_steps) self._mutation_rate = check_value_non_negative('mutation_rate', mutation_rate) if self._mutation_rate > 1: msg = "mutation_rate should not be greater than 1.0, but got {}.".format(self._mutation_rate) LOGGER.error(TAG, msg) raise ValueError(msg) self._adaptive = check_param_type('adaptive', adaptive, bool) # initial global optimum fitness value self._best_fit = -np.inf # count times of no progress self._plateau_times = 0 # count times of changing attack step_size self._adap_times = 0 self._bounds = bounds if self._bounds is not None: self._bounds = check_param_multi_types('bounds', bounds, [list, tuple]) for b in self._bounds: _ = check_param_multi_types('bound', b, [int, float]) self._c = check_value_positive('c', c)
def __init__(self, network, eps=0.3, bounds=(0.0, 1.0), is_targeted=False, norm_level='l1', prob=0.5, loss_fn=None): eps_iter = 16*2 / 255 nb_iter = int(min(eps*255 + 4, 1.25*255*eps)) super(MomentumDiverseInputIterativeMethod, self).__init__(network=network, eps=eps, eps_iter=eps_iter, bounds=bounds, nb_iter=nb_iter, is_targeted=is_targeted, norm_level=norm_level, loss_fn=loss_fn) self._prob = check_param_type('prob', prob, float)
def __init__(self, norm_bound=1.0, initial_noise_multiplier=1.0, seed=0, noise_decay_rate=6e-6, decay_policy='Exp'): super(NoiseAdaGaussianRandom, self).__init__(norm_bound=norm_bound, initial_noise_multiplier=initial_noise_multiplier, seed=seed) self._noise_multiplier = Parameter(self._initial_noise_multiplier, name='noise_multiplier') noise_decay_rate = check_param_type('noise_decay_rate', noise_decay_rate, float) check_param_in_range('noise_decay_rate', noise_decay_rate, 0.0, 1.0) self._noise_decay_rate = Tensor(noise_decay_rate, mstype.float32) if decay_policy not in ['Time', 'Step', 'Exp']: raise NameError("The decay_policy must be in ['Time', 'Step', 'Exp'], but " "get {}".format(decay_policy)) self._decay_policy = decay_policy