|
| 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 using membership inference attacks. |
| 20 | +""" |
| 21 | +from __future__ import absolute_import, division, print_function, unicode_literals |
| 22 | + |
| 23 | +import logging |
| 24 | +from typing import Optional, Union, List, TYPE_CHECKING |
| 25 | + |
| 26 | +import numpy as np |
| 27 | + |
| 28 | +from art.estimators.estimator import BaseEstimator |
| 29 | +from art.estimators.classification.classifier import ClassifierMixin |
| 30 | +from art.attacks.attack import AttributeInferenceAttack, MembershipInferenceAttack |
| 31 | +from art.exceptions import EstimatorError |
| 32 | + |
| 33 | +if TYPE_CHECKING: |
| 34 | + from art.utils import CLASSIFIER_TYPE |
| 35 | + |
| 36 | +logger = logging.getLogger(__name__) |
| 37 | + |
| 38 | + |
| 39 | +class AttributeInferenceMembership(AttributeInferenceAttack): |
| 40 | + """ |
| 41 | + Implementation of a an attribute inference attack that utilizes a membership inference attack. |
| 42 | +
|
| 43 | + The idea is to find the target feature value that causes the membership inference attack to classify the sample |
| 44 | + as a member with the highest confidence. |
| 45 | + """ |
| 46 | + |
| 47 | + _estimator_requirements = (BaseEstimator, ClassifierMixin) |
| 48 | + |
| 49 | + def __init__( |
| 50 | + self, |
| 51 | + classifier: "CLASSIFIER_TYPE", |
| 52 | + membership_attack: MembershipInferenceAttack, |
| 53 | + attack_feature: Union[int, slice] = 0, |
| 54 | + ): |
| 55 | + """ |
| 56 | + Create an AttributeInferenceMembership attack instance. |
| 57 | +
|
| 58 | + :param classifier: Target classifier. |
| 59 | + :param membership_attack: The membership inference attack to use. Should be fit/callibrated in advance, and |
| 60 | + should support returning probabilities. |
| 61 | + :param attack_feature: The index of the feature to be attacked or a slice representing multiple indexes in |
| 62 | + case of a one-hot encoded feature. |
| 63 | + """ |
| 64 | + super().__init__(estimator=classifier, attack_feature=attack_feature) |
| 65 | + if not all(t in type(classifier).__mro__ for t in membership_attack.estimator_requirements): |
| 66 | + raise EstimatorError(membership_attack, membership_attack.estimator_requirements, classifier) |
| 67 | + |
| 68 | + self.membership_attack = membership_attack |
| 69 | + self._check_params() |
| 70 | + |
| 71 | + def infer(self, x: np.ndarray, y: Optional[np.ndarray] = None, **kwargs) -> np.ndarray: |
| 72 | + """ |
| 73 | + Infer the attacked feature. |
| 74 | +
|
| 75 | + :param x: Input to attack. Includes all features except the attacked feature. |
| 76 | + :param y: The labels expected by the membership attack. |
| 77 | + :param values: Possible values for attacked feature. For a single column feature this should be a simple list |
| 78 | + containing all possible values, in increasing order (the smallest value in the 0 index and so |
| 79 | + on). For a multi-column feature (for example 1-hot encoded and then scaled), this should be a |
| 80 | + list of lists, where each internal list represents a column (in increasing order) and the values |
| 81 | + represent the possible values for that column (in increasing order). |
| 82 | + :type values: list |
| 83 | + :return: The inferred feature values. |
| 84 | + """ |
| 85 | + if self.estimator.input_shape is not None: |
| 86 | + if isinstance(self.attack_feature, int) and self.estimator.input_shape[0] != x.shape[1] + 1: |
| 87 | + raise ValueError("Number of features in x + 1 does not match input_shape of classifier") |
| 88 | + |
| 89 | + if "values" not in kwargs.keys(): |
| 90 | + raise ValueError("Missing parameter `values`.") |
| 91 | + values: Optional[List] = kwargs.get("values") |
| 92 | + if not values: |
| 93 | + raise ValueError("`values` cannot be None or empty") |
| 94 | + |
| 95 | + if y is not None: |
| 96 | + if y.shape[0] != x.shape[0]: |
| 97 | + raise ValueError("Number of rows in x and y do not match") |
| 98 | + |
| 99 | + # assumes single index |
| 100 | + if isinstance(self.attack_feature, int): |
| 101 | + first = True |
| 102 | + for value in values: |
| 103 | + v_full = np.full((x.shape[0], 1), value).astype(np.float32) |
| 104 | + x_value = np.concatenate((x[:, : self.attack_feature], v_full), axis=1) |
| 105 | + x_value = np.concatenate((x_value, x[:, self.attack_feature :]), axis=1) |
| 106 | + |
| 107 | + predicted = self.membership_attack.infer(x_value, y, probabilities=True) |
| 108 | + if first: |
| 109 | + probabilities = predicted[:, 1].reshape(-1, 1) |
| 110 | + first = False |
| 111 | + else: |
| 112 | + probabilities = np.hstack((probabilities, predicted[:, 1].reshape(-1, 1))) |
| 113 | + |
| 114 | + # needs to be of type float so we can later replace back the actual values |
| 115 | + value_indexes = np.argmax(probabilities, axis=1).astype(np.float32) |
| 116 | + pred_values = np.zeros_like(value_indexes) |
| 117 | + for index, value in enumerate(values): |
| 118 | + pred_values[value_indexes == index] = value |
| 119 | + else: # 1-hot encoded feature. Can also be scaled. |
| 120 | + first = True |
| 121 | + # assumes that the second value is the "positive" value and that there can only be one positive column |
| 122 | + for index, value in enumerate(values): |
| 123 | + curr_value = np.zeros((x.shape[0], len(values))) |
| 124 | + curr_value[:, index] = value[1] |
| 125 | + for not_index, not_value in enumerate(values): |
| 126 | + if not_index != index: |
| 127 | + curr_value[:, not_index] = not_value[0] |
| 128 | + x_value = np.concatenate((x[:, : self.attack_feature.start], curr_value), axis=1) |
| 129 | + x_value = np.concatenate((x_value, x[:, self.attack_feature.start :]), axis=1) |
| 130 | + |
| 131 | + predicted = self.membership_attack.infer(x_value, y, probabilities=True) |
| 132 | + if first: |
| 133 | + probabilities = predicted[:, 1].reshape(-1, 1) |
| 134 | + else: |
| 135 | + probabilities = np.hstack((probabilities, predicted[:, 1].reshape(-1, 1))) |
| 136 | + first = False |
| 137 | + value_indexes = np.argmax(probabilities, axis=1).astype(np.float32) |
| 138 | + pred_values = np.zeros_like(probabilities) |
| 139 | + for index, value in enumerate(values): |
| 140 | + curr_value = np.zeros(len(values)) |
| 141 | + curr_value[index] = value[1] |
| 142 | + for not_index, not_value in enumerate(values): |
| 143 | + if not_index != index: |
| 144 | + curr_value[not_index] = not_value[0] |
| 145 | + pred_values[value_indexes == index] = curr_value |
| 146 | + return pred_values |
| 147 | + |
| 148 | + def _check_params(self) -> None: |
| 149 | + if not isinstance(self.attack_feature, int) and not isinstance(self.attack_feature, slice): |
| 150 | + raise ValueError("Attack feature must be either an integer or a slice object.") |
| 151 | + if isinstance(self.attack_feature, int) and self.attack_feature < 0: |
| 152 | + raise ValueError("Attack feature index must be positive.") |
| 153 | + if not isinstance(self.membership_attack, MembershipInferenceAttack): |
| 154 | + raise ValueError("membership_attack should be a sub-class of MembershipInferenceAttack") |
0 commit comments