cleverhans库——FGSM代码实战
生活随笔
收集整理的這篇文章主要介紹了
cleverhans库——FGSM代码实战
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
什么是cleverhans庫?
cleverhans是一個機器學習模型攻防庫,里面有很多的攻防技術實現。安裝只需pip install cleverhans 這句口令,隨后便能調用庫里的函數。
FGSM代碼——可以直接運行
1、使用了Alexnet模型,然后只放了一張圖片,這部分代碼主要對圖片進行初始化,方便使用
from __future__ import print_function import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from torchvision import datasets, transforms import numpy as np import matplotlib.pyplot as plt from torchvision import models import cv2 from torch.autograd import Variable #獲取計算設備 默認是CPU device = torch.device("cuda" if torch.cuda.is_available() else "cpu")#圖像加載以及預處理 image_path="data/goldfish.jpg" orig = cv2.imread(image_path)[..., ::-1] orig = cv2.resize(orig, (224, 224)) img = orig.copy().astype(np.float32)mean = [0.485, 0.456, 0.406] std = [0.229, 0.224, 0.225] img /= 255.0 img = (img - mean) / std img = img.transpose(2, 0, 1)img=np.expand_dims(img, axis=0)img = Variable(torch.from_numpy(img).to(device).float()) print(img.shape)#使用預測模式 主要影響droupout和BN層的行為,用的是Alexnet模型,現成的 model = models.alexnet(pretrained=True).to(device).eval() #取真實標簽 label=np.argmax(model(img).data.cpu().numpy())#這里為什么要加cup()?因為np無法直接轉為cuda使用,要先轉cpu print("label={}".format(label))epoch = 1#訓練輪次 target = 31#原始圖片的標簽 target = Variable(torch.Tensor([float(target)]).to(device).long())#轉換數據類型 print(target)2、使用cleverhans實現FGSN攻擊,關鍵代碼段是
adver_example = fast_gradient_method(model, img.data, 0.01, np.inf)#(模型,圖片數據,擾動值,范數:np.inf、0或1)范數的作用占時不知道 adver_target = torch.max(model(adver_example),1)[1]#取出概率最大的那個標簽 #導入cleverhans中的FGSM函數 from cleverhans.torch.attacks.fast_gradient_method import fast_gradient_method def FGSM(model):for i in range(epoch):adver_example = fast_gradient_method(model, img.data, 0.01, np.inf)adver_target = torch.max(model(adver_example),1)[1]if adver_target != target:print("FGSM attack 成功")print("epoch={} adver_target={}".format(epoch,adver_target))return adver_example,adver_target,'FGSM attack' FGSM(model)運行結果如下,原來標簽為31,之后模型識別為114
?參考鏈接
https://github.com/cleverhans-lab/cleverhans/tree/master/examples
總結
以上是生活随笔為你收集整理的cleverhans库——FGSM代码实战的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 大功率UWB模块 XZM3000 移植手
- 下一篇: TMDB电影数据分析