-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
(#6) Attack: Impl. attack with defense model
- Loading branch information
Showing
2 changed files
with
35 additions
and
30 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,37 +1,28 @@ | ||
from typings.models import Attack, Model | ||
from typings.dataset import Dataset | ||
from typings.models import Attack | ||
|
||
from cleverhans.tf2.attacks.fast_gradient_method import fast_gradient_method | ||
|
||
from victim.models import Classifier | ||
from defense.models import Reformer | ||
|
||
from utils.dataset import Cifar10 | ||
|
||
import numpy as np | ||
import tensorflow as tf | ||
|
||
|
||
keras = tf.keras | ||
|
||
|
||
class Fgsm(Attack): | ||
def __init__( | ||
self, | ||
model: Model, | ||
dataset: Dataset, | ||
accuracy_normal: keras.metrics.Accuracy = tf.metrics.SparseCategoricalAccuracy(), | ||
accuracy_under_attack: keras.metrics.Accuracy = tf.metrics.SparseCategoricalAccuracy(), | ||
): | ||
super(Fgsm, self).__init__( | ||
model, dataset, accuracy_normal, accuracy_under_attack | ||
) | ||
|
||
def add_perturbation(self, x: np.array) -> np.array: | ||
return fast_gradient_method(self.model.model(), x, 0.05, np.inf) | ||
return fast_gradient_method(self.victim_model.model(), x, 0.05, np.inf) | ||
|
||
|
||
if __name__ == "__main__": | ||
f = Fgsm( | ||
Classifier(name="victim_classifier_cifar10", input_shape=(32, 32, 3)), Cifar10() | ||
Classifier(name="victim_classifier_cifar10", input_shape=(32, 32, 3)), | ||
Cifar10(), | ||
defense_model=Reformer("defense_reformer_cifar10", input_shape=(32, 32, 3)), | ||
) | ||
acc_with_attack, acc = f.attack() | ||
print(acc_with_attack.result(), acc.result()) | ||
acc, acc_under_attack, acc_with_defense = f.attack() | ||
print(acc.result(), acc_under_attack.result(), acc_with_defense.result()) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters