如果您正在閱讀本文,希望您能體會到某些機器學習模型的有效性。研究不斷推動 ML 模型更快,更準確和更高效。但是,設計和訓練模型的一個經常被忽略的方面是安全性和魯棒性,尤其是在面對想要欺騙模型的對手的情況下。
本教程將提高您對 ML 模型的安全漏洞的認識,並深入了解對抗性機器學習的熱門話題。您可能會驚訝地發現,在圖像上添加無法察覺的擾動會導致導致完全不同的模型性能。鑑於這是一個教程,我們將通過圖像分類器上的示例來探討該主題。具體來說,我們將使用第一種也是最流行的攻擊方法之一,即快速梯度符號攻擊(FGSM)來欺騙 MNIST 分類器。
威脅模型就上下文而言,有多種類型的對抗性攻擊,每種攻擊者的目標和假設都不同。但是,總的來說,總體目標是向輸入數據添加最少的擾動,以引起所需的錯誤分類。攻擊者的知識有幾種假設,其中兩種是:白盒和黑盒。 白盒攻擊假定攻擊者具有完整的知識並可以訪問模型,包括體系結構,輸入,輸出和權重。 黑盒攻擊假定攻擊者僅有權訪問模型的輸入和輸出,並且對底層體系結構或權重一無所知。目標也有幾種類型,包括錯誤分類和源/目標錯誤分類。 錯誤分類的目標是,這意味著對手只希望輸出分類錯誤,而不在乎新分類是什麼。 源/目標錯誤分類意味著對手想要更改最初屬於特定源類別的圖像,以便將其分類為特定目標類別。
在這種情況下,FGSM 攻擊是白盒攻擊,目標是錯誤分類。有了這些背景信息,我們現在就可以詳細討論攻擊了。
快速梯度符號攻擊迄今為止,最早的也是最流行的對抗性攻擊之一稱為快速梯度符號攻擊(FGSM),由 Goodfellow 等描述。等 中的解釋和利用對抗性示例。攻擊非常強大,而且直觀。它旨在利用神經網絡的學習方式梯度來攻擊神經網絡。這個想法很簡單,不是通過基於反向傳播的梯度來調整權重來使損失最小化,攻擊會基於相同的反向傳播的梯度來調整輸入數據以使損失最大化。換句話說,攻擊使用損失了輸入數據的梯度,然後調整輸入數據以使損失最大化。
在進入代碼之前,讓我們看一下著名的 FGSM 熊貓示例,並提取一些符號。
從圖中可以看出,是正確分類為「熊貓」的原始輸入圖像,是的地面真實標籤,代表模型參數,是損失,即 用於訓練網絡。攻擊將梯度反向傳播回輸入數據以計算。然後,它會在使損失最大化的方向(即)上以小步長(圖片中的或)調整輸入數據。當目標網絡仍然明顯是「熊貓」時,目標網絡將由此產生的擾動圖像誤分類為為「長臂猿」。
希望本教程的動機已經明確,所以讓我們跳入實施過程。
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 pltCopy
在本節中,我們將討論本教程的輸入參數,定義受攻擊的模型,然後編寫攻擊代碼並運行一些測試。
輸入項本教程只有三個輸入,定義如下:
epsilons -用於運行的 epsilon 值列表。在列表中保留 0 很重要,因為它表示原始測試集上的模型性能。同樣,從直覺上講,我們期望ε越大,擾動越明顯,但是從降低模型準確性的角度來看,攻擊越有效。由於此處的數據範圍是,因此 epsilon 值不得超過 1。
pretrained_model -使用 pytorch / examples / mnist 訓練的預訓練 MNIST 模型的路徑。為簡單起見,請在此處下載預訓練模型。
use_cuda -布爾標誌,如果需要和可用,則使用 CUDA。請注意,具有 CUDA 的 GPU 在本教程中並不重要,因為 CPU 不會花費很多時間。
epsilons = [0, .05, .1, .15, .2, .25, .3]
pretrained_model = "data/lenet_mnist_model.pth"
use_cuda=TrueCopy
如前所述,受到攻擊的模型與 pytorch / examples / mnist 中的 MNIST 模型相同。您可以訓練並保存自己的 MNIST 模型,也可以下載並使用提供的模型。這裡的網絡定義和測試數據加載器已從 MNIST 示例中複製而來。本部分的目的是定義模型和數據加載器,然後初始化模型並加載預訓練的權重。
# 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()Copy
出:
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: TrueCopy
現在,我們可以通過幹擾原始輸入來定義創建對抗示例的函數。 fgsm_attack函數接受三個輸入,圖像是原始的乾淨圖像(), epsilon 是像素級擾動量(),以及[HTG7 data_grad 是輸入圖像()的損耗的梯度。該函數然後創建擾動圖像為
最後,為了維持數據的原始範圍,將被攝動的圖像裁剪為範圍。
# 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_imageCopy
最後,本教程的主要結果來自test函數。每次調用此測試功能都會在 MNIST 測試集中執行完整的測試步驟,並報告最終精度。但是,請注意,此功能還需要 epsilon 輸入。這是因為test函數報告了具有強度的對手所攻擊的模型的準確性。更具體地說,對於測試集中的每個樣本,該函數都會計算輸入數據()的損耗梯度,使用fgsm_attack()創建一個擾動圖像,然後檢查是否受到擾動 例子是對抗性的。除了測試模型的準確性外,該功能還保存並返回了一些成功的對抗示例,以供以後可視化。
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_examplesCopy
實現的最後一部分是實際運行攻擊。在這裡,我們為 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)Copy
Out:
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.0869Copy
第一個結果是精度與ε曲線的關係。如前所述,隨著ε的增加,我們期望測試精度會降低。這是因為較大的ε意味著我們朝著將損失最大化的方向邁出了更大的一步。請注意,即使 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()Copy
還記得沒有免費午餐的想法嗎?在這種情況下,隨著ε的增加,測試精度降低,但的擾動變得更容易察覺。實際上,在攻擊者必須考慮的準確性下降和可感知性之間要進行權衡。在這裡,我們展示了每個 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()Copy