AI Wiki中文/EN

视觉模型鲁棒性:模型究竟挺过了哪些变化?

Robustness in vision

用完整小分类器测量退化、预测稳定性、校准和有界攻击,区分有限搜索结果与数学保证。

本页目录直觉理解数学与方法代码实现局限与误解实验与练习研究脉络

干净测试全对,仍有几件事没问清楚

小型视觉模型在一种测试条件下张张答对。加入噪声,它的行为变了;让图像连续移动,预测可能来回跳;按照模型自己的梯度改变像素,它又可能失败。这些是视觉模型鲁棒性(visual robustness)的不同测试,不能当成同一分数的几个别名。

本文实现完整分类器、受控退化、序列稳定性、置信度指标,以及白盒攻击候选池。目的是让评测约定可检查:究竟哪些图像、变化、标签、归一化和分母产生了结果。视觉数据增强解释了本文两种训练流程的构造。

先问怎样才算失败,会更容易读懂这些指标。始终猜错同一类别,也可以完全稳定;校准良好的抛硬币式分类器,准确率可能很低;挺过一种攻击的模型,也可能被同一允许扰动集合中的另一种搜索击败。不用大型基准,也能检查这些说法。

实际图像与分别定义的评测。攻击曲线先保留每张图已见候选的最大损失,再求平均;校准来自独立含噪样本。
实际图像与分别定义的评测。攻击曲线先保留每张图已见候选的最大损失,再求平均;校准来自独立含噪样本。

先写评测约定,再计算分数

退化、稳定性与对抗评测

设D是带标签图像分布,Q是明确声明、与分类器无关的退化分布,退化准确率可写为:

AQ(f)=E(x,y)∼D, c∼Q[1{f(c(x))=y}].A_Q(f)=\mathbb E_{(x,y)\sim D,\,c\sim Q}\big[\mathbf1\{f(c(x))=y\}\big].

保留原标签本身是一项假设:退化图像仍须代表目标类别。遮住整个对象,或旋转一个由方向定义类别的对象,可能破坏这项假设。基准分布Q也是一种选择,不等于实际部署中各类故障发生频率的测量。

ImageNet-C组织了15类退化,每类五种强度;ImageNet-P评估较小变化构成的序列。其协议将基准评测与针对测试退化的训练分开。这能提供可复现比较,但不能证明覆盖了每种真实相机、天气或用户群体。退化与扰动论文,§§3–4

按约定顺序平均误差

设e_cs为模型在退化类型c、强度s上的错误率,b_cs为参考模型在相同条件下的错误率。论文的归一化退化误差及均值为:

CE⁡c=∑s=1Secs∑s=1Sbcs,mCE⁡=1C∑c=1CCE⁡c.\operatorname{CE}_c=\frac{\sum_{s=1}^{S}e_{cs}}{\sum_{s=1}^{S}b_{cs}},\qquad \operatorname{mCE}=\frac1C\sum_{c=1}^{C}\operatorname{CE}_c.

原基准取C=15、S=5,参考模型为AlexNet。本函数显式接收误差矩阵和参考矩阵;演示使用三类自定义退化、三个等级和常类别参考。输出是比值,不是概率,也不是ImageNet-C结果。参考分母为零时拒绝计算。先平均各个e_cs/b_cs,通常会得到另一个答案。论文,§4.2

还应核对印刷公式中的另一项约定:Relative CE从各强度误差之和中,只减一次干净错误率:

RelativeCE⁡c=∑secs−eclean∑sbcs−bclean.\operatorname{RelativeCE}_c= \frac{\sum_s e_{cs}-e_{\rm clean}}{\sum_s b_{cs}-b_{\rm clean}}.

本例保留这个约定,并推广到所给等级数;它不是平均超额误差公式。若五个退化错误率和干净错误率都为0.2,对应参考值都为0.4,比值为0.8/1.6=0.5,而不是零。测试会抓住“换了聚合方式,却继续使用同一个名字”的问题。

固定版本ImageNet-C测试脚本平均五个强度的错误率,遍历包括四类验证退化在内的19个名字,并明确打印未归一化结果。因此,不读细节就运行该文件,并不会自动复现论文中15类、经归一化的指标。固定评测器,第219–288行

稳定性需要约定比较对象

对N个长度为T的预测序列,相邻帧翻转概率为:

FP⁡adjacent=1N(T−1)∑i=1N∑t=2T1{f(xit)≠f(xi,t−1)}.\operatorname{FP}_{\rm adjacent}= \frac1{N(T-1)}\sum_{i=1}^{N}\sum_{t=2}^{T} \mathbf1\{f(x_{it})\ne f(x_{i,t-1})\}.

如果各含噪帧独立地从第一张干净图生成,就应把后续帧与这张参考图比较:

FP⁡reference=1N(T−1)∑i=1N∑t=2T1{f(xit)≠f(xi1)}.\operatorname{FP}_{\rm reference}= \frac1{N(T-1)}\sum_{i=1}^{N}\sum_{t=2}^{T} \mathbf1\{f(x_{it})\ne f(x_{i1})\}.

论文与已核实现区分了这两种情况。实现还按难度改变时间步长;本演示只用相邻帧。归一化翻转率会把原始翻转概率再除以参考值,所以两者不能放进一个没有注明区别的列。论文,§4.2 固定翻转函数,第257–274行

两个公式都不含真实标签,预测可以稳定地一起错。本例平移序列来自独立的居中图集,并检查每帧至少保留三个明亮条纹像素,避免小型教学序列意外变成“对象被移除”的测试。

校准问的是置信度是否符合正确率

以p-hat_i表示最大预测类别概率,y-hat_i表示对应类别。对非空置信度桶B_m,定义:

acc⁡(Bm)=1∣Bm∣∑i∈Bm1{y^i=yi},conf⁡(Bm)=1∣Bm∣∑i∈Bmp^i.\operatorname{acc}(B_m)=\frac1{|B_m|}\sum_{i\in B_m}\mathbf1\{\widehat y_i=y_i\},\qquad \operatorname{conf}(B_m)=\frac1{|B_m|}\sum_{i\in B_m}\widehat p_i.

经验期望校准误差为:

ECE⁡=∑m: ∣Bm∣>0∣Bm∣N∣acc⁡(Bm)−conf⁡(Bm)∣.\operatorname{ECE}=\sum_{m:\,|B_m|>0}\frac{|B_m|}{N} \left|\operatorname{acc}(B_m)-\operatorname{conf}(B_m)\right|.

本例用五个等宽桶,左闭右开,最后一桶额外包含置信度一。Guo等人的论文采用相反的端点约定,即右闭桶;恰好落在边界时,样本归属可能不同。空桶没有贡献。有限的小样本和分桶方式,都会限制ECE能够证明的内容。校准论文,§2

还报告平均负对数似然,以及沿类别求和的Brier分数:

NLL⁡=−1N∑ilog⁡pi,yi,Brier⁡=1N∑i∑c(pic−1{c=yi})2.\operatorname{NLL}=-\frac1N\sum_i\log p_{i,y_i},\qquad \operatorname{Brier}=\frac1N\sum_i\sum_c\left(p_{ic}-\mathbf1\{c=y_i\}\right)^2.

引用论文将NLL写成总和,本例除以N;这里的Brier不再除以类别数。对平衡二分类集,全部输出[0.5,0.5]并固定平局处理规则,准确率为0.5,若归入同一桶,ECE却为零。因此,校准不是准确率的另一个名字。校准论文,§2

用像素单位定义攻击集合

对[0,1]^d内的归一化像素x,本例允许的数字扰动是以下交集:

Sϵ(x)={u∈[0,1]d:∥u−x∥∞≤ϵ}.\mathcal S_\epsilon(x)=\{u\in[0,1]^d:\|u-x\|_\infty\leq\epsilon\}.

它限制每个像素的变化,不是在涵盖所有感知相似图像或所有真实相机变化。如果模型包含预处理,要同时处理单位和导数;原像素中的预算,不会自动等于通道归一化后的预算。Madry等人用明确的扰动集合及内部损失最大化来表述对抗评测。鲁棒优化形式,§2

固定模型参数,以g表示输入损失梯度。在像素值域裁剪尚未起作用时,线性化目标的盒约束最优解为:

L(x+δ)≈L(x)+gTδ,max⁡∥δ∥∞≤ϵgTδ=ϵ∥g∥1,δ∗=ϵsign⁡(g).L(x+\delta)\approx L(x)+g^T\delta,\qquad \max_{\|\delta\|_\infty\leq\epsilon}g^T\delta=\epsilon\|g\|_1, \qquad\delta^*=\epsilon\operatorname{sign}(g).

每个坐标独立选择与梯度符号一致的可行端点,就得到快速梯度符号法FGSM。对本例额外的像素盒约束,将各坐标裁到交集中,也能求解对应的线性子问题;但这不等于精确求解非线性网络的最坏情况。FGSM论文,§§3–4

投影梯度步骤在当前候选点重新计算梯度:

ut+1=ΠSϵ(x)(ut+ηsign⁡∇uL(θ,ut,y)).u^{t+1}=\Pi_{\mathcal S_\epsilon(x)}\left(u^t+\eta\operatorname{sign}\nabla_u L(\theta,u^t,y)\right).

投影中心始终是原图x,不能改成上一步迭代点。eta是步长,epsilon是每坐标的总预算。多个随机起点会探索不同路径,但仍是有限搜索。本模型没有批量归一化或dropout,攻击评测期间参数保持固定。PGD讨论,§§2.1–3.1

搜索结果的不确定性有方向

对同一个有限带标签测试集,令A_i为已经评测的候选池,包含x_i且位于S_epsilon(x_i)内。对正确性指示量取下确界,定义最坏情况和候选池准确率:

A^robust=1N∑iinf⁡u∈Sϵ(xi)1{f(u)=yi},A^pool=1N∑imin⁡u∈Ai1{f(u)=yi}.\widehat A_{\rm robust}=\frac1N\sum_i\inf_{u\in\mathcal S_\epsilon(x_i)}\mathbf1\{f(u)=y_i\},\qquad \widehat A_{\rm pool}=\frac1N\sum_i\min_{u\in A_i}\mathbf1\{f(u)=y_i\}.

由集合包含关系可得:

A^robust≤A^pool≤A^clean.\widehat A_{\rm robust}\leq\widehat A_{\rm pool}\leq\widehat A_{\rm clean}.

这是同一有限测试集上的界,不是总体置信区间。找到反例,能证明那张图失败;没找到反例,不能证明鲁棒。应保留所有候选中发现的失败,而不只看最后一次迭代。多类别下,最高损失候选未必是分类判断唯一需要关心的候选,因此程序另行记录是否有任一候选答错。

保存的最佳损失曲线之所以单调,是因为始终对已经看过的候选取最大值。这不能证明每条PGD轨迹单调改善,更不能证明其最大值是全局最优。

完整模型与四类评测

将程序保存为 vision_robustness.py,安装NumPy后运行 python vision_robustness.py。记录环境为Python 3.12.4、NumPy 1.26.4。分类器采用从一到四通道的有效3×3卷积、ReLU、144维展平特征及二分类头,共330个存储参数,全部实现反向传播。

训练图40张,种子11;参数种子7,变换种子17。两个模型各执行120次Adam更新,学习率0.01,系数0.9/0.999,epsilon为1e−8。一种看居中图像,另一种接受随机整数平移。主要测试使用种子29的80张位置变化图;序列图则独立采用种子47生成居中位置。没有根据测试结果选择策略。

三类自定义退化是:标准差0.08s的裁值高斯噪声;以1/(1+s)比例向0.5缩放的对比度;以s/3权重混合3×3反射填充盒模糊,s取1、2、3。退化随机种子37,另一个高噪声校准样本使用种子43。这不是ImageNet-C生成流程。平衡二分类中的常类别参考,每个强度错误率均为0.5。

攻击评测取epsilon=0.2、步长0.04、12步、三个随机起点,种子31,还纳入原图和FGSM候选。每图共41个候选:两个初始候选,加三组“随机起点及12次更新”。返回的输入梯度来自平均损失;在这个图像间独立的模型中,正的批量缩放不影响符号步骤。

"""Original complete small vision model and declared robustness evaluations.

Custom synthetic corruptions, reference-normalized errors, sequence stability,
calibration and a white-box Linf candidate pool. No ImageNet or certified claim.
"""
import json
import numpy as np

def finite(x,shape=None):
    x=np.asarray(x,dtype=float)
    if not np.isfinite(x).all() or (shape is not None and x.shape!=shape):raise ValueError('Finite matching arrays required')
    return x


def count(n,minimum=1):
    if isinstance(n,(bool,np.bool_)) or not isinstance(n,(int,np.integer)) or not minimum<=n<=4096:raise ValueError('Integer count out of range')
    return int(n)


def convolve(x,w,b):
    x=finite(x);w=finite(w);b=finite(b)
    if x.ndim!=4 or w.ndim!=4 or b.shape!=(w.shape[3],) or x.shape[-1]!=w.shape[2] or not x.size:raise ValueError('NHWC image and HWIO kernel required')
    kh,kw,ci,co=w.shape;n,h,width,_=x.shape;oh=h-kh+1;ow=width-kw+1
    if min(kh,kw,ci,co,oh,ow)<1:raise ValueError('Kernel does not fit input')
    patches=np.stack([x[:,i:i+oh,j:j+ow,:] for i in range(kh) for j in range(kw)],axis=-2)
    result=patches.reshape(-1,kh*kw*ci)@w.reshape(-1,co)+b
    return result.reshape(n,oh,ow,co),(x,w,patches)


def convolve_vjp(g,cache):
    x,w,patches=cache;n,oh,ow=patches.shape[:3];kh,kw,ci,co=w.shape;g=finite(g,(n,oh,ow,co))
    flat=g.reshape(-1,co);dw=(patches.reshape(-1,kh*kw*ci).T@flat).reshape(w.shape);db=flat.sum(axis=0)
    dp=(flat@w.reshape(-1,co).T).reshape(n,oh,ow,kh*kw,ci);dx=np.zeros_like(x)
    for i in range(kh):
        for j in range(kw):dx[:,i:i+oh,j:j+ow,:]+=dp[:,:,:,i*kw+j,:]
    return dx,dw,db


def dataset(number,seed,spread=0):
    n=count(number);s=count(spread,0)
    if s>2:raise ValueError('This bar generator supports spread at most two')
    rng=np.random.default_rng(seed);labels=np.arange(n)%2;images=np.full((n,8,8,1),.12)
    for i,label in enumerate(labels):
        row,col=np.array([3,3])+rng.integers(-s,s+1,size=2)
        if label==0:images[i,max(0,row-2):min(8,row+3),col,0]=rng.uniform(.7,.95)
        else:images[i,row,max(0,col-2):min(8,col+3),0]=rng.uniform(.7,.95)
    return np.clip(images+rng.normal(0,.015,images.shape),0,1),labels


def translate(x,dy,dx):
    x=finite(x)
    if x.ndim!=4 or not x.size:raise ValueError('Nonempty NHWC images required')
    for value in [dy,dx]:
        if isinstance(value,(bool,np.bool_)) or not isinstance(value,(int,np.integer)):raise ValueError('Integer shifts required')
    h,w=x.shape[1:3];out=np.zeros_like(x)
    if abs(dy)>=h or abs(dx)>=w:return out
    sy=slice(max(0,-dy),min(h,h-dy));sx=slice(max(0,-dx),min(w,w-dx))
    ty=slice(max(0,dy),min(h,h+dy));tx=slice(max(0,dx),min(w,w+dx))
    out[:,ty,tx]=x[:,sy,sx];return out


def initialize(seed=7):
    rng=np.random.default_rng(seed)
    return {'conv':rng.normal(0,.15,(3,3,1,4)),'bias':np.full(4,.1),'head':rng.normal(0,.08,(144,2)),'output_bias':np.zeros(2)}


def forward(x,p):
    x=finite(x)
    if x.ndim!=4 or x.shape[1:]!=(8,8,1) or not len(x):raise ValueError('N x 8 x 8 x 1 input required')
    if set(p)!={'conv','bias','head','output_bias'}:raise ValueError('All classifier parameter arrays required')
    head=finite(p['head'],(144,2));bias=finite(p['output_bias'],(2,))
    activations,cache=convolve(x,finite(p['conv'],(3,3,1,4)),finite(p['bias'],(4,)))
    features=np.maximum(activations,0).reshape(len(x),-1)
    return features@head+bias,(activations,features,cache,head)


def backward(g,cache):
    a,features,conv,head=cache;g=finite(g,(len(features),2));dh=(g@head.T).reshape(a.shape)*(a>0)
    dx,dw,db=convolve_vjp(dh,conv)
    return {'conv':dw,'bias':db,'head':features.T@g,'output_bias':g.sum(axis=0)},dx


def log_probabilities(logits):
    logits=finite(logits)
    if logits.ndim<2 or logits.shape[-1]<2 or not logits.size:raise ValueError('Nonempty logits with at least two classes required')
    shifted=logits-logits.max(axis=-1,keepdims=True)
    return shifted-np.log(np.exp(shifted).sum(axis=-1,keepdims=True))


