|
| 1 | +from __future__ import absolute_import, division, print_function, unicode_literals |
| 2 | + |
| 3 | +from scipy import ndimage |
| 4 | + |
| 5 | +from src.defences.preprocessor import Preprocessor |
| 6 | + |
| 7 | + |
| 8 | +class SpatialSmoothing(Preprocessor): |
| 9 | + """ |
| 10 | + Implement the local spatial smoothing defence approach. |
| 11 | + Defence method from https://arxiv.org/abs/1704.01155. |
| 12 | + """ |
| 13 | + params = ["window_size"] |
| 14 | + |
| 15 | + def __init__(self, window_size=3): |
| 16 | + """ |
| 17 | + Create an instance of local spatial smoothing. |
| 18 | + :param window_size: (int) The size of the sliding window. |
| 19 | + """ |
| 20 | + self.is_fitted = True |
| 21 | + self.set_params(window_size=window_size) |
| 22 | + |
| 23 | + def __call__(self, x_val, window_size=3): |
| 24 | + """ |
| 25 | + Apply local spatial smoothing to sample x_val. |
| 26 | + :param x_val: (np.ndarray) Sample to smooth. `x_val` is supposed to |
| 27 | + have shape (batch_size, width, height, depth). |
| 28 | + :param window_size: (int) The size of the sliding window. |
| 29 | + :return: Smoothed sample |
| 30 | + :rtype: np.ndarray |
| 31 | + """ |
| 32 | + self.set_params(window_size=window_size) |
| 33 | + size = (1, window_size, window_size, 1) |
| 34 | + result = ndimage.filters.median_filter(x_val, size=size, mode="reflect") |
| 35 | + |
| 36 | + return result |
| 37 | + |
| 38 | + def fit(self, x_val, y_val=None, **kwargs): |
| 39 | + """ |
| 40 | + No parameters to learn for this method; do nothing. |
| 41 | + """ |
| 42 | + pass |
| 43 | + |
| 44 | + def set_params(self, **kwargs): |
| 45 | + """ |
| 46 | + Take in a dictionary of parameters and applies defense-specific checks |
| 47 | + before saving them as attributes. |
| 48 | + Defense-specific parameters: |
| 49 | + :param window_size: (int) The size of the sliding window. |
| 50 | + """ |
| 51 | + # Save attack-specific parameters |
| 52 | + super(SpatialSmoothing, self).set_params(**kwargs) |
| 53 | + |
| 54 | + if type(self.window_size) is not int or self.window_size <= 0: |
| 55 | + raise ValueError("Sliding window size must be a positive integer") |
| 56 | + |
| 57 | + return True |
| 58 | + |
| 59 | + |
| 60 | + |
| 61 | + |
| 62 | + |
| 63 | + |
0 commit comments