-
Notifications
You must be signed in to change notification settings - Fork 3
/
fgs.py
35 lines (30 loc) · 820 Bytes
/
fgs.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# --coding:utf-8--
'''
@author: cailikun
@time: 2019/4/4 上午12:10
'''
import torch
from attack_utils import gen_grad
def symbolic_fgs(data, grad, eps=0.3, clipping=True):
'''
FGSM attack.
'''
# signed gradien
normed_grad = grad.detach().sign()
# Multiply by constant epsilon
scaled_grad = eps * normed_grad
# Add perturbation to original example to obtain adversarial example
adv_x = data.detach() + scaled_grad
if clipping:
adv_x = torch.clamp(adv_x, 0, 1)
return adv_x
def iter_fgs(model, data, labels, steps, eps):
'''
I-FGSM attack.
'''
adv_x = data
# iteratively apply the FGSM with small step size
for i in range(steps):
grad = gen_grad(adv_x, model, labels)
adv_x = symbolic_fgs(adv_x, grad, eps)
return adv_x