|
| 1 | +from __future__ import absolute_import, division, print_function, unicode_literals |
| 2 | + |
| 3 | +import abc |
| 4 | +import sys |
| 5 | + |
| 6 | + |
| 7 | +# Ensure compatibility with Python 2 and 3 when using ABCMeta |
| 8 | +if sys.version_info >= (3, 4): |
| 9 | + ABC = abc.ABC |
| 10 | +else: |
| 11 | + ABC = abc.ABCMeta(str('ABC'), (), {}) |
| 12 | + |
| 13 | + |
| 14 | +class Detector(ABC): |
| 15 | + """ |
| 16 | + Base abstract class for all detection methods. |
| 17 | + """ |
| 18 | + def __init__(self): |
| 19 | + """ |
| 20 | + Create a detector. |
| 21 | + """ |
| 22 | + self._is_fitted = False |
| 23 | + |
| 24 | + @property |
| 25 | + def is_fitted(self): |
| 26 | + """ |
| 27 | + Return the state of the detector. |
| 28 | +
|
| 29 | + :return: `True` if the detection model has been fitted (if this applies). |
| 30 | + :rtype: `bool` |
| 31 | + """ |
| 32 | + return self._is_fitted |
| 33 | + |
| 34 | + @abc.abstractmethod |
| 35 | + def fit(self, x, y=None, **kwargs): |
| 36 | + """ |
| 37 | + Fit the detector using training data (if this applies). |
| 38 | +
|
| 39 | + :param x: Training set to fit the detector. |
| 40 | + :type x: `np.ndarray` |
| 41 | + :param y: Labels for the training set. |
| 42 | + :type y: `np.ndarray` |
| 43 | + :param kwargs: Other parameters. |
| 44 | + :type kwargs: `dict` |
| 45 | + :return: None |
| 46 | + """ |
| 47 | + self._is_fitted = True |
| 48 | + |
| 49 | + @abc.abstractmethod |
| 50 | + def __call__(self, x): |
| 51 | + """ |
| 52 | + Perform detection of adversarial data and return preprocessed data as tuple. |
| 53 | +
|
| 54 | + :param x: Data sample on which to perform detection. |
| 55 | + :type x: `np.ndarray` |
| 56 | + :return: Per-sample prediction whether data is adversarial or not, where `0` means non-adversarial. |
| 57 | + Return variable has the same `batch_size` (first dimension) as `x`. |
| 58 | + :rtype: `np.ndarray` |
| 59 | + """ |
| 60 | + raise NotImplementedError |
| 61 | + |
| 62 | + def set_params(self, **kwargs): |
| 63 | + """ |
| 64 | + Take in a dictionary of parameters and apply checks before saving them as attributes. |
| 65 | + :return: True when parsing was successful |
| 66 | + """ |
| 67 | + for key, value in kwargs.items(): |
| 68 | + if key in self.params: |
| 69 | + setattr(self, key, value) |
| 70 | + return True |
0 commit comments