AI Wiki中文/EN

Visual robustness: say which changes a model survives

视觉模型的鲁棒性

Measure corruptions, prediction stability, calibration and bounded attacks with a complete small classifier; keep finite-search results distinct from guarantees.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

A perfect clean score leaves several questions unanswered

Our small vision model classifies every image correctly in one test condition. Add noise and it behaves differently. Move an image through a sequence and its prediction may flicker. Choose pixel changes using the model’s own gradient and it can fail again. These are different tests of visual robustness, not interchangeable versions of one score.

This article implements a complete classifier, controlled corruptions, sequence stability, confidence metrics and a white-box attack candidate pool. The purpose is to make the evaluation contract inspectable: which images, which changes, which labels, which normalization and which denominator produced a result. Visual data augmentation explains how the two training procedures used here are constructed.

A useful first question is what would count as a failure. Constantly predicting one wrong class is perfectly stable. A well-calibrated coin-flip classifier can have low accuracy. A model that survives one attack may fail a different search within the same allowed perturbation set. Each statement can be checked without a large benchmark.

Actual images and separately defined evaluations. The attack curve averages per-image maximum loss over candidates already seen; calibration uses the independent noisy sample.
Actual images and separately defined evaluations. The attack curve averages per-image maximum loss over candidates already seen; calibration uses the independent noisy sample.

Write the test contract before computing the score

Corruption, stability and adversarial evaluation

For a distribution D of labeled images and a declared, classifier-independent corruption distribution Q, corruption accuracy can be expressed as:

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].

The unchanged label is an assumption: the corrupted image must still represent the intended class. Occluding the entire object or rotating an orientation-defined class may invalidate it. The benchmark distribution Q is also a choice, not a measurement of how frequently each failure occurs in a particular deployment.

ImageNet-C organizes 15 corruption types with five severity levels. ImageNet-P evaluates sequences of smaller changes. Their protocol separates benchmark evaluation from training on those test corruptions. This provides a reproducible comparison; it does not prove coverage of every real camera, weather condition or user population. Corruption and perturbation paper, §§3–4

Average errors in the declared order

Let e_cs be a model’s error on corruption type c and severity s, and b_cs a reference model’s error under the same conditions. The paper’s normalized corruption error and mean are:

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.

For the paper benchmark, C=15, S=5 and the reference is AlexNet. Our function accepts an explicit matrix and reference; the demonstration uses three custom types, three levels and a constant-class reference. Its output is a ratio, not a probability or an ImageNet-C result. A zero reference denominator is rejected. Averaging e_cs/b_cs first generally produces a different answer. Paper, §4.2

There is a further convention worth checking against the printed equation. The paper’s Relative CE subtracts clean error once from each sum:

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

We retain that convention and generalize it to the supplied number of levels. It is not a mean excess-error formula. If five corrupted errors all equal 0.2 and the clean error is 0.2, while the corresponding reference values all equal 0.4, the ratio is 0.8/1.6=0.5, not zero. The test catches silently replacing a severity sum with another aggregation while keeping the same name.

The pinned ImageNet-C test script averages five severity errors, loops over 19 corruption names including four validation types, and explicitly prints an unnormalized result. Running that file without reading these details does not automatically reproduce the 15-type normalized paper metric. Pinned evaluator, lines 219–288

Stability needs a comparison rule

For N prediction sequences of length T, the adjacent-frame flip probability is:

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})\}.

When noisy frames are generated independently from the first clean frame, compare each later frame with that reference instead:

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})\}.

The paper and inspected implementation distinguish these cases. The implementation also uses a difficulty-dependent temporal stride; our demonstration uses adjacent frames. A normalized flip rate divides a raw flip probability by a reference value, so the two quantities should not share an unlabeled column. Paper, §4.2 Pinned flip function, lines 257–274

Neither expression contains the true label. All predictions can be stable and wrong. In our translation sequence, images originate from a separate centered set, and every frame is checked to retain at least three bright bar pixels. This prevents the small teaching sequence from accidentally becoming an object-removal test.

Calibration asks whether confidence matches correctness

Let confidence p-hat_i be the maximum predicted class probability and y-hat_i the corresponding class. For nonempty bins B_m of confidence values, define:

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.

The empirical expected calibration error is:

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|.

We use five equal-width bins, left-closed and right-open except for including confidence one in the final bin. Guo and colleagues describe the opposite endpoint convention, right-closed bins. At exact boundaries this distinction can change assignments. Empty bins receive no contribution. A small finite sample and the bin choice limit what ECE can establish. Calibration paper, §2

We also report mean negative log likelihood and a Brier score that sums across classes:

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.

The cited paper writes NLL as a sum; our report divides by N. Brier is not divided by the class count here. Giving [0.5,0.5] to a balanced binary set, with a fixed tie-breaking rule, gives accuracy 0.5 and ECE zero when the predictions fall in one bin. Calibration is therefore not another name for accuracy. Calibration paper, §2

Specify an attack set in pixel units

For normalized pixels x in [0,1]^d, our allowed digital perturbations form the intersection:

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

This limits every pixel change. It is not a claim about all perceptually similar images or all physical camera changes. If a model has a preprocessing transform, account for its units and derivatives; a budget in raw pixel units is not automatically the same budget after channel normalization. Madry and colleagues formulate adversarial evaluation through an explicitly defined perturbation set and an inner loss maximization. Robust optimization formulation, §2

For fixed model parameters and g equal to the input loss gradient, the linearized objective has the following box optimum before active pixel-domain clipping:

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).

Each coordinate independently takes the feasible endpoint matching its gradient sign. This explains the fast gradient sign method (FGSM). For our additional pixel box, clipping each coordinate to the intersection also solves that coordinate’s linear subproblem. It does not solve the nonlinear network’s worst-case problem exactly. FGSM paper, §§3–4

Projected gradient steps repeatedly recompute the gradient at the current candidate:

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).

Projection remains centered on the original x, not on the previous iterate. The parameter eta is the step size; epsilon is the total coordinate budget. Multiple random starting points explore different paths but remain finite searches. Our model has no batch normalization or dropout, and the parameters remain fixed during attack evaluation. PGD discussion, §§2.1–3.1

A search result has a direction of uncertainty

For the same finite labeled test set, let A_i be the evaluated candidate pool, containing x_i and lying within S_epsilon(x_i). Define worst-case and candidate-pool accuracy with an infimum of the correctness indicator:

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\}.

Set inclusion immediately gives:

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

This is a bound on the same finite test set, not a population confidence interval. A discovered counterexample proves failure for that image; absence of a discovered counterexample does not prove robustness. Keep failures from all candidates, not merely the final iterate. For multiple classes, the highest-loss candidate need not be the only candidate that matters for classification, so the program separately records whether any candidate was wrong.

The stored best-loss curve is monotone because we take the maximum over all candidates seen so far. It does not prove that individual PGD trajectories improve monotonically, or that their maxima are globally optimal.

A complete model and four kinds of evaluation

Save the following program as vision_robustness.py and run python vision_robustness.py with NumPy. Recorded execution used Python 3.12.4 and NumPy 1.26.4. The classifier has a valid 3×3 convolution from one to four channels, ReLU, 144 flattened features and a two-class head: 330 stored parameters, all with backward passes.

There are 40 training images from seed 11, parameter seed 7 and transformation seed 17. Both models train for 120 Adam updates at learning rate 0.01, coefficients 0.9/0.999 and epsilon 1e−8. One sees centered images, the other random integer translations. The main test uses 80 position-varied images from seed 29. Sequence images are independently generated with seed 47 in centered positions. No test-dependent policy selection is performed.

The three custom corruption families are clipped Gaussian noise with standard deviation 0.08s, contrast scaling toward 0.5 by 1/(1+s), and a blend with a 3×3 reflect-padded box blur using weight s/3, for s=1,2,3. Corruption randomness uses seed 37; a separate high-noise calibration sample uses seed 43. This is not the ImageNet-C generation pipeline. The balanced binary constant-class reference has error 0.5 at every severity.

Attack evaluation uses epsilon 0.2, step size 0.04, 12 steps and three random starts with seed 31. Clean and FGSM candidates are also included. There are 41 candidates per image: two initial candidates plus three times one random start and 12 updates. The returned input gradient is the gradient of mean loss; its positive batch scaling does not affect sign steps in this independent-image model.

"""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))

The actual fixed experiment gives:

QuantityCenter-trained modelTranslation-trained model
Accuracy on position-varied clean images0.53751.0000
Raw mean corruption error0.4458330.115278
Error ratio versus constant-class reference0.8916670.230556
Adjacent translation flip probability0.25000.0000
FGSM accuracy0.00000.4000
Accuracy surviving the complete candidate pool0.00000.0000

Translation training improves several measured properties, but it does not survive the full declared attack pool. The sequence score uses its own centered source set; it is not computed from the position-varied test images in the first row. Ratios and probabilities have intentionally different names.

For the independent high-noise calibration sample, accuracy/NLL/Brier/ECE are approximately 0.5250/2.427631/0.879347/0.390578 for the center-trained model and 0.9750/0.102332/0.057198/0.034338 for the translation-trained model. These summaries describe that sample and binning convention. They do not certify calibration under the attack distribution.

The numerical checks cover all 330 parameter and input derivatives, the mean-loss gradient used for attacks, a direct blur calculation, ratio-of-sums aggregation, relative-score conventions, sequence validity, calibration endpoints, coordinate projection, a hand-solvable linear FGSM example and retention of clean/FGSM failures across PGD candidates. Floating-point budget comparisons allow small rounding error; this is not verified real-arithmetic certification.

Broader claims need broader evidence

An evaluation report should identify data provenance, corruption types and levels, source splits, model checkpoint, preprocessing, attack access, norm, budget, step size, restarts, selection rule and aggregation. Comparing numbers while any of those contracts differ may compare different questions. Report both clean and changed-input results; do not select only the severity or attack where a preferred method looks good.

Our shifted bars are controlled synthetic shapes. The program does not test natural images, spatially complex scenes, physical attacks, all norm balls, adaptive attacks on a stochastic defense, top-five ranking stability or performance across demographic or acquisition groups. The code includes no adversarial training and no certification method. Adversarial examples and adversarial training are separate planned topics; their absence from this experiment should not be hidden behind a robustness label.

A small empirical ECE can conceal differences within a bin or within subgroups, and source shift can change confidence quality. More bins do not create more data. Our noisy-image comparison uses a separate noise draw from the corruption grid; its accuracy is therefore not required to equal one grid entry.

The original robustness repository recommends its provided JPEG files for consistent evaluation instead of casually regenerating corruptions in memory. The pinned evaluator also illustrates why reading the exact operation set and normalization matters. Repository README, inspected lines Our experiment uses an explicitly different synthetic pipeline and preserves its results without transferring a benchmark’s name or conclusions to it.

Four ways a robust-looking score can mislead

  1. Understanding. A model predicts class one in every frame, but every true label is class zero. What are its flip probability and accuracy?

    Answer: Flip probability is zero because predictions never change; accuracy is zero because they are always wrong. Stability alone cannot establish correct recognition.

  2. Calculation. Two corruption types have errors [0.1,0.2] and [0.4,0.6]; their reference errors are [0.2,0.8] and [0.1,0.2]. Compute the mean of normalized type errors.

    Answer: The type ratios are 0.3/1=0.3 and 1/0.3=10/3. Their mean is approximately 1.816667. A ratio above one means worse than the reference under that aggregation, not an impossible probability. Averaging individual severity ratios would give a different value.

  3. Counterexample. Two binary predictions are both [0.5,0.5]; tie-breaking chooses class zero, and the labels are zero and one. Compute accuracy, ECE and class-summed Brier score.

    Answer: Accuracy is 0.5. Both confidences are 0.5 and share a bin with accuracy 0.5, giving ECE zero. Each Brier score is 0.25+0.25=0.5. A calibrated confidence level can accompany weak classification.

  4. Transfer. FGSM leaves 40% of test images correct, but the complete allowed candidate pool finds an error for every image. Which robustness result should be reported?

    Answer: Report both attack configurations and the pool-surviving accuracy of zero. For this finite test set, the found counterexamples establish failure within the stated budget. Do not retain only the weaker result or infer performance against every possible physical change. If no counterexample had been found, that alone would still not prove robustness.

Keep the score attached to its source and implementation

The corruption/perturbation paper was read for its definitions and protocol, and its repository was inspected at commit 8190fe329f5f072a06e3a2aea02bb5dda69aed9f. The C evaluator’s final 70 lines, the P flip function’s lines 257–274 and specified README excerpts were read; the linked mCE spreadsheet was not opened. The earlier manuscript numbered 1807.01697 has not been reconciled with 1903.12261 here, so this article makes no earliest-publication claim.

Goodfellow and colleagues supply the FGSM formulation; Madry and colleagues supply the explicit threat-set and iterative optimization framing; Guo and colleagues supply the calibration definitions used for comparison. Only the stated method/definition ranges were reviewed, not their complete experiments. Historical superiority claims and universal first-order-attack guarantees are not adopted. The HTML calibration rendering has a supplementary-material title, but the cited definition section is the main-paper §2 shown in that rendering.

The repository license opening identifies Apache 2.0; full terms were not audited. No upstream implementation was copied or executed. The small network, gradients, corruptions, metric counterexamples and complete experiment are original teaching material. Domain adaptation is a useful continuation when the goal is to change a model for a new distribution rather than merely measure its behavior there.

Make a prediction, then check

No evaluated attack candidate fools a model. What has been established?

Choose one answer

Learning objectives

  • Separate corruption error, prediction stability, calibration and adversarial evaluation.
  • Compute declared severity normalization and sequence comparisons.
  • Derive pixel-domain projection and track all failed attack candidates.
  • Explain finite-test candidate accuracy bounds and their limits.

Prerequisites & connections

Explore related knowledge →

References

  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

Version1 · Editorial status: Recorded technical checks completed

View technical check record (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.

  • Compared both manuscripts: ratio-of-severity-sums CE, printed single-clean subtraction, adjacent/reference flips, ECE endpoints, mean NLL and class-summed Brier, pixel-domain threat intersection, FGSM linear optimum, original-centered projection and same-finite-test candidate bound; four explained exercises.
  • The 16 numerical checks cover all 330 parameter/input derivatives, independent blur, metric counterexamples and invalid normalizers, visible-object sequences, calibration boundaries, projection and linear FGSM enumeration, attack replay and retention of all failures. Formal tests execute production MDX.
  • Three custom corruptions and three levels use a constant-class reference, not ImageNet-C. Separate centered sequence sources retain at least three bright pixels per frame. The translation model has clean accuracy 1, FGSM 0.4 and pool accuracy 0 under 41 candidates at epsilon 0.2; negative results and calibration sample separation retained.
  • Four original SVGs bind actual output and raw data. Final isolated bilingual, three-width/four-font validation passed and desktop/mobile screenshots were inspected. Full article acceptance is recorded separately. Single-AI-author technical check, not independent human review; no upstream code copied or executed.

Source locations checked:

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.