AI Wiki中文/EN

Visual data augmentation: transform the target with the image

视觉数据增强

Align pixels, masks and boxes; differentiate a full three-view objective and test when augmentation preserves—or breaks—the task.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

The picture changed. Should the answer change too?

A classifier learns to tell a vertical bar from a horizontal one. Moving either bar a little leaves its class unchanged. Rotating it by 90 degrees swaps the answer. Applying the same label rule to both transformations creates a broken training task, even if the training loss becomes small.

Visual data augmentation generates training views by transforming images and, when necessary, their targets. The useful question is not how many filters a library offers. It is which changes the intended task should tolerate, which changes should alter the prediction, and which changes destroy the evidence needed to answer at all.

This article connects that contract to geometry, stochastic objectives and a complete 330-parameter classifier. We compare ordinary training, translation, correct and incorrect rotation labels, and a restricted mixed-view consistency method. Mixup and CutMix have separate articles; here the focus is the visual pipeline and its targets. RandAugment supplies an example of a small policy search space, while AugMix supplies an example of mixing views and enforcing consistency. RandAugment, §3 AugMix, §3

Actual transformed views and fixed test accuracies. The box uses half-open edges and flips with its image; mixed-view targets are assignments, not guaranteed semantic preservation.
Actual transformed views and fixed test accuracies. The box uses half-open edges and flips with its image; mixed-view targets are assignments, not guaranteed semantic preservation.

Transform the task, not only the pixels

An objective includes a target transformation

Let the training set contain n original image/target pairs. Draw transformation T from a declared distribution q and transform the target with g_T. The augmented empirical objective is:

R^q(θ)=1n∑i=1nET∼q[ℓ(fθ(Txi),gT(yi))].\widehat R_q(\theta)=\frac1n\sum_{i=1}^n\mathbb E_{T\sim q}\left[\ell\big(f_\theta(Tx_i),g_T(y_i)\big)\right].

For a label-preserving classification change, g_T is the identity. For a quarter turn of our two-class bar problem, g_T swaps the class. A detection target may need new box coordinates; a segmentation target needs its spatial labels moved with the image. If a crop removes the only object, keeping the old image label is a new assumption, not a consequence of this equation.

There are two different desired behaviors:

f(Tx)≈f(x)(invariance),f(Tx)≈gT(f(x))(equivariance).f(Tx)\approx f(x)\quad\text{(invariance)},\qquad f(Tx)\approx g_T(f(x))\quad\text{(equivariance)}.

Equivariance means the output changes in the corresponding way. A segmentation mask should move when the object moves; forcing its pixels to remain unchanged would be the wrong objective. For class probabilities, a class-changing transformation can instead act as a permutation of output coordinates. Not every geometric operation has a meaningful target map for every dataset.

Coordinates make off-by-one errors visible

Use integer pixel-center indices 0 through W−1 and half-open box edges that range from 0 to W. A horizontal flip gives:

j′=W−1−j,[x0,y0,x1,y1]↦[W−x1,y0,W−x0,y1].j'=W-1-j,\qquad [x_0,y_0,x_1,y_1]\mapsto[W-x_1,y_0,W-x_0,y_1].

For an image four pixels wide, a box spanning the first column, [0,0,1,3], becomes [3,0,4,3]. Subtracting from W−1 in the edge formula would shrink or misplace it. The program flips the image, integer mask and boxes together, and verifies that two flips return every input exactly.

Let Omega denote the set of valid input pixel indices. An integer translation with zero fill is:

