AI Wiki中文/EN

Consistency regularization

一致性正则化

Derive an exact two-view noise penalty and test how the wrong invariance harms generalization.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

Start with the problem

An image classifier should usually give compatible answers after a small, label-preserving change. Consistency regularization turns that expectation into a penalty on predictions. The usefulness comes from deciding which changes should matter—and which should not.

The Π-model described by Laine and Aila compares outputs from two stochastic, shared-weight branches and combines their squared discrepancy with labeled supervision. Their comparison uses class probabilities. We use a linear regression score to derive an exact finite-noise expectation; it is a teaching model of consistency, not a reproduction of their image classifier. Temporal Ensembling for Semi-Supervised Learning — arXiv v1

The example deliberately includes a bad augmentation choice. Penalizing sensitivity to a nuisance coordinate helps on a constructed domain shift. Penalizing the useful coordinate instead produces a much worse prediction, even though the regularized objective is solved correctly.

Definitions and derivation

Let two perturbations be independent draws with mean zero and covariance Sigma. Compare predictions of the same function under the two perturbed inputs:

C(f)=12Eδa,δb[(f(x+δa)−f(x+δb))2],Eδa=Eδb=0,Cov⁡(δa)=Cov⁡(δb)=Σ.C(f)=\tfrac12\mathbb E_{\delta_a,\delta_b}\left[(f(x+\delta_a)-f(x+\delta_b))^2\right],\qquad \mathbb E\delta_a=\mathbb E\delta_b=0,\quad \operatorname{Cov}(\delta_a)=\operatorname{Cov}(\delta_b)=\Sigma.

For a linear score fw(x)=x⊤wf_w(x)=x^\top w, the common x cancels. Independence makes the covariance of the difference equal to twice Sigma, and the leading one half cancels that factor:

C(w)=w⊤Σw,∇wC=2Σw.C(w)=w^\top\Sigma w,\qquad \nabla_w C=2\Sigma w.

Both branches are differentiated here. Freezing one branch as a target defines a different derivative and must be stated separately. For a smooth nonlinear f and small perturbations, a first-order expansion suggests a local Jacobian penalty; finite large transformations need not obey that approximation. Bishop’s noise/regularization analysis likewise states a small-noise Taylor expansion for its supervised-noise objective. It is related mathematics, not a license to equate all augmentation losses. Training with Noise is Equivalent to Tikhonov Regularization

Add labeled squared error, isotropic ridge lambda and consistency strength kappa. Setting the gradient to zero yields:

J(w)=12N∥Xw−y∥2+λ2∥w∥2+κw⊤Σw,w∗=(X⊤X/N+λI+2κΣ)−1X⊤y/N.J(w)=\frac1{2N}\|Xw-y\|^2+\frac\lambda2\|w\|^2+\kappa w^\top\Sigma w,\qquad w_*=(X^\top X/N+\lambda I+2\kappa\Sigma)^{-1}X^\top y/N.

The program uses a linear solve rather than explicitly forming the inverse. Its four perturbation vectors are positive/negative coordinate steps scaled by the square root of twice the specified variance. Uniformly averaging all sixteen pairs computes the expectation exactly for that discrete distribution. The covariance is a population expectation over those four equally likely vectors, not an N−1 sample estimate.

Exact regularized solutions tested after reversing the nuisance coordinate. The declared perturbation covariance changes the learned invariance: mainly perturbing nuisance helps this constructed shift, while mainly perturbing signal hurts. This is not an image benchmark.
Exact regularized solutions tested after reversing the nuisance coordinate. The declared perturbation covariance changes the learned invariance: mainly perturbing nuisance helps this constructed shift, while mainly perturbing signal hurts. This is not an image benchmark.

Run the calculation

Run CPython 3.12.4 and NumPy 1.26.4. Four training examples have target equal to the first coordinate and a highly correlated second coordinate. Test examples reverse only the second coordinate. With ridge 0.1, the supervised baseline has shifted-test MSE 1.986058601. Consistency with variances (0.01,1), mostly perturbing the nuisance, reduces it to 0.053084293. Reversing those perturbation variances gives MSE 8.335779495. The small useful-coordinate perturbation in the first setting still encodes an approximate smoothness assumption. For w=(0.3,−0.7) and variances (0.2,0.8), exact enumeration and the covariance formula both give consistency 0.41.

import numpy as np

X=np.c_[np.array([-2.,-1,1,2]),np.array([-2.1,-.8,.8,2.1])];Y=X[:,0].copy();TEST=np.c_[Y,-Y]


def perturbations(variances):
    v=np.asarray(variances,dtype=float)
    if v.shape!=(2,) or np.any(v<0) or not np.isfinite(v).all():raise ValueError('Use two finite nonnegative perturbation variances.')
    return np.array([[np.sqrt(2*v[0]),0],[-np.sqrt(2*v[0]),0],[0,np.sqrt(2*v[1])],[0,-np.sqrt(2*v[1])]])


def consistency(w,variances):
    noise=perturbations(variances);d=noise[:,None,:]-noise[None,:,:];error=d@w;return .5*float(np.mean(error**2)),np.mean(error[:,:,None]*d,axis=(0,1))


def objective(w,variances,strength=1.,ridge=.1):
    residual=X@w-Y;c,g=consistency(w,variances);return .5*np.mean(residual**2)+ridge*(w@w)/2+strength*c,X.T@residual/len(X)+ridge*w+strength*g


def solve(variances,strength=1.,ridge=.1):return np.linalg.solve(X.T@X/len(X)+ridge*np.eye(2)+2*strength*np.diag(variances),X.T@Y/len(X))


if __name__=='__main__':
    for name,variances,strength in [('supervised ridge',[0.,0.],0.),('perturb nuisance',[.01,1.],1.),('perturb useful coordinate',[1.,.01],1.)]:
        w=solve(variances,strength);print(name,'weights',w.round(9).tolist(),'training MSE',round(float(np.mean((X@w-Y)**2)),9),'shifted test MSE',round(float(np.mean((TEST@w-Y)**2)),9))
    w=np.array([.3,-.7]);v=np.array([.2,.8]);loss,g=consistency(w,v);print('enumerated consistency / covariance formula',loss,float(w@np.diag(v)@w),'gradient',g.round(9).tolist())
supervised ridge weights [0.543478261, 0.434782609] training MSE 0.005907372 shifted test MSE 1.986058601
perturb nuisance weights [0.905411163, 0.051129101] training MSE 0.004787226 shifted test MSE 0.053084293
perturb useful coordinate weights [0.061264154, 0.887273956] training MSE 0.026302192 shifted test MSE 8.335779495
enumerated consistency / covariance formula 0.41 0.4099999999999999 gradient [0.12, -1.12]

When the method fails

Constant predictions have zero consistency loss. Labels, useful pretraining or another constraint must supply a reason to predict anything informative. A small discrepancy between views is therefore not sufficient evidence of learning.

The augmentation distribution is part of the model’s assumptions. Flipping a digit can change its class; removing a negation can change a sentence’s meaning. Even a smooth perturbation can alter a regression target. The right strength depends on how closely the desired target is preserved, and should be selected on relevant validation data.

Our linear penalty happens not to depend on unlabeled input locations because its Jacobian is constant. Nonlinear models generally have input-dependent sensitivity and can use the unlabeled distribution differently. Do not generalize this cancellation to a neural classifier. Similarly, two identical perturbations give zero discrepancy for every model; independent views are essential to the covariance calculation.

Enumerating S perturbations costs O(S2d)O(S^2d) here; the closed covariance form costs O(d2)O(d^2) for dense Sigma. These are small analytical costs, not measured image-training speedups. The Π-model and later temporal-target approaches differ in which predictions are compared and retained. Temporal Ensembling for Semi-Supervised Learning — arXiv v1

Exercises with answers

  1. Why does the factor two disappear from the covariance expectation?

Answer 1: Two independent noises give difference covariance 2 Sigma, canceled by the one-half in the loss.

  1. What if the same perturbation is used in both branches?

Answer 2: Their predictions agree exactly, giving no consistency learning signal.

  1. Why can perturbing the useful coordinate hurt?

Answer 3: It penalizes sensitivity needed to predict the target; a correctly optimized regularizer can encode the wrong invariance.

  1. Does the linear cancellation prove unlabeled examples never matter?

Answer 4: No. It relies on a constant linear Jacobian; nonlinear sensitivity depends on input location.

Sources and next steps

Read the Π-model section of Laine and Aila’s fixed 2016 first version for two stochastic branches and probability-space discrepancy. Read Bishop’s Taylor expansion with its noise-amplitude assumptions. Compare pseudo-labeling, which adds discrete target selection, and contractive autoencoders, which explicitly penalize encoder sensitivity. Temporal Ensembling for Semi-Supervised Learning — arXiv v1; Training with Noise is Equivalent to Tikhonov Regularization

Make a prediction, then check

A model gives identical predictions under every perturbation. Does this prove useful learning?

Choose one answer

Learning objectives

  • Derive the two-independent-view covariance penalty and its gradient.
  • Test the task assumptions encoded by an augmentation distribution.

Prerequisites & connections

Explore related knowledge →

References

  1. Temporal Ensembling for Semi-Supervised Learning — arXiv v1
    Samuli Laine; Timo Aila · 2016
  2. Training with Noise is Equivalent to Tikhonov Regularization
    Christopher M. Bishop · 1995

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-07 · Codex single-AI-author technical check: primary-source scope, explicit assumptions, original calculations, independent mathematical references and bilingual tests; not independent human or second-agent review.

  • Single-AI-author technical check: bounded primary-source reading, explicit assumptions, original calculations, executable examples and corresponding bilingual equations, code and exercises. Not independent human or second-agent review.
  • Four CPython 3.12.4 checks per chapter: spectra and exact recurrence with scale-aware tolerances, frozen ridge probes, literal graded retrieval metrics, whitening/SVD constraints, finite balancing marginals and stopped targets, pseudo-label denominator, exact noise expectation and temperature-weighted distillation as applicable, plus bilingual structure. All eight programs use NumPy 1.26.4; no real image/text benchmark reproduction claimed.
  • Promoted the full prose, equations, code and exercises. Tests read formal MDX only; removed temporary fallbacks/draft skips and updated review assertion to checked. Algorithm and independent references are unchanged; final record binds both locale hashes.
  • Publication navigation points published topics to complete articles and removes corresponding pending wording, retaining directory entries for unwritten targets. Principles, equations, programs and exercises are unchanged; final article SHA values rebound.
  • Compact bilingual Matplotlib 3.9.1 charts use executed functions for eigenvalue shares, accepted-label coverage/precision and shifted-test error. Numerical samples and both SVGs are hash-bound. Zero-variance and undefined-precision cases are not plotted as invented measurements.

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.