对抗样本cleverhans的使用

cleverhans模块的使用

介绍

  • cleverhans是一个开源的对抗样本库,最新版本v4.0.0支持pytorchv3.1.0及之前仅仅支持tensorflow
  • 里面实现了常见对抗样本的攻击和防御,v4.0.0版本还不太完善,仅仅实现了部分算法
  • 下载:
    • pip install cleverhans

使用:

对抗样本生成常见流程:
  • 收集处理数据
  • 构建并训练目标模型
  • 实现相应的对抗样本算法,实现与之对应的对抗样本
导入对应包
import cleverhans
from cleverhans.torch.attacks.fast_gradient_method import fast_gradient_method
from cleverhans.torch.attacks.carlini_wagner_l2 import carlini_wagner_l2
from cleverhans.torch.attacks.projected_gradient_descent import projected_gradient_descent
import numpy as np
import torch
import torch.nn as nn
from torchvision.datasets import MNIST
from torchvision.transforms import ToTensor
from torch.utils.data import DataLoader
import matplotlib.pyplot as plt
import os
import torch.nn.functional as F
from tqdm import tqdm
os.environ["KMP_DUPLICATE_LIB_OK"]="TRUE"
%matplotlib inline
收集处理数据:

我们采用torchvision模块中的MNIST数据集

#MNIST数据集加载和处理
train_data=MNIST(root="data",train=True,download=False,transform=ToTensor())
test_data=MNIST(root="data",train=False,download=False,transform=ToTensor())

在这里插入图片描述

#数据处理
batch_size=16
train_loader=DataLoader(train_data,batch_size=batch_size)
test_loader=DataLoader(test_data,batch_size=batch_size)
原始数据可视化:
for x,label in train_loader:
    plt.figure(figsize=(16,8))
    id=0
    for i in range(4):
        for j in range(4):
            plt.subplot(4,4,id+1)
            plt.imshow(x[id,0].reshape(28,28),cmap="gray")
            plt.title(str(label[id].detach().numpy()),{"color":"red"})
            plt.axis("off")
            id+=1
    break

在这里插入图片描述

构建模型进行训练:
#构建网络模型
class Net(nn.Module):
    def __init__(self):
        super(Net,self).__init__()
        self.conv=nn.Sequential(nn.Conv2d(1,16,3,1,0),nn.ReLU(),nn.Conv2d(16,8,3,1,0),nn.ReLU())
        self.full=nn.Sequential(nn.Linear(8*24*24,32),nn.ReLU(),nn.Linear(32,10))
    def weight_init(self):
        for m in self._modules:
            if isinstance(m, nn.Linear) or isinstance(m, nn.Conv2d):  #判断当前网络结构是否为全连接层或者卷积层
                m.weight.data.normal_(0.0, 0.01)
                m.bias.data.zero_()
    def forward(self,inx):
        x=self.conv(inx)
#         print(x.shape)
#         input()
        x=x.view(-1,8*24*24)
        x=self.full(x)
        return x

在这里插入图片描述

模型训练
#模型训练
def train(model,data_loader,loss_func,epochs,lr):
    optimizer=torch.optim.Adam(model.parameters(),lr)
    for epoch in range(1,epochs+1):
        for i,(x,y) in tqdm(enumerate(data_loader)):
            x=x.to(device)
            y=y.to(device)
            out=model(x)
            loss=loss_func(out,y)
            optimizer.zero_grad()
            loss.backward()
            optimizer.step()
            if i%1000==0:
                print(f"epoch:{epoch}|| current_num:{i}|| loss:{loss}")
criterion=nn.CrossEntropyLoss()
lr=1e-3
epochs=1
net.weight_init()

在这里插入图片描述

模型测试:
def test(model,data_loader):
    correct_sum=0
    all_sum=0
    for x,y in data_loader:
        x=x.to(device)
        out=torch.argmax(model(x),dim=1).cpu()
        correct=(out==y).sum()
        correct_sum+=correct
        all_sum+=len(y)
    return correct_sum/all_sum

在这里插入图片描述

