对抗样本中L0、L2、Linf范数的理解与实现

L0范数

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

L2范数

在这里插入图片描述
在这里插入图片描述

Linf范数

在这里插入图片描述

Code

import numpy as np
import matplotlib.pyplot as plt

#输入格式示例为:[None,224,244,3] 归一化后的数据
def show_d(img,img_adv,show=True):
    #(224*224*3)
    size=(img.shape[0])*(img.shape[1])*(img.shape[2])*(img.shape[3])
    
    print('Image Size {} Shape {}'.format(size,img.shape) )
    
    #计算该变量
    deta=img[0] - img_adv[0]
    
    #计算绝对量
    _l0 = len(np.where(np.abs(deta)>0.0)[0])   
    _l1 = np.sum(np.abs(deta))
    _l2 = np.linalg.norm(deta) 
    _linf = np.max(np.abs(deta))
    #计算相对量
    #l0 = int(99*len(np.where(np.abs(img[0] - img_adv[0])>0.5)[0]) / size ) + 1
    l0=int(_l0*99/size)+1
    l1 = int(99*np.sum(np.abs(img[0] - img_adv[0])) / np.sum(np.abs(img[0]))) + 1
    #l2 = int(99*np.linalg.norm(img[0] - img_adv[0]) / np.linalg.norm(img[0])) + 1 
    l2=int(99*_l2 / np.linalg.norm(img[0])) + 1 
    #linf = int(99*np.max(np.abs(img[0] - img_adv[0])) / 255) + 1
    linf = int(99*_linf / 255) + 1
    print('Noise L_0 norm: (absolute:){} (compare:){}%'.format(_l0,l0) )
    print('Noise L_2 norm: (absolute:){} (compare:){}%'.format(_l2,l2) )
    print('Noise L_inf norm: (absolute:){} (compare:){}%'.format(_linf,linf) )

    
    if show:
        plt.figure()

        plt.subplot(131)
        plt.title('Original')
        plt.imshow(img[0])
        plt.axis('off')

        plt.subplot(132)
        plt.title('Adversarial')
        plt.imshow(img_adv[0])
        plt.axis('off')

        plt.subplot(133)
        plt.title('Adversarial-Original')
        difference = img_adv - img

        difference=difference / abs(difference).max()/2.0+0.5

        plt.imshow(difference[0],cmap=plt.cm.gray)
        plt.axis('off')
        plt.tight_layout()
        plt.show()
    
    return (l0,l2,linf)
  • 3
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值