(Tdy,dxx)ij={xi−dy,j−dx,(i−dy,j−dx)∈Ω,0,(i−dy,j−dx)∉Ω.(T_{d_y,d_x}x)_{ij}=\begin{cases} x_{i-d_y,j-d_x},&(i-d_y,j-d_x)\in\Omega,\\ 0,&(i-d_y,j-d_x)\notin\Omega. \end{cases}

This is not a circular shift. Moving right and then left cannot recover pixels that left the image. Its transpose moves a gradient in the opposite direction with the same boundary convention; it is an adjoint, not a lossless inverse. For continuous warps, specify inverse sampling coordinates, interpolation and fill values separately. Interpolating a categorical mask as ordinary intensities can create nonexistent class IDs; preserving its target meaning takes priority over matching the image interpolation method.

More views do not create more independent source images

For fixed model parameters, consider K independently sampled transformations of one random source pair, and let Z be the loss on a transformed view. Conditional on the source, the transformation losses are independent. The law of total variance gives:

Var⁡ ⁣(1K∑k=1KZk)=Var⁡(E[Z∣X,Y])+1KE[Var⁡(Z∣X,Y)].\operatorname{Var}\!\left(\frac1K\sum_{k=1}^K Z_k\right) =\operatorname{Var}\big(\mathbb E[Z\mid X,Y]\big) +\frac1K\mathbb E\big[\operatorname{Var}(Z\mid X,Y)\big].

More views reduce the transformation-sampling term. They do not remove variation between source images. Split sources before augmentation: variants of the same photograph in training and test are not an independent test of generalization. Correlated transformation draws would also change the conditional-variance term above.

A small policy space still requires selection discipline

RandAugment’s method selects N operations sequentially from K available operations with uniform probabilities, and uses a common magnitude parameter M. Its listed pool contains 14 operations. An ordered sequence therefore has probability:

Pr⁡(o1,…,oN)=K−N.\Pr(o_1,\ldots,o_N)=K^{-N}.

There are K to the power N possible operation sequences, not necessarily that many distinct output images: identities, repeated choices and equivalent compositions can collapse to the same result. M indexes operation-specific strengths; it is not a shared physical unit such as degrees for every operation. Reducing the policy space does not eliminate validation or make every operation label-preserving. RandAugment, §3 and pseudocode

Choose a policy on training/validation data, keep the test set untouched, and record whether the validation task matches the deployment conditions. Our comparison fixes its settings and test seeds in advance. It does not search a full RandAugment policy, and it does not retune until every named method wins.

Mix views, then compare predictions

For one image, form R−1 additional views. One AugMix-style view combines k transformed chains with Dirichlet weights, then blends that result with the original:

w∼Dirichlet⁡(α1k),m∼Beta⁡(α,α),x~=mx+(1−m)∑j=1kwjTjx.w\sim\operatorname{Dirichlet}(\alpha\mathbf1_k),\quad m\sim\operatorname{Beta}(\alpha,\alpha),\qquad \widetilde x=mx+(1-m)\sum_{j=1}^k w_j T_jx.

Our restricted implementation uses k=3, alpha=1, and chain depths drawn uniformly from 1 through 3. The pool contains horizontal/vertical integer shifts and horizontal flips. It is not the paper’s operation pool. A convex combination stays within the range of its component images, but that range fact does not prove that mixed objects remain semantically valid. AugMix, §3

For each view r, let p_r be the classifier’s probability vector and let their mean be p-bar. Jensen–Shannon disagreement is:

p‾=1R∑r=1Rpr,JS⁡(p1,…,pR)=1R∑r=1R∑cprclog⁡prcp‾c.\overline p=\frac1R\sum_{r=1}^R p_r,\qquad \operatorname{JS}(p_1,\ldots,p_R)=\frac1R\sum_{r=1}^R\sum_c p_{rc}\log\frac{p_{rc}}{\overline p_c}.

The original image and two independently mixed views give R=3. Our loss applies cross-entropy to the original image only, and adds a batch-mean consistency term:

L=1B∑i=1B[−log⁡p0i,yi]+λB∑i=1BJS⁡(p0i,p1i,p2i).L=\frac1B\sum_{i=1}^B[-\log p_{0i,y_i}] +\frac\lambda B\sum_{i=1}^B\operatorname{JS}(p_{0i},p_{1i},p_{2i}).

If every view receives the same confidently wrong prediction, JS is zero. Consistency cannot supply the missing class evidence, which is why the supervised term and transformation semantics matter. The inspected upstream training function also applies classification loss only to the clean branch; it uses JS weight 12 and clamps mixture probabilities. We use weight 2 and stable log-sum-exp calculations without that probability clamp. Pinned training function, lines 205–245

Differentiate through all views

Let z_ric be a logit, p_ric its softmax probability, and a_ric=log(p_ric/p-bar_ic). For the batch-mean JS term alone:

∂LJS∂zric=pricRB(aric−∑jprijarij).\frac{\partial L_{\rm JS}}{\partial z_{ric}} =\frac{p_{ric}}{RB}\left(a_{ric}-\sum_j p_{rij}a_{rij}\right).

To derive it, first differentiate the entropy difference defining JS. The contributions through the mean distribution cancel the additive terms, leaving the log ratio. Multiplying by the softmax Jacobian subtracts its probability-weighted mean. Treating the mean as a detached constant is not the justification for this result. Each view still contributes a gradient through the same model parameters; those parameter gradients must be added.

Choosing a view index uniformly and then drawing a class from that view makes JS the information the class reveals about the view index. Thus, with C classes and natural logarithms:

0≤JS⁡≤min⁡(log⁡R,log⁡C).0\leq\operatorname{JS}\leq\min(\log R,\log C).

The conditional-entropy terms are nonnegative, while information cannot exceed either variable’s entropy. This gives the bound above. For three views and two classes, log 2 is sharper than log 3. Identical views give zero disagreement; the numerical checks include this case and logits of magnitude 1,000.

A complete small classifier

The input is B×8×8×1. A valid 3×3 convolution produces B×6×6×4 activations, followed by ReLU, flattening and a two-class linear head:

h=ReLU⁡(W∗x+b),q=vec⁡(h),z=qV+c.h=\operatorname{ReLU}(W*x+b),\qquad q=\operatorname{vec}(h),\qquad z=qV+c.

Its stored parameter count is:

3⋅3⋅1⋅4+4+144⋅2+2=330.3\cdot3\cdot1\cdot4+4+144\cdot2+2=330.

For one view’s batch-mean cross-entropy, the logit gradient is:

Gic=1B(pic−1[c=yi]),∇VL=QTG,∇cL=∑iGi,∇QL=GVT.G_{ic}=\frac1B\left(p_{ic}-\mathbf1[c=y_i]\right),\qquad \nabla_V L=Q^TG,\quad \nabla_c L=\sum_iG_i,\quad \nabla_Q L=GV^T.

Here Q stacks the flattened features as rows. Reshape the feature gradient, apply the ReLU mask, and scatter the convolution patch gradients by addition. The program supplies every weight, bias and input derivative; backpropagation explains that chain rule in more detail. At a ReLU value of zero, this implementation selects derivative zero.

Convolution work scales with batch size, output area, kernel area and channel counts; the dense head costs order B times 144 times 2. Three-view consistency needs three forward/backward paths and their stored activations. The teaching code materializes patches and loops over augmentation operations; it is designed for inspection, not throughput claims. Training-time augmentation need not add a test-time ensemble, but any chosen test-time averaging adds its own inference cost.

Five training choices, including two disappointing ones

Save the complete program as visual_augmentation.py and run python visual_augmentation.py with NumPy. The recorded environment is Python 3.12.4 with NumPy 1.26.4. It trains on 40 synthetic bar images generated with seed 11; initialization uses seed 7 and training transformations use seed 17. Each model receives 120 Adam updates, learning rate 0.01, coefficients 0.9/0.999 and epsilon 1e−8.

All five modes share the original training images and initial parameters. Their sampled views and objectives differ. There are 80 centered test images from seed 23 and 80 position-varied images from seed 29. Quarter-turned evaluation uses the centered test images with correctly swapped orientation labels. These are fixed synthetic conditions, not ImageNet or a claim that the five objectives have comparable loss values.

"""Original 330-parameter visual classifier with label-aware teaching augmentation.

Synthetic bars, custom restricted operators and complete parameter/input gradients.
AugMix-style mixing and full three-view JS loss; not the paper operation pool,
RandAugment search implementation or ImageNet benchmark reproduction.
"""
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 flip_annotations(image,mask,boxes):
    image=finite(image);mask=np.asarray(mask);boxes=finite(boxes)
    if image.ndim!=3 or mask.shape!=image.shape[:2] or boxes.ndim!=2 or boxes.shape[1]!=4:raise ValueError('HWC image, HW mask and N x 4 boxes required')
    if not np.issubdtype(mask.dtype,np.integer):raise ValueError('Categorical mask must use integer IDs')
    width=image.shape[1];height=image.shape[0]
    if np.any(boxes[:,2:]<boxes[:,:2]) or np.any(boxes<0) or np.any(boxes[:,[0,2]]>width) or np.any(boxes[:,[1,3]]>height):raise ValueError('Half-open boxes must lie inside the image')
    flipped=boxes.copy();flipped[:,0]=width-boxes[:,2];flipped[:,2]=width-boxes[:,0]
    return image[:,::-1].copy(),mask[:,::-1].copy(),flipped


def augment(x,labels,rng,mode='shift',magnitude=2):
    x=finite(x);labels=np.asarray(labels);m=count(magnitude,0)
    if x.ndim!=4 or labels.shape!=(len(x),) or not np.isin(labels,[0,1]).all() or m>2:raise ValueError('Binary paired images and magnitude in 0..2 required')
    if mode not in ['none','shift','wrong90','right90']:raise ValueError('Unknown augmentation mode')
    out=x.copy();target=labels.copy()
    for i in range(len(x)):
        if mode=='shift':out[i]=translate(x[i:i+1],*rng.integers(-m,m+1,2))[0]
        if mode in ['wrong90','right90'] and rng.random()<.5:
            out[i]=np.rot90(x[i],axes=(0,1))
            if mode=='right90':target[i]=1-target[i]
    return out,target


def mixed_views(x,rng,width=3,max_depth=3,magnitude=1):
    x=finite(x);width=count(width);depth=count(max_depth);mag=count(magnitude,0)
    if x.ndim!=4 or not x.size or width>8 or depth>3 or mag>2:raise ValueError('Small NHWC mixing configuration required')
    output=np.zeros_like(x)
    for i in range(len(x)):
        weights=rng.dirichlet(np.ones(width));mix=rng.beta(1,1);combined=np.zeros_like(x[i])
        for weight in weights:
            chain=x[i:i+1].copy()
            for _ in range(rng.integers(1,depth+1)):
                op=rng.integers(3)
                if op==0:chain=translate(chain,0,int(rng.integers(-mag,mag+1)))
                elif op==1:chain=translate(chain,int(rng.integers(-mag,mag+1)),0)
                else:chain=chain[:,:,::-1,:].copy()
            combined+=weight*chain[0]
        output[i]=mix*x[i]+(1-mix)*combined
    return output


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 js_loss(logits):
    logits=finite(logits)
    if logits.ndim!=3 or not logits.size:raise ValueError('Views x batch x classes required')
    logp=log_probabilities(logits);prob=np.exp(logp);shift=logp.max(axis=0,keepdims=True)
    logmean=shift[0]+np.log(np.exp(logp-shift).mean(axis=0));ratio=logp-logmean
    value=float(np.sum(prob*ratio)/np.prod(logits.shape[:2]))
    u=ratio/np.prod(logits.shape[:2]);gradient=prob*(u-np.sum(prob*u,axis=-1,keepdims=True))
    return value,gradient


def loss(views,labels,p,consistency=0.):
    if not len(views) or not np.isfinite(consistency) or consistency<0:raise ValueError('Views and nonnegative consistency weight required')
    outputs=[forward(x,p) for x in views];stack=np.array([a for a,_ in outputs]);value,g=cross_entropy(stack[0],labels)
    js,djs=js_loss(stack);allg=consistency*djs;allg[0]+=g;grads={k:np.zeros_like(v) for k,v in p.items()};inputs=[]
    for derivative,(_,cache) in zip(allg,outputs):
        local,dx=backward(derivative,cache);inputs.append(dx)
        for key in p:grads[key]+=local[key]
    return value+consistency*js,grads,inputs


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(mode='none',steps=120,magnitude=2,consistency=2.):
    steps=count(steps)
    if mode not in ['none','shift','wrong90','right90','mixed']:raise ValueError('Unknown training mode')
    x,y=dataset(40,11);p=initialize();rng=np.random.default_rng(17)
    first={k:np.zeros_like(v) for k,v in p.items()};second={k:np.zeros_like(v) for k,v in p.items()};history=[]
    for step in range(1,steps+1):
        if mode=='mixed':views=[x,mixed_views(x,rng,magnitude=1),mixed_views(x,rng,magnitude=1)];labels=y;weight=consistency
        else:
            image,labels=augment(x,y,rng,mode,magnitude);views=[image];weight=0
        value,grads,_=loss(views,labels,p,weight);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 demo():
    clean,labels=dataset(80,23);shifted,shift_labels=dataset(80,29,spread=2);results={}
    for mode in ['none','shift','wrong90','right90','mixed']:
        p,history=train(mode)
        results[mode]={'clean':evaluate(clean,labels,p),'shifted':evaluate(shifted,shift_labels,p),'rotated_with_correct_labels':evaluate(np.rot90(clean,axes=(1,2)),1-labels,p),'first_last_training_objective':[history[0],history[-1]]}
    return {'parameters':sum(v.size for v in initialize().values()),'train_images':40,'test_images_per_condition':80,'training_steps':120,'results':results,
            'notes':'Same initial parameters and source training images; mode-specific training randomness/objectives. Test seeds fixed; no hyperparameter selection on these tests. Mixed uses restricted shifts/flips, not the AugMix paper operation pool. Wrong90 intentionally retains incorrect orientation labels.'}


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

Recorded accuracies are fractions of the relevant 80-image test set:

Training modeCenteredPosition variedQuarter turned, correct labels
None1.00000.53751.0000
Translation1.00001.00001.0000
Rotation, wrong labels1.00000.41250.0000
Rotation, corrected labels1.00000.60001.0000
Restricted mixed views1.00000.47500.5000

The wrong-label model still scores perfectly on centered originals. Its low training loss therefore cannot validate the augmentation contract; evaluating correctly labeled rotations exposes the problem. The restricted mixed-view model also fails to improve the position-varied condition. Preserve that result. It concerns our tiny model, pool and settings, not the original AugMix benchmark.

The checks cover all 330 parameter derivatives for cross-entropy and the three-view objective, input derivatives, JS logits, extreme probabilities, box/mask alignment, translation adjoints, reproducible transforms and the reported failures. No original-author code is executed by this program.

A pipeline can be reproducible and still answer the wrong question

A fixed random seed reproduces a mistake as reliably as a useful experiment. Record the original-source split, operation order, magnitude interpretation, interpolation, padding and target handling. For detection, define what happens to clipped or invisible objects. For segmentation, define ignore labels. For color changes, decide whether color is a nuisance or part of the class definition. Those decisions come from the task, not from the operation’s popularity.

Our transforms operate directly on floating-point grayscale arrays. The inspected AugMix helper converts each operation’s input to uint8/PIL and normalizes with CIFAR channel statistics. It also weights the original with 1−m where the paper pseudocode uses m. Because the sampled Beta distribution is symmetric, the two conventions have the same marginal law, but a fixed numerical m generally produces different images. Affine normalization commutes with weights summing to one; clipping and quantization need not. Pinned mixing helper

The restricted mixing method here is not a geometric guarantee. Repeated shifts may remove pixels, and mixtures may weaken the signal. We kept this teaching pool separate from the actual paper policy. Adding views cannot substitute for collecting missing source conditions or for evaluating visual robustness under a separately declared test distribution.

Four checks before trusting an augmentation

  1. Understanding. A horizontal bar is rotated by 90 degrees in this task. Why should the label change, while a horizontal flip keeps it?

    Answer: The label means orientation. A quarter turn exchanges horizontal and vertical; a horizontal mirror preserves that orientation. These are properties of the bar task, not universal rules for all classification datasets.

  2. Calculation. Flip a width-eight image with half-open box [1,2,4,6]. What is the new box?

    Answer: Its horizontal edges become 8−4 and 8−1, giving [4,2,7,6]. Pixel centers instead use 7−j. Two applications return the original box; using the center formula for the edges fails that coordinate convention.

  3. Counterexample. Three views receive probability vector [0.99,0.01], but the true class is the second one. Does zero JS imply successful learning?

    Answer: No. Equal vectors give JS zero, while clean cross-entropy is −log(0.01), approximately 4.6052. The predictions agree and are wrong. Consistency does not replace supervision or semantic validity.

  4. Transfer. A policy wins after you repeatedly change the test seed. Can it be reported as the best policy on an untouched test set?

    Answer: No. The repeated test feedback became part of selection. Choose settings on a separate validation set, preserve source-level separation, and report a final test that did not guide the choice. Keep unsuccessful fixed experiments rather than silently deleting them.

Use a policy name together with its actual contract

RandAugment v2 was read for its operation pool and small parameter space; AugMix v2 for chain mixing, the three-view objective and training/test corruption separation. Upstream AugMix was inspected at commit 9b9824c7c19bf7e72df2d085d97b99b3bfb00ba4: the entire mixing helper and lines 205–245 of its CIFAR training function. This is scoped method reading, not a full-paper review or benchmark reproduction.

The helper’s license header and the repository license opening identify Apache 2.0; the complete terms were not audited, and no upstream code was copied or executed. Our network, annotation examples and numerical tests are original teaching material. When adapting another implementation, record its exact version and actual preprocessing instead of assuming that the method name determines every operation.

Make a prediction, then check

A quarter turn swaps horizontal and vertical bars. What should happen to their orientation labels?

Choose one answer

Learning objectives

  • Match image, mask, box and class transformations to the task.
  • Explain why augmented replicas are not independent source images.
  • Differentiate all330 parameters and the complete three-view JS objective.
  • Interpret successful and failed augmentations without changing the test set.

Prerequisites & connections

Explore related knowledge →

References

  1. RandAugment: Practical automated data augmentation with a reduced search space (v2)
    Ekin D. Cubuk; Barret Zoph; Jonathon Shlens; Quoc V. Le · 2019
  2. AugMix: A Simple Data Processing Method to Improve Robustness and Uncertainty (v2)
    Dan Hendrycks; Norman Mu; Ekin D. Cubuk; Barret Zoph; Justin Gilmer; Balaji Lakshminarayanan · 2020
  3. AugMix mixing helper, pinned implementation
    Google Research AugMix contributors · 2020
  4. AugMix CIFAR training function, pinned implementation
    Google Research AugMix contributors · 2020

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-08 · Codex single-AI-author technical check: scoped RandAugment/AugMix methods and pinned implementation; 14 paired equations, complete 330-parameter CE and three-view JS gradients, target geometry, conditional variance, information bound, four explained bilingual exercises and actual figure data. Production browser acceptance recorded separately. Not human peer review or a benchmark reproduction.

  • Compared both manuscripts: target invariance/equivariance, half-open box versus pixel-center coordinates, zero-fill translation adjoint, fixed-parameter conditional variance, policy sequence probability, mixed-view target assumptions, full JS gradient and information bound; four explained exercises.
  • The 16 numerical checks cover all 330 parameter derivatives for CE and the three-view objective, input derivatives, extreme logits, annotation alignment, translation adjoint, repeatable transforms and training updates. Formal tests execute production MDX rather than preflight imports.
  • Retained wrong-label rotation failure and restricted mixing underperformance. Forty source images, 120 Adam updates, fixed 80-image tests; custom shifts/flips, JS weight 2 and stable unclamped log-sum-exp. No test-seed selection or original AugMix/RandAugment benchmark claim.
  • 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.