def cross_entropy(logits,labels):
    logits=finite(logits);labels=np.asarray(labels)
    if logits.ndim!=2 or labels.shape!=(len(logits),) or not np.issubdtype(labels.dtype,np.integer) or np.any(labels<0) or np.any(labels>=logits.shape[-1]):raise ValueError('Integer class labels required')
    logp=log_probabilities(logits);gradient=np.exp(logp);gradient[np.arange(len(labels)),labels]-=1
    return float(-logp[np.arange(len(labels)),labels].mean()),gradient/len(labels)


def evaluate(x,labels,p):
    logits=forward(x,p)[0];value,_=cross_entropy(logits,labels)
    return {'accuracy':float(np.mean(logits.argmax(axis=1)==labels)),'cross_entropy':value}


def train(steps=120,shift=True):
    steps=count(steps);x,labels=dataset(40,11);p=initialize();rng=np.random.default_rng(17);history=[]
    first={k:np.zeros_like(v) for k,v in p.items()};second={k:np.zeros_like(v) for k,v in p.items()}
    for step in range(1,steps+1):
        images=np.array([translate(x[i:i+1],*rng.integers(-2,3,2))[0] for i in range(len(x))]) if shift else x
        logits,cache=forward(images,p);value,g=cross_entropy(logits,labels);grads,_=backward(g,cache);history.append(value)
        for key in p:
            first[key]=.9*first[key]+.1*grads[key];second[key]=.999*second[key]+.001*grads[key]**2
            p[key]-=.01*(first[key]/(1-.9**step))/(np.sqrt(second[key]/(1-.999**step))+1e-8)
    return p,history


def corruption(x,kind,severity,rng):
    x=finite(x);level=count(severity)
    if x.ndim!=4 or x.shape[1:]!=(8,8,1) or not len(x) or level>3:raise ValueError('Synthetic images and severity 1..3 required')
    if kind=='noise':return np.clip(x+rng.normal(0,.08*level,x.shape),0,1)
    if kind=='contrast':return .5+(x-.5)/(1+level)
    if kind=='blur':
        padded=np.pad(x,((0,0),(1,1),(1,1),(0,0)),mode='reflect')
        blurred=sum(padded[:,i:i+8,j:j+8] for i in range(3) for j in range(3))/9
        return (1-level/3)*x+level/3*blurred
    raise ValueError('Unknown synthetic corruption')


def corruption_errors(errors,reference,clean=None,reference_clean=None):
    errors=finite(errors);reference=finite(reference,errors.shape)
    if errors.ndim!=2 or not errors.size or np.any((errors<0)|(errors>1)|(reference<0)|(reference>1)):raise ValueError('Type x severity error rates in [0,1] required')
    denominator=reference.sum(axis=1)
    if np.any(denominator<=0):raise ValueError('Reference severity sum must be positive')
    ce=errors.sum(axis=1)/denominator;result={'per_type_ce':ce.tolist(),'mean_ce':float(ce.mean()),'raw_mean_error':float(errors.mean())}
    if clean is not None or reference_clean is not None:
        if clean is None or reference_clean is None or not np.isfinite([clean,reference_clean]).all() or not 0<=clean<=1 or not 0<=reference_clean<=1:raise ValueError('Both clean error rates required')
        # Paper single-clean-subtraction convention, generalized to the supplied severity count.
        denom=denominator-reference_clean
        if np.any(denom<=0):raise ValueError('Relative reference denominator must be positive')
        relative=(errors.sum(axis=1)-clean)/denom
        result['paper_relative_ce']=relative.tolist();result['paper_relative_mean_ce']=float(relative.mean())
    return result


def flip_probability(predictions,comparison='adjacent'):
    predictions=np.asarray(predictions)
    if predictions.ndim!=2 or predictions.shape[1]<2 or not predictions.size or not np.issubdtype(predictions.dtype,np.integer):raise ValueError('Integer sequence x time predictions required')
    if comparison=='adjacent':reference=predictions[:,:-1]
    elif comparison=='clean-reference':reference=predictions[:,:1]
    else:raise ValueError('Unknown sequence comparison')
    return float(np.mean(predictions[:,1:]!=reference))


def calibration(logits,labels,bins=5):
    bins=count(bins);logits=finite(logits);nll,_=cross_entropy(logits,labels);labels=np.asarray(labels)
    probabilities=np.exp(log_probabilities(logits));pred=probabilities.argmax(axis=1);confidence=probabilities.max(axis=1);correct=pred==labels
    indices=np.minimum((confidence*bins).astype(int),bins-1);ece=0.;rows=[]
    for i in range(bins):
        mask=indices==i;n=int(mask.sum())
        if n:
            accuracy=float(correct[mask].mean());conf=float(confidence[mask].mean());ece+=n/len(labels)*abs(conf-accuracy)
            rows.append({'bin':i,'count':n,'accuracy':accuracy,'confidence':conf})
    onehot=np.eye(logits.shape[1])[labels]
    return {'accuracy':float(correct.mean()),'nll':nll,'brier_sum_over_classes':float(np.mean(np.sum((probabilities-onehot)**2,axis=1))),'ece':float(ece),'bins':bins,'nonempty_bins':rows}


def per_image_loss_and_gradient(x,labels,p):
    """Individual losses, gradient of their mean, and predicted classes."""
    logits,cache=forward(x,p);_,g=cross_entropy(logits,labels);_,dx=backward(g,cache)
    logp=log_probabilities(logits)
    return -logp[np.arange(len(labels)),labels],dx,logits.argmax(axis=1)


def project(candidate,original,epsilon):
    original=finite(original);candidate=finite(candidate,original.shape)
    if not np.isfinite(epsilon) or not 0<=epsilon<=1 or np.any((original<0)|(original>1)):raise ValueError('Pixel-domain input and epsilon in [0,1] required')
    return np.clip(candidate,np.maximum(0,original-epsilon),np.minimum(1,original+epsilon))


def attack_pool(x,labels,p,epsilon=.2,steps=12,restarts=3,step_size=.04,seed=31):
    x=finite(x);steps=count(steps);restarts=count(restarts)
    if not np.isfinite(step_size) or step_size<=0:raise ValueError('Positive finite step size required')
    project(x,x,epsilon);best=x.copy();best_loss,gradient,pred=per_image_loss_and_gradient(x,labels,p);wrong=pred!=labels;history=[float(best_loss.mean())]
    def consider(candidate):
        nonlocal best,best_loss,wrong
        values,_,prediction=per_image_loss_and_gradient(candidate,labels,p);improved=values>best_loss
        best[improved]=candidate[improved];best_loss=np.maximum(best_loss,values);wrong|=prediction!=labels;history.append(float(best_loss.mean()))
    # Include clean and FGSM candidates before random-start PGD, keeping all observed failures.
    fgsm=project(x+epsilon*np.sign(gradient),x,epsilon);consider(fgsm);fgsm_wrong=per_image_loss_and_gradient(fgsm,labels,p)[2]!=labels
    rng=np.random.default_rng(seed)
    for _ in range(restarts):
        candidate=project(x+rng.uniform(-epsilon,epsilon,x.shape),x,epsilon);consider(candidate)
        for _ in range(steps):
            _,g,_=per_image_loss_and_gradient(candidate,labels,p);candidate=project(candidate+step_size*np.sign(g),x,epsilon);consider(candidate)
    return best,{'candidate_pool_robust_accuracy':float(np.mean(~wrong)),'fgsm_accuracy':float(np.mean(~fgsm_wrong)),
                 'found_wrong':wrong.tolist(),'best_loss_trace':history,'max_linf':float(np.max(np.abs(best-x))),
                 'candidates_per_image':len(history),'note':'Clean + FGSM + random-start PGD candidates. Observed robust accuracy is an upper bound on true worst-case robust accuracy, not a certificate.'}


def demo():
    x,labels=dataset(80,29,spread=2);results={}
    for mode in [False,True]:
        p,history=train(shift=mode);clean=calibration(forward(x,p)[0],labels);rng=np.random.default_rng(37);errors=[]
        for kind in ['noise','contrast','blur']:
            errors.append([1-evaluate(corruption(x,kind,level,rng),labels,p)['accuracy'] for level in [1,2,3]])
        normalized=corruption_errors(errors,np.full((3,3),.5),1-clean['accuracy'],.5)
        sequence_source,_=dataset(80,47)
        sequence=np.stack([forward(translate(sequence_source,0,dx),p)[0].argmax(axis=1) for dx in [-2,-1,0,1,2]],axis=1)
        noisy=corruption(x,'noise',3,np.random.default_rng(43));noisy_calibration=calibration(forward(noisy,p)[0],labels)
        best,attack=attack_pool(x,labels,p)
        results['shift_trained' if mode else 'center_trained']={'clean_shifted_distribution':clean,'corruption_types':['noise','contrast','blur'],
            'severity_errors':errors,'reference_normalized':normalized,'translation_flip_probability':flip_probability(sequence),
            'noisy_calibration':noisy_calibration,'attack':attack,'first_last_training_ce':[history[0],history[-1]]}
    return {'parameters':sum(v.size for v in initialize().values()),'train_images':40,'test_images':80,'severity_levels':3,
            'sequence_source_seed':47,'sequence_sources_are_centered':True,'epsilon_in_pixel_units':.2,'pgd_steps':12,'pgd_restarts':3,'pgd_step_size':.04,'results':results,
            'scope':'Custom 8x8 bar data, three synthetic corruption types. Reference is constant-class prediction (error 0.5), not AlexNet. No ImageNet-C/P reproduction, physical threat claim or robustness certificate.'}


