原文: https://pytorch.org/tutorials/beginner/fgsm_tutorial.html
作者: Nathan Inkawhich
如果您正在閱讀本文,希望您能體會到某些機器學習模型的有效性。 研究不斷推動 ML 模型更快,更準確和更高效。 但是,設計和訓練模型的一個經(jīng)常被忽略的方面是安全性和魯棒性,尤其是在面對想要欺騙模型的對手的情況下。
本教程將提高您對 ML 模型的安全漏洞的認識,并深入了解對抗性機器學習的熱門話題。 您可能會驚訝地發(fā)現(xiàn),在圖像上添加無法察覺的擾動會導致導致完全不同的模型性能。 鑒于這是一個教程,我們將通過圖像分類器上的示例來探討該主題。 具體來說,我們將使用第一種也是最流行的攻擊方法之一,即快速梯度符號攻擊(FGSM)來欺騙 MNIST 分類器。
就上下文而言,有多種類型的對抗性攻擊,每種攻擊者的目標和假設都不同。 但是,總的來說,總體目標是向輸入數(shù)據(jù)添加最少的擾動,以引起所需的錯誤分類。 攻擊者的知識有幾種假設,其中兩種是:白盒和黑盒。 白盒攻擊假定攻擊者具有完整的知識并可以訪問模型,包括體系結構,輸入,輸出和權重。 黑盒攻擊假定攻擊者僅有權訪問模型的輸入和輸出,并且對底層體系結構或權重一無所知。 目標也有幾種類型,包括錯誤分類和源/目標錯誤分類。 錯誤分類的目標是,這意味著對手只希望輸出分類錯誤,而不在乎新分類是什么。 源/目標錯誤分類意味著對手想要更改最初屬于特定源類別的圖像,以便將其分類為特定目標類別。
在這種情況下,F(xiàn)GSM 攻擊是白盒攻擊,目標是錯誤分類。 有了這些背景信息,我們現(xiàn)在就可以詳細討論攻擊了。
迄今為止,最早的也是最流行的對抗性攻擊之一稱為快速梯度符號攻擊(FGSM),由 Goodfellow 等描述。 等 中的解釋和利用對抗性示例。 攻擊非常強大,而且直觀。 它旨在利用神經(jīng)網(wǎng)絡的學習方式梯度來攻擊神經(jīng)網(wǎng)絡。 這個想法很簡單,不是通過基于反向傳播的梯度來調整權重來使損失最小化,攻擊會基于相同的反向傳播的梯度來調整輸入數(shù)據(jù)以使損失最大化。 換句話說,攻擊使用損失了輸入數(shù)據(jù)的梯度,然后調整輸入數(shù)據(jù)以使損失最大化。
在進入代碼之前,讓我們看一下著名的 FGSM 熊貓示例,并提取一些符號。
從圖中可以看出,
是正確分類為“熊貓”的原始輸入圖像,
是
的地面真實標簽,
代表模型參數(shù),
是損失,即 用于訓練網(wǎng)絡。 攻擊將梯度反向傳播回輸入數(shù)據(jù)以計算
。 然后,它會在使損失最大化的方向(即
)上以小步長(圖片中的
或
)調整輸入數(shù)據(jù)。 當目標網(wǎng)絡仍然明顯是“熊貓”時,目標網(wǎng)絡將由此產(chǎn)生的擾動圖像
誤分類為為“長臂猿”。
希望本教程的動機已經(jīng)明確,所以讓我們跳入實施過程。
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
在本節(jié)中,我們將討論本教程的輸入?yún)?shù),定義受攻擊的模型,然后編寫攻擊代碼并運行一些測試。
本教程只有三個輸入,定義如下:
epsilons = [0, .05, .1, .15, .2, .25, .3]
pretrained_model = "data/lenet_mnist_model.pth"
use_cuda=True
如前所述,受到攻擊的模型與 pytorch / examples / mnist 中的 MNIST 模型相同。 您可以訓練并保存自己的 MNIST 模型,也可以下載并使用提供的模型。 這里的網(wǎng)絡定義和測試數(shù)據(jù)加載器已從 MNIST 示例中復制而來。 本部分的目的是定義模型和數(shù)據(jù)加載器,然后初始化模型并加載預訓練的權重。
# LeNet Model definition
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.conv1 = nn.Conv2d(1, 10, kernel_size=5)
self.conv2 = nn.Conv2d(10, 20, kernel_size=5)
self.conv2_drop = nn.Dropout2d()
self.fc1 = nn.Linear(320, 50)
self.fc2 = nn.Linear(50, 10)
def forward(self, x):
x = F.relu(F.max_pool2d(self.conv1(x), 2))
x = F.relu(F.max_pool2d(self.conv2_drop(self.conv2(x)), 2))
x = x.view(-1, 320)
x = F.relu(self.fc1(x))
x = F.dropout(x, training=self.training)
x = self.fc2(x)
return F.log_softmax(x, dim=1)
## MNIST Test dataset and dataloader declaration
test_loader = torch.utils.data.DataLoader(
datasets.MNIST('../data', train=False, download=True, transform=transforms.Compose([
transforms.ToTensor(),
])),
batch_size=1, shuffle=True)
## Define what device we are using
print("CUDA Available: ",torch.cuda.is_available())
device = torch.device("cuda" if (use_cuda and torch.cuda.is_available()) else "cpu")
## Initialize the network
model = Net().to(device)
## Load the pretrained model
model.load_state_dict(torch.load(pretrained_model, map_location='cpu'))
## Set the model in evaluation mode. In this case this is for the Dropout layers
model.eval()
得出:
Downloading http://yann.lecun.com/exdb/mnist/train-images-idx3-ubyte.gz to ../data/MNIST/raw/train-images-idx3-ubyte.gz
Extracting ../data/MNIST/raw/train-images-idx3-ubyte.gz to ../data/MNIST/raw
Downloading http://yann.lecun.com/exdb/mnist/train-labels-idx1-ubyte.gz to ../data/MNIST/raw/train-labels-idx1-ubyte.gz
Extracting ../data/MNIST/raw/train-labels-idx1-ubyte.gz to ../data/MNIST/raw
Downloading http://yann.lecun.com/exdb/mnist/t10k-images-idx3-ubyte.gz to ../data/MNIST/raw/t10k-images-idx3-ubyte.gz
Extracting ../data/MNIST/raw/t10k-images-idx3-ubyte.gz to ../data/MNIST/raw
Downloading http://yann.lecun.com/exdb/mnist/t10k-labels-idx1-ubyte.gz to ../data/MNIST/raw/t10k-labels-idx1-ubyte.gz
Extracting ../data/MNIST/raw/t10k-labels-idx1-ubyte.gz to ../data/MNIST/raw
Processing...
Done!
CUDA Available: True
現(xiàn)在,我們可以通過干擾原始輸入來定義創(chuàng)建對抗示例的函數(shù)。 fgsm_attack
函數(shù)接受三個輸入,圖像是原始的干凈圖像(
), epsilon 是像素級擾動量(
),以及[HTG7 data_grad 是輸入圖像(
)的損耗的梯度。 該函數(shù)然后創(chuàng)建擾動圖像為
最后,為了維持數(shù)據(jù)的原始范圍,將被攝動的圖像裁剪為
范圍。
# FGSM attack code
def fgsm_attack(image, epsilon, data_grad):
# Collect the element-wise sign of the data gradient
sign_data_grad = data_grad.sign()
# Create the perturbed image by adjusting each pixel of the input image
perturbed_image = image + epsilon*sign_data_grad
# Adding clipping to maintain [0,1] range
perturbed_image = torch.clamp(perturbed_image, 0, 1)
# Return the perturbed image
return perturbed_image
最后,本教程的主要結果來自test
函數(shù)。 每次調用此測試功能都會在 MNIST 測試集中執(zhí)行完整的測試步驟,并報告最終精度。 但是,請注意,此功能還需要 epsilon 輸入。 這是因為test
函數(shù)報告了具有強度
的對手所攻擊的模型的準確性。 更具體地說,對于測試集中的每個樣本,該函數(shù)都會計算輸入數(shù)據(jù)(
)的損耗梯度,使用
fgsm_attack
(
)創(chuàng)建一個擾動圖像,然后檢查是否受到擾動 例子是對抗性的。 除了測試模型的準確性外,該功能還保存并返回了一些成功的對抗示例,以供以后可視化。
def test( model, device, test_loader, epsilon ):
# Accuracy counter
correct = 0
adv_examples = []
# Loop over all examples in test set
for data, target in test_loader:
# Send the data and label to the device
data, target = data.to(device), target.to(device)
# Set requires_grad attribute of tensor. Important for Attack
data.requires_grad = True
# Forward pass the data through the model
output = model(data)
init_pred = output.max(1, keepdim=True)[1] # get the index of the max log-probability
# If the initial prediction is wrong, dont bother attacking, just move on
if init_pred.item() != target.item():
continue
# Calculate the loss
loss = F.nll_loss(output, target)
# Zero all existing gradients
model.zero_grad()
# Calculate gradients of model in backward pass
loss.backward()
# Collect datagrad
data_grad = data.grad.data
# Call FGSM Attack
perturbed_data = fgsm_attack(data, epsilon, data_grad)
# Re-classify the perturbed image
output = model(perturbed_data)
# Check for success
final_pred = output.max(1, keepdim=True)[1] # get the index of the max log-probability
if final_pred.item() == target.item():
correct += 1
# Special case for saving 0 epsilon examples
if (epsilon == 0) and (len(adv_examples) < 5):
adv_ex = perturbed_data.squeeze().detach().cpu().numpy()
adv_examples.append( (init_pred.item(), final_pred.item(), adv_ex))
else:
# Save some adv examples for visualization later
if len(adv_examples) < 5:
adv_ex = perturbed_data.squeeze().detach().cpu().numpy()
adv_examples.append( (init_pred.item(), final_pred.item(), adv_ex))
# Calculate final accuracy for this epsilon
final_acc = correct/float(len(test_loader))
print("Epsilon: {}\tTest Accuracy = {} / {} = {}".format(epsilon, correct, len(test_loader), final_acc))
# Return the accuracy and an adversarial example
return final_acc, adv_examples
實現(xiàn)的最后一部分是實際運行攻擊。 在這里,我們?yōu)?nbsp;epsilons 輸入中的每個 epsilon 值運行完整的測試步驟。 對于每個 epsilon,我們還將保存最終精度,并在接下來的部分中繪制一些成功的對抗示例。 請注意,隨著ε值的增加,打印的精度如何降低。 另外,請注意
的情況代表了原始的測試準確性,沒有受到攻擊。
accuracies = []
examples = []
## Run test for each epsilon
for eps in epsilons:
acc, ex = test(model, device, test_loader, eps)
accuracies.append(acc)
examples.append(ex)
得出:
Epsilon: 0 Test Accuracy = 9810 / 10000 = 0.981
Epsilon: 0.05 Test Accuracy = 9426 / 10000 = 0.9426
Epsilon: 0.1 Test Accuracy = 8510 / 10000 = 0.851
Epsilon: 0.15 Test Accuracy = 6826 / 10000 = 0.6826
Epsilon: 0.2 Test Accuracy = 4301 / 10000 = 0.4301
Epsilon: 0.25 Test Accuracy = 2082 / 10000 = 0.2082
Epsilon: 0.3 Test Accuracy = 869 / 10000 = 0.0869
第一個結果是精度與ε曲線的關系。 如前所述,隨著ε的增加,我們期望測試精度會降低。 這是因為較大的ε意味著我們朝著將損失最大化的方向邁出了更大的一步。 請注意,即使 epsilon 值是線性間隔的,曲線中的趨勢也不是線性的。 例如,在
處的精度僅比
低約 4%,但在
處的精度比
低 25%。 另外,請注意,對于
和
之間的 10 類分類器,模型的準確性達到了隨機準確性。
plt.figure(figsize=(5,5))
plt.plot(epsilons, accuracies, "*-")
plt.yticks(np.arange(0, 1.1, step=0.1))
plt.xticks(np.arange(0, .35, step=0.05))
plt.title("Accuracy vs Epsilon")
plt.xlabel("Epsilon")
plt.ylabel("Accuracy")
plt.show()
還記得沒有免費午餐的想法嗎? 在這種情況下,隨著 ε 的增加,測試精度降低,但的擾動變得更容易察覺。 實際上,在攻擊者必須考慮的準確性下降和可感知性之間要進行權衡。 在這里,我們展示了每個 epsilon 值的成功對抗示例。 繪圖的每一行顯示不同的ε值。 第一行是
示例,代表原始的“干凈”圖像,沒有干擾。 每張圖像的標題均顯示“原始分類->對抗分類”。 注意,擾動開始在
變得明顯,并且在
變得非常明顯。 然而,在所有情況下,盡管噪聲增加,人類仍然能夠識別正確的類別。
# Plot several examples of adversarial samples at each epsilon
cnt = 0
plt.figure(figsize=(8,10))
for i in range(len(epsilons)):
for j in range(len(examples[i])):
cnt += 1
plt.subplot(len(epsilons),len(examples[0]),cnt)
plt.xticks([], [])
plt.yticks([], [])
if j == 0:
plt.ylabel("Eps: {}".format(epsilons[i]), fontsize=14)
orig,adv,ex = examples[i][j]
plt.title("{} -> {}".format(orig, adv))
plt.imshow(ex, cmap="gray")
plt.tight_layout()
plt.show()
希望本教程對對抗性機器學習主題有所了解。 從這里可以找到許多潛在的方向。 這種攻擊代表了對抗性攻擊研究的最開始,并且由于隨后有許多關于如何攻擊和防御來自對手的 ML 模型的想法。 實際上,在 NIPS 2017 上有一個對抗性的攻擊和防御競賽,并且本文描述了該競賽中使用的許多方法:對抗性的攻擊與防御競賽。 國防方面的工作還引發(fā)了使機器學習模型總體上更健壯健壯的想法,以適應自然擾動和對抗制造的輸入。
另一個方向是不同領域的對抗性攻擊和防御。 對抗性研究不僅限于圖像領域,請查看對語音到文本模型的這種攻擊。 但是,也許更多地了解對抗性機器學習的最好方法是弄臟您的手。 嘗試實施與 NIPS 2017 競賽不同的攻擊,并查看其與 FGSM 的不同之處。 然后,嘗試保護模型免受自己的攻擊。
腳本的總運行時間:(3 分鐘 14.922 秒)
Download Python source code: fgsm_tutorial.py
Download Jupyter notebook: fgsm_tutorial.ipynb
由獅身人面像畫廊生成的畫廊
更多建議: