快速梯度符号法(FGSM)及其改进
部分引用,如有侵权,告知删除。
个人理解,如有不对,欢迎指正。
FGSM发展相关论文
FGSM ——> IFGSM(也叫BIM) 、ILCM ——> R+FGSM
相关论文: FGSM : 《Explaining And Harnessing Adversarial Examples》 (2014) [2]
I-FGSM(也叫BIM) 、ILCM: 《Adversarial examples in the physical world》(2016)
R+FGSM:《Ensemble Adversarial Training: Attacks and Defenses》 (2017)
论文源址:
FGSM : http://de.arxiv.org/pdf/1412.6572
IFGSM(也叫BIM) 、ILCM :http://arxiv.org/pdf/1607.02533
参考笔记:
FGSM : https://zhuanlan.zhihu.com/p/33875223
IFGSM(也叫BIM) 、ILCM:https://www.jianshu.com/p/2f3b15617236
FGSM
FGSM:在 在原始样本(x,y)处求损失函数增大的梯度方向sign(▽J(θ,x,y)),在梯度方向上生成 一定的(由ε控制) 扰动ŋ
FGSM的代码实现(pytorch)
代码是从https://www.cnblogs.com/tangweijqxx/p/10615950.html搬来的,加了点自己理解的注释,我自己没跑,仅供参考
范数那里不太懂,希望懂得可以指点一下
class FGSM(nn.Module):
def __init__(self,model):
super().__init__()
self.model=model#必须是pytorch的model
self.device=torch.device("cuda" if (torch.cuda.is_available()) else "cpu")
def generate(self,x,**params):
self.parse_params(**params)
labels=self.y
if self.rand_init: #模型给x求导之前会为其添加一个随机噪声(噪声类型可以自己指定),据说这样效果过会好一点。
x_new = x + torch.Tensor(np.random.uniform(-self.eps, self.eps, x.shape)).type_as(x).cuda()
# get the gradient of x
x_new=Variable(x_new,requires_grad=True)
loss_func = nn.CrossEntropyLoss()
preds = self.model(x_new)
if self.flag_target:
loss = -loss_func(preds, labels) # labels为指定的目标标签,加负号即正常的梯度下降
else:
loss = loss_func(preds, labels) #使整体损失函数增大
self.model.zero_grad() #把模型中参数的梯度设为0
loss.backward()
#如果想把CUDA tensor格式的数据改成numpy时,需要先将其转换成cpu float-tensor随后再转到numpy格式。 numpy不能读取CUDA tensor 需要将它转化为 CPU tensor
grad = x_new.grad.cpu().detach().numpy()
# get the pertubation of an iter_eps
if self.ord==np.inf: #无穷范数
grad =np.sign(grad)
else:
tmp = grad.reshape(grad.shape[0], -1)
norm = 1e-12 + np.linalg.norm(tmp, ord=self.ord, axis=1, keepdims=False).reshape(-1, 1, 1, 1)
# 选择更小的扰动
grad=grad/norm
pertubation = grad*self.eps
adv_x = x.cpu().detach().numpy() + pertubation
adv_x=np.clip(adv_x,self.clip_min,self.clip_max) #产生的对抗样本可能会在(0,1)这个范围之外,因此需要对x clip至(0,1)
return adv_x
def parse_params(self,eps=0.3,ord=np.inf,
clip_min=0.0,clip_max=1.0, #保证对抗样本在样本空间
y=None,rand_init=False,flag_target=False):
self.eps=eps
self.ord=ord #指定范数类型
self.clip_min=clip_min
self.clip_max=clip_max
self.y=y #可指定目标标签
self.rand_init=rand_init #扰动是否随机初始化
self.model.to(self.device)
self.flag_target=flag_target
IFGSM/IBM
ITERATIVE FGSM ( BASIC ITERATIVE METHOD ):针对无目标攻击
ILCM( ITERATIVE LEAST-LIKELY CLASS METH):针对目标攻击,使最不可能的类损失函数最小
BIM算法以XNadv =Xc开始,并运行由公式[min(ε+4,1.25ε )]确定的迭代次数。该方法可以有效地降低扰动的噪声。
两种算法的比较
FGSM更快但是,攻击效果不是很好,产生的扰动更大
R+FGSM
目标是最大化损失函数
作者通过用单步攻击的输出替换内置最大化问题的解来近似方程式。