sample=next(iter(test_loader))
data,label=sample
predic=torch.argmax(net(data.to(device)),dim=1).detach().cpu()
plt.figure(figsize=(16,8))
id=0
for i in range(4):
    for j in range(4):
        plt.subplot(4,4,id+1)
        plt.imshow(data[id,0].reshape(28,28),cmap="gray")
        plt.title(f"{label[id]}->{predic[id]}",{"color":"red"})
        plt.axis("off")
        id+=1

在这里插入图片描述

对抗样本生成
FGSM算法:
advx=fast_gradient_method(net,data.to(device),0.1,np.inf).detach().cpu()
predic=torch.argmax(net(advx.to(device)),dim=1).detach().cpu()
plt.figure(figsize=(16,8))
id=0
for i in range(4):
    for j in range(4):
        plt.subplot(4,4,id+1)
        plt.imshow(advx[id,0].reshape(28,28),cmap="gray")
        plt.title(f"{label[id]}->{predic[id]}",{"color":"red"})
        plt.axis("off")
        id+=1

在这里插入图片描述

PGD算法:
advx=projected_gradient_descent(net,data.to(device),0.1,0.05,40,np.inf).detach().cpu()
predic=torch.argmax(net(advx.to(device)),dim=1).detach().cpu()

在这里插入图片描述

CW算法
1.定向攻击,target=5
advx=carlini_wagner_l2(net,data.to(device),10,torch.tensor([5]*batch_size,device=device),targeted=True).detach().cpu()
predic=torch.argmax(net(advx.to(device)),dim=1).detach().cpu()

在这里插入图片描述

2.非定向攻击
advx=carlini_wagner_l2(net,data.to(device),10,torch.tensor([5]*batch_size,device=device),targeted=False).detach().cpu()
predic=torch.argmax(net(advx.to(device)),dim=1).detach().cpu()

在这里插入图片描述

Cleverhans是一个基于TensorFlow的开源,用于评估机器学习模型的安全性并提供防御机制。它提供了许多攻击和防御算法,以帮助研究人员测试和改进模型的安全性。 如果您要在Jupyter Notebook中使用Cleverhans,您可以按照以下步骤操作: 1. 安装Cleverhans。您可以通过运行以下命令来安装它: ```python !pip install cleverhans ``` 2. 导入所需的模块。例如,如果您想使用Fast Gradient Method(FGM)攻击,请导入以下模块: ```python import tensorflow as tf import numpy as np from cleverhans.attacks import FastGradientMethod from cleverhans.utils_keras import KerasModelWrapper from keras.models import Sequential from keras.layers import Dense ``` 3. 定义您的模型。在这个例子中,我们使用一个简单的神经网络,它包含一个输入层,一个隐藏层,一个ReLU激活函数和一个输出层: ```python model = Sequential() model.add(Dense(64, input_dim=10, activation='relu')) model.add(Dense(1, activation='sigmoid')) ``` 4. 创建Cleverhans包装器。这将是您定义的模型的“包装器”,以便可以使用Cleverhans提供的攻击算法: ```python wrap = KerasModelWrapper(model) ``` 5. 定义您的攻击。在这个例子中,我们使用Fast Gradient Method(FGM)攻击。可以使用以下代码创建攻击实例: ```python fgm = FastGradientMethod(wrap, sess=sess) ``` 6. 生成对抗样本使用您定义的攻击來生成对抗样本,例如: ```python adv_x = fgm.generate_np(x_test, eps=0.1) ``` 在这个例子中,我们使用`x_test`作为原始样本,`eps=0.1`作为FGM攻击的扰动范围。 7. 测试模型的准确性。使用Cleverhans还可以测试模型的准确性。以下是一个示例代码: ```python adv_preds_class = np.argmax(model.predict(adv_x), axis=1) adv_acc = np.mean(adv_preds_class == y_test) print("Test Accuracy on Adversarial Examples: {:.2f}%".format(adv_acc * 100)) ``` 在这个例子中,我们使用了`adv_x`生成的对抗样本,并计算了模型在这些对抗样本上的准确性。
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值