|
| 1 | +# MIT License |
| 2 | +# |
| 3 | +# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2021 |
| 4 | +# |
| 5 | +# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated |
| 6 | +# documentation files (the "Software"), to deal in the Software without restriction, including without limitation the |
| 7 | +# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit |
| 8 | +# persons to whom the Software is furnished to do so, subject to the following conditions: |
| 9 | +# |
| 10 | +# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the |
| 11 | +# Software. |
| 12 | +# |
| 13 | +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE |
| 14 | +# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE |
| 15 | +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, |
| 16 | +# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE |
| 17 | +# SOFTWARE. |
| 18 | +""" |
| 19 | +This module implements attribute inference attacks. |
| 20 | +""" |
| 21 | +from __future__ import absolute_import, division, print_function, unicode_literals |
| 22 | + |
| 23 | +import logging |
| 24 | +from typing import Optional, Union, TYPE_CHECKING |
| 25 | + |
| 26 | +import numpy as np |
| 27 | +from sklearn.neural_network import MLPClassifier |
| 28 | + |
| 29 | +from art.estimators.estimator import BaseEstimator |
| 30 | +from art.estimators.classification.classifier import ClassifierMixin |
| 31 | +from art.attacks.attack import AttributeInferenceAttack |
| 32 | +from art.utils import check_and_transform_label_format, float_to_categorical, floats_to_one_hot |
| 33 | + |
| 34 | +if TYPE_CHECKING: |
| 35 | + from art.utils import CLASSIFIER_TYPE |
| 36 | + |
| 37 | +logger = logging.getLogger(__name__) |
| 38 | + |
| 39 | + |
| 40 | +class AttributeInferenceBaseline(AttributeInferenceAttack): |
| 41 | + """ |
| 42 | + Implementation of a baseline attribute inference, not using a model. |
| 43 | +
|
| 44 | + The idea is to train a simple neural network to learn the attacked feature from the rest of the features. Should |
| 45 | + be used to compare with other attribute inference results. |
| 46 | + """ |
| 47 | + _estimator_requirements = () |
| 48 | + |
| 49 | + def __init__( |
| 50 | + self, |
| 51 | + attack_model: Optional["CLASSIFIER_TYPE"] = None, |
| 52 | + attack_feature: Union[int, slice] = 0, |
| 53 | + ): |
| 54 | + """ |
| 55 | + Create an AttributeInferenceBaseline attack instance. |
| 56 | +
|
| 57 | + :param attack_model: The attack model to train, optional. If none is provided, a default model will be created. |
| 58 | + :param attack_feature: The index of the feature to be attacked or a slice representing multiple indexes in |
| 59 | + case of a one-hot encoded feature. |
| 60 | + """ |
| 61 | + super().__init__(estimator=None, attack_feature=attack_feature) |
| 62 | + |
| 63 | + if isinstance(self.attack_feature, int): |
| 64 | + self.single_index_feature = True |
| 65 | + else: |
| 66 | + self.single_index_feature = False |
| 67 | + |
| 68 | + if attack_model: |
| 69 | + if ClassifierMixin not in type(attack_model).__mro__: |
| 70 | + raise ValueError("Attack model must be of type Classifier.") |
| 71 | + self.attack_model = attack_model |
| 72 | + else: |
| 73 | + self.attack_model = MLPClassifier( |
| 74 | + hidden_layer_sizes=(100,), |
| 75 | + activation="relu", |
| 76 | + solver="adam", |
| 77 | + alpha=0.0001, |
| 78 | + batch_size="auto", |
| 79 | + learning_rate="constant", |
| 80 | + learning_rate_init=0.001, |
| 81 | + power_t=0.5, |
| 82 | + max_iter=2000, |
| 83 | + shuffle=True, |
| 84 | + random_state=None, |
| 85 | + tol=0.0001, |
| 86 | + verbose=False, |
| 87 | + warm_start=False, |
| 88 | + momentum=0.9, |
| 89 | + nesterovs_momentum=True, |
| 90 | + early_stopping=False, |
| 91 | + validation_fraction=0.1, |
| 92 | + beta_1=0.9, |
| 93 | + beta_2=0.999, |
| 94 | + epsilon=1e-08, |
| 95 | + n_iter_no_change=10, |
| 96 | + max_fun=15000, |
| 97 | + ) |
| 98 | + self._check_params() |
| 99 | + |
| 100 | + def fit(self, x: np.ndarray) -> None: |
| 101 | + """ |
| 102 | + Train the attack model. |
| 103 | +
|
| 104 | + :param x: Input to training process. Includes all features used to train the original model. |
| 105 | + """ |
| 106 | + |
| 107 | + # Checks: |
| 108 | + if self.single_index_feature and self.attack_feature >= x.shape[1]: |
| 109 | + raise ValueError("attack_feature must be a valid index to a feature in x") |
| 110 | + |
| 111 | + # get vector of attacked feature |
| 112 | + y = x[:, self.attack_feature] |
| 113 | + if self.single_index_feature: |
| 114 | + y_one_hot = float_to_categorical(y) |
| 115 | + else: |
| 116 | + y_one_hot = floats_to_one_hot(y) |
| 117 | + y_ready = check_and_transform_label_format(y_one_hot, len(np.unique(y)), return_one_hot=True) |
| 118 | + |
| 119 | + # create training set for attack model |
| 120 | + x_train = np.delete(x, self.attack_feature, 1).astype(np.float32) |
| 121 | + |
| 122 | + # train attack model |
| 123 | + self.attack_model.fit(x_train, y_ready) |
| 124 | + |
| 125 | + def infer(self, x: np.ndarray, y: Optional[np.ndarray] = None, **kwargs) -> np.ndarray: |
| 126 | + """ |
| 127 | + Infer the attacked feature. |
| 128 | +
|
| 129 | + :param x: Input to attack. Includes all features except the attacked feature. |
| 130 | + :param y: Not used in this attack. |
| 131 | + :param values: Possible values for attacked feature. Only needed in case of categorical feature (not one-hot). |
| 132 | + :type values: `np.ndarray` |
| 133 | + :return: The inferred feature values. |
| 134 | + """ |
| 135 | + x_test = x.astype(np.float32) |
| 136 | + |
| 137 | + if self.single_index_feature: |
| 138 | + if "values" not in kwargs.keys(): |
| 139 | + raise ValueError("Missing parameter `values`.") |
| 140 | + values: np.ndarray = kwargs.get("values") |
| 141 | + return np.array([values[np.argmax(arr)] for arr in self.attack_model.predict(x_test)]) |
| 142 | + else: |
| 143 | + if "values" in kwargs.keys(): |
| 144 | + values = kwargs.get("values") |
| 145 | + predictions = self.attack_model.predict(x_test).astype(np.float32) |
| 146 | + i = 0 |
| 147 | + for column in predictions.T: |
| 148 | + for index in range(len(values[i])): |
| 149 | + np.place(column, [column == index], values[i][index]) |
| 150 | + i += 1 |
| 151 | + return np.array(predictions) |
| 152 | + else: |
| 153 | + return np.array(self.attack_model.predict(x_test)) |
| 154 | + |
| 155 | + def _check_params(self) -> None: |
| 156 | + if not isinstance(self.attack_feature, int) and not isinstance(self.attack_feature, slice): |
| 157 | + raise ValueError("Attack feature must be either an integer or a slice object.") |
| 158 | + if isinstance(self.attack_feature, int) and self.attack_feature < 0: |
| 159 | + raise ValueError("Attack feature index must be positive.") |
0 commit comments