if __name__=='__main__':print(json.dumps(demo(),indent=2))

固定实验实际得到:

指标居中训练模型平移训练模型
位置变化干净图准确率0.53751.0000
原始平均退化错误率0.4458330.115278
相对常类别参考的错误率比值0.8916670.230556
相邻平移帧翻转概率0.25000.0000
FGSM准确率0.00000.4000
对整个候选池保持正确的比例0.00000.0000

平移训练改善了几项测量性质,却没有挺过完整的指定攻击池。序列分数使用自己的居中来源集,不是由第一行的位置变化测试图计算。比值与概率故意采用不同名称。

对独立高噪声校准样本,居中模型的准确率/NLL/Brier/ECE约为0.5250/2.427631/0.879347/0.390578,平移模型约为0.9750/0.102332/0.057198/0.034338。这些汇总描述的是该样本和分桶约定,不证明攻击分布上的校准性质。

数值检查覆盖全部330参数与输入导数、攻击使用的平均损失梯度、直接模糊计算、先求和再作比值、相对分数约定、序列有效性、校准端点、坐标投影、可手算的线性FGSM例子,以及跨PGD候选保留原图/FGSM失败。浮点预算比较允许微小舍入误差,不是经过验证的实数算术认证。

更广的结论,需要更广的证据

评测应明确数据来源、退化类型与等级、来源划分、模型检查点、预处理、攻击访问方式、范数、预算、步长、重启次数、选择规则和聚合方式。其中任何约定不同,数字就可能在回答不同问题。应同时报告干净与变化后的结果,不能只挑偏好方法占优的强度或攻击。

本例位移条纹是受控合成形状,没有测试自然图像、复杂空间场景、物理攻击、全部范数球、针对随机防御的自适应攻击、前五名排序稳定性,或不同人口/采集群体上的表现。代码也没有实现对抗训练或认证方法。对抗样本与对抗训练属于另列的规划主题,不能用一个“鲁棒”标签掩盖本实验尚未覆盖的范围。

小的经验ECE可能掩盖桶内或子群体差异,来源变化也可能改变置信度质量。增加桶数不会增加数据。本例含噪图比较采用独立于退化网格的噪声采样,因此准确率不必恰好等于某一网格单元。

原鲁棒性仓库建议使用其提供的JPEG文件保持评测一致,而非随意在内存中重新生成退化。固定评测器也说明了,为什么需要读清操作集合与归一化。仓库README已读行 本例采用明确不同的合成流程,保留真实结果,不套用另一个基准的名字和结论。

四种看似鲁棒的分数

  1. 基本理解。模型每帧都预测类别一,但真实标签全是类别零,翻转概率与准确率各是多少?

    答案:预测从不改变,翻转概率为零;它始终答错,准确率也为零。仅凭稳定性不能证明识别正确。

  2. 手算。两类退化的错误率分别为[0.1,0.2]、[0.4,0.6],参考为[0.2,0.8]、[0.1,0.2],归一化类型错误率的均值是多少?

    答案:两类比值为0.3/1=0.3、1/0.3=10/3,平均约1.816667。比值超过一,表示在该聚合下差于参考,并非不可能的概率。先平均各强度比值,会产生不同结果。

  3. 反例。两个二分类预测都为[0.5,0.5],平局选择类别零,标签分别为零和一。准确率、ECE和沿类别求和的Brier是多少?

    答案:准确率为0.5。置信度均为0.5,所在桶准确率也是0.5,因此ECE为零。每个Brier为0.25+0.25=0.5。置信水平可以校准,分类仍然很弱。

  4. 迁移。FGSM后40%的图像仍答对,但完整的允许候选池为每张图都找到了错误,应报告哪个鲁棒结果?

    答案:报告两种攻击配置,以及候选池下保持正确的比例零。对这个有限测试集,已找到的反例证明了指定预算内的失败。不能只保留较弱攻击的结果,也不能据此推断所有真实物理变化下的表现。如果一个反例都没找到,单凭这一点也仍不能证明鲁棒。

