cleverhans库——FGSM代码实战
生活随笔
收集整理的這篇文章主要介紹了
cleverhans库——FGSM代码实战
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
什么是cleverhans庫?
cleverhans是一個機(jī)器學(xué)習(xí)模型攻防庫,里面有很多的攻防技術(shù)實(shí)現(xiàn)。安裝只需pip install cleverhans 這句口令,隨后便能調(diào)用庫里的函數(shù)。
FGSM代碼——可以直接運(yùn)行
1、使用了Alexnet模型,然后只放了一張圖片,這部分代碼主要對圖片進(jìn)行初始化,方便使用
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 #獲取計(jì)算設(shè)備 默認(rèn)是CPU device = torch.device("cuda" if torch.cuda.is_available() else "cpu")#圖像加載以及預(yù)處理 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)#使用預(yù)測模式 主要影響droupout和BN層的行為,用的是Alexnet模型,現(xiàn)成的 model = models.alexnet(pretrained=True).to(device).eval() #取真實(shí)標(biāo)簽 label=np.argmax(model(img).data.cpu().numpy())#這里為什么要加cup()?因?yàn)閚p無法直接轉(zhuǎn)為cuda使用,要先轉(zhuǎn)cpu print("label={}".format(label))epoch = 1#訓(xùn)練輪次 target = 31#原始圖片的標(biāo)簽 target = Variable(torch.Tensor([float(target)]).to(device).long())#轉(zhuǎn)換數(shù)據(jù)類型 print(target)2、使用cleverhans實(shí)現(xiàn)FGSN攻擊,關(guān)鍵代碼段是
adver_example = fast_gradient_method(model, img.data, 0.01, np.inf)#(模型,圖片數(shù)據(jù),擾動值,范數(shù):np.inf、0或1)范數(shù)的作用占時不知道 adver_target = torch.max(model(adver_example),1)[1]#取出概率最大的那個標(biāo)簽 #導(dǎo)入cleverhans中的FGSM函數(shù) 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)運(yùn)行結(jié)果如下,原來標(biāo)簽為31,之后模型識別為114
?參考鏈接
https://github.com/cleverhans-lab/cleverhans/tree/master/examples
總結(jié)
以上是生活随笔為你收集整理的cleverhans库——FGSM代码实战的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 大功率UWB模块 XZM3000 移植手
- 下一篇: TMDB电影数据分析