对抗网络学习-FGSM对抗样本生成
對(duì)抗樣本指的是一個(gè)經(jīng)過(guò)微小調(diào)整就可以讓機(jī)器學(xué)習(xí)算法輸出錯(cuò)誤結(jié)果的輸入樣本。在圖像識(shí)別中,可以理解為原來(lái)被一個(gè)卷積神經(jīng)網(wǎng)絡(luò)(CNN)分類(lèi)為一個(gè)類(lèi)(比如“熊貓”)的圖片,經(jīng)過(guò)非常細(xì)微甚至人眼無(wú)法察覺(jué)的改動(dòng)后,突然被誤分成另一個(gè)類(lèi)(比如“長(zhǎng)臂猿”)。
為什么這樣輕微的擾動(dòng)可以對(duì)神經(jīng)網(wǎng)絡(luò)造成如此大的影響,業(yè)界目前的共識(shí)認(rèn)為這不是過(guò)擬合的結(jié)果,而是因?yàn)檩斎胩卣骶S度過(guò)高和模型的線性性質(zhì)導(dǎo)致的。
深度模型本實(shí)確實(shí)是一個(gè)非常非線性的模型,但是模型的組成部分都是線性的,全連接網(wǎng)絡(luò)的矩陣乘法是線性的,卷積網(wǎng)絡(luò)的卷積計(jì)算也是計(jì)算點(diǎn)乘,同樣也是線性的,哪怕是激活函數(shù),看似是為了造成模型的非線性,但是目前主流的relu激活函數(shù)其實(shí)在部分區(qū)域內(nèi)也是線性的。
因此,盡管深度模型整體呈非線性,但是其中的線性部分卻依舊占了很大一部分,也正是如此,輕微的擾動(dòng)經(jīng)過(guò)網(wǎng)絡(luò)的積累后會(huì)形成雪崩效應(yīng),從而對(duì)最終結(jié)果造成影響。
更具體的來(lái)說(shuō),在高維空間中,每個(gè)像素值即使改變很小,這些改變會(huì)通過(guò)線性模型的參數(shù)進(jìn)行點(diǎn)乘累計(jì)造成很明顯的變化。只要方向正確,即使數(shù)據(jù)上只是邁出了一小步,在特征空間上就是一大步,極大概率會(huì)跨越?jīng)Q策層。
Fast Gradient Sign Method (FGSM)
關(guān)鍵公式
x′=x+η
η =εsign(▽xJ(θ,x,y))
參數(shù)解釋:
x -輸入圖象 ,x^′-輸出圖像, η-擾動(dòng)
ε-步長(zhǎng),即擾動(dòng)大小
Sign()-符號(hào)函數(shù),J(θ,x,y)損失函數(shù)
θ -模型參數(shù),x-模型輸入,y-標(biāo)簽
主要思想
攻擊成功的目標(biāo)是使得模型分類(lèi)錯(cuò)誤,也即是利用加入擾動(dòng)的樣本使得模型的損失增大,而我們沿著梯度方向添加擾動(dòng),可以對(duì)分類(lèi)結(jié)果產(chǎn)生最大的影響,因?yàn)槲覀円话闶茄刂荻认陆档姆较蛉p小損失函數(shù)。
代碼實(shí)現(xiàn)
from __future__ import absolute_import, division, print_function, unicode_literals import warnings warnings.filterwarnings('ignore') import tensorflow as tf import matplotlib as mpl import matplotlib.pyplot as plt mpl.rcParams['figure.figsize'] = (8, 8) mpl.rcParams['axes.grid'] = False #MobileNetV2# Let's load the pretained MobileNetV2 model and the ImageNet class names. pretrained_model = tf.keras.applications.MobileNetV2(include_top=True, weights='imagenet') pretrained_model.trainable = False# ImageNet labels decode_predictions = tf.keras.applications.mobilenet_v2.decode_predictions# Helper function to preprocess the image so that it can be inputted in MobileNetV2 # 對(duì)圖像預(yù)處理,使得圖像可以輸入MobileNetV2模型 def preprocess(image):image = tf.cast(x=image, dtype=tf.float32)image = image/255image = tf.image.resize(images=image, size=(224, 224))image = image[None, ...]return image# Helper function to extract labels from probability vector # 得到圖像真實(shí)標(biāo)簽 將圖像輸入模型并得到概率最高的分類(lèi)結(jié)果 def get_imagenet_label(probs):return decode_predictions(probs, top=1)[0][0]#只獲取第一個(gè)#image_path = tf.keras.utils.get_file(fname='YellowLabradorLooking_new.jpg', origin='https://storage.googleapis.com/download.tensorflow.org/example_images/YellowLabradorLooking_new.jpg')#image_path=tf.keras.utils.get_file('turtle.jpg','https://storage.googleapis.com/download.tensorflow.org/example_images/Green_Sea_Turtle_grazing_seagrass.jpg') image_path = tf.keras.utils.get_file(fname='grace_hopper.jpg', origin='https://storage.googleapis.com/download.tensorflow.org/example_images/grace_hopper.jpg') image_raw = tf.io.read_file(filename=image_path)image = tf.image.decode_image(contents=image_raw)#可以自動(dòng)判定圖像格式然后 decodeimage = preprocess(image)#預(yù)處理 image_probs = pretrained_model.predict(image) #模型預(yù)測(cè),輸入測(cè)試集,輸出預(yù)測(cè)結(jié)果---概率plt.figure() plt.imshow(image[0]) _, image_class, class_confidence = get_imagenet_label(image_probs)#probs? plt.title('{} : {:.2f}% Confidence'.format(image_class, class_confidence*100))#加入標(biāo)簽 plt.show()#計(jì)算梯度 loss_object = tf.keras.losses.CategoricalCrossentropy()#損失函數(shù)--交叉熵?fù)p失函數(shù) #交叉熵是用來(lái)評(píng)估當(dāng)前訓(xùn)練得到的概率分布與真實(shí)分布的差異情況。 #它刻畫(huà)的是實(shí)際輸出(概率)與期望輸出(概率)的距離,也就是交叉熵的值越小,兩個(gè)概率分布就越接近。def create_adversarial_pattern(input_image, input_label):with tf.GradientTape() as tape: #梯度帶tape.watch(tensor=input_image) #watch函數(shù)把需要計(jì)算梯度的變量input_image加進(jìn)來(lái)prediction = pretrained_model(input_image)loss = loss_object(input_label, prediction)# Get the gradients of the loss w.r.t to the input image.獲取梯度gradient = tape.gradient(loss, input_image)# Get the sign of the gradients to create the perturbation.獲取符號(hào)signed_grad = tf.sign(gradient) # 符號(hào)梯度攻擊return signed_grad# Get the input label of the image. labrador_retriever_index = 208 label = tf.one_hot(labrador_retriever_index, image_probs.shape[-1]) label = tf.reshape(label, (1, image_probs.shape[-1]))perturbations = create_adversarial_pattern(image, image_probs) plt.imshow(perturbations[0]) #定義函數(shù)來(lái)顯示圖像 def display_images(image, description): # 展示被攻擊過(guò)的圖像_, label, confidence = get_imagenet_label(pretrained_model.predict(image))plt.figure()plt.imshow(image[0])plt.title('{} \n {} : {:.2f}% Confidence'.format(description,label, confidence*100))plt.show()#加入噪聲后再將圖像輸入模型進(jìn)行判斷 epsilons = [0, 0.01, 0.1, 0.15, 0.20] descriptions = [('Epsilon = {:0.3f}'.format(eps) if eps else 'Input') for eps in epsilons]for i, eps in enumerate(epsilons):adv_x = image + eps*perturbations[0]adv_x = tf.clip_by_value(adv_x, 0, 1) # 將值限制在[0,1]范圍內(nèi)display_images(adv_x, descriptions[i])
參考鏈接
https://blog.csdn.net/nemoyy/article/details/81052301
https://blog.csdn.net/nemoyy/article/details/81052301
https://download.csdn.net/download/qq_35225463/11646431
總結(jié)
以上是生活随笔為你收集整理的对抗网络学习-FGSM对抗样本生成的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 交叉小波分析matlab,[转载]Mat
- 下一篇: MicroSIP编译完全手册