把分数与来源、实现放在一起读

退化/扰动论文用于定义与协议;其仓库固定提交为 8190fe329f5f072a06e3a2aea02bb5dda69aed9f。实际检查C评测器最后70行、P翻转函数第257–274行和指定README片段,没有打开链接的mCE表格。这里尚未核清较早1807.01697稿件与1903.12261的关系,因此不作最早发表主张。

Goodfellow等人提供FGSM形式,Madry等人提供明确威胁集合与迭代优化表述,Guo等人提供用于比较的校准定义。本次只核读所述方法/定义范围,没有完整复现实验,也不采用历史优越性或通用一阶攻击保证。校准论文HTML的标题显示“补充材料”,但所引定义位于该渲染中显示的主文§2。

仓库许可证开头标明Apache 2.0,完整条款未审阅。没有复制或运行上游实现。小网络、梯度、退化、指标反例和完整实验均为原创教学材料。如果目标是改变模型以适应新分布,而非仅仅测量其行为,可以继续读领域适应。

先判断,再看解释

已评测的攻击候选都未让模型答错,这说明什么?

选择一个答案

学习目标

  • 区分退化错误率、预测稳定性、校准和对抗评测。
  • 按声明的强度归一化和序列比较约定计算。
  • 推导像素域投影,并保留所有攻击候选中的失败。
  • 解释有限测试候选准确率的界及其限制。

先修与延伸

查看知识关联图 →

参考文献

  1. Benchmarking Neural Network Robustness to Common Corruptions and Perturbations (v1)
    Dan Hendrycks; Thomas Dietterich · 2019
  2. ImageNet-C evaluator, pinned implementation
    hendrycks/robustness contributors · 2022
  3. ImageNet-P flip probability, pinned implementation
    hendrycks/robustness contributors · 2022
  4. Corruption and perturbation benchmark README, pinned version
    hendrycks/robustness contributors · 2022
  5. Explaining and Harnessing Adversarial Examples (v3)
    Ian J. Goodfellow; Jonathon Shlens; Christian Szegedy · 2015
  6. Towards Deep Learning Models Resistant to Adversarial Attacks (v4)
    Aleksander Madry; Aleksandar Makelov; Ludwig Schmidt; Dimitris Tsipras; Adrian Vladu · 2019
  7. On Calibration of Modern Neural Networks (v2)
    Chuan Guo; Geoff Pleiss; Yu Sun; Kilian Q. Weinberger · 2017

版本1 · 编写状态: 已完成记录中的技术复核

查看技术检查记录(AI)

Codex · 2026-09-08 · Codex single-AI-author technical check: scoped corruption/perturbation, FGSM, PGD and calibration definitions plus pinned evaluators; 13 paired equations, complete 330-parameter and input gradients, metric denominators, finite-test attack bounds, four explained bilingual exercises and actual figure data. Production browser acceptance recorded separately. Not human peer review or a robustness certificate.

  • 逐节核对两语:强度求和后比值CE、原式减一次干净误差、相邻/参考翻转、ECE端点、平均NLL与类别求和Brier、像素域威胁交集、FGSM线性最优、原图中心投影和同一有限测试候选界;四道解释习题。
  • 16项数值检查覆盖全部330参数/输入导数、独立模糊、指标反例及无效分母、保留对象的序列、校准端点、投影与线性FGSM枚举、攻击重放和全部失败保留。正式测试执行生产MDX。
  • 三类自定义退化、三强度和常类别参考,不是ImageNet-C。独立居中序列每帧至少保留三亮像素。平移模型干净准确率1、FGSM为0.4、epsilon 0.2下41候选池为0;保留失败与校准样本分离。
  • 四张原创SVG绑定真实输出与原数据;最终隔离双语、三宽/四字体验证通过,实际查看桌面/手机截图。完整文章验收另记。单AI作者技术检查,不是独立人工审校;无上游代码复制或执行。

核对的来源位置:

相关主题

没有匹配结果,试试英文名或缩写。

已显示 0 条结果

将整个查询放入双引号,可按短语匹配。