AI Wiki中文/EN

Score matching: learn density slopes without a normalizer

分数匹配

Derive the implicit and denoising objectives, fit a quartic energy and test a boundary failure.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

Learn the slope without knowing the total area

Suppose a model assigns an unnormalized density to every point, but integrating that density is too expensive. Maximum likelihood normally needs the normalization constant. Differentiating the log density with respect to the input offers another route: a constant with respect to that input disappears.

The resulting vector is called the score. Here “score” means a spatial gradient, not a confidence percentage, an evaluation metric or the parameter gradient used in classical likelihood theory. Hyvärinen’s 2005 paper turns matching this field into an objective that can be estimated from data without evaluating the unknown data score. Vincent’s 2011 work connects this idea to denoising noisy observations. Read gradients, expectation and Gaussian mixtures first.

Fitted score fields and a bounded-support counterexample show why the target density and boundary conditions matter.
Fitted score fields and a bounded-support counterexample show why the target density and boundary conditions matter.

Which derivative removes the normalizer?

Let an energy Eθ(x) define a positive integrable density on Euclidean space. The normalizer Zθ may depend on θ but not on x. The spatial score therefore has a form that avoids Zθ:

pθ(x)=e−Eθ(x)Zθ,sθ(x)=∇xlog⁡pθ(x)=−∇xEθ(x).p_\theta(x)=\frac{e^{-E_\theta(x)}}{Z_\theta},\qquad s_\theta(x)=\nabla_x\log p_\theta(x)=-\nabla_xE_\theta(x).

This cancellation does not say that the parameter derivative of log Zθ is zero. It changes the estimation objective. If pdata is the true smooth density, consider the squared discrepancy between its score and the model score:

JF(θ)=12Epdata∥sθ(x)−∇xlog⁡pdata(x)∥2.J_F(\theta)=\tfrac12\mathbb E_{p_{\rm data}}\|s_\theta(x)-\nabla_x\log p_{\rm data}(x)\|^2.

We do not know the second field. Expanding the square leaves a cross term involving it. In one dimension, integration by parts gives the essential step:

∫sθ(x)pdata′(x) dx=[pdata(x)sθ(x)]−∞∞−∫pdata(x)sθ′(x) dx.\int s_\theta(x)p'_{\rm data}(x)\,dx=[p_{\rm data}(x)s_\theta(x)]_{-\infty}^{\infty}-\int p_{\rm data}(x)s'_\theta(x)\,dx.

Under sufficient smoothness, square integrability and a vanishing boundary term, the unknown data score disappears from the parameter-dependent part. In D dimensions, the spatial derivative becomes a divergence, the sum of diagonal derivatives:

JF(θ)=JSM(θ)+C,JSM(θ)=Epdata[12∥sθ(x)∥2+∇x⋅sθ(x)].J_F(\theta)=J_{\rm SM}(\theta)+C,\qquad J_{\rm SM}(\theta)=\mathbb E_{p_{\rm data}}\left[\tfrac12\|s_\theta(x)\|^2+\nabla_x\cdot s_\theta(x)\right].

C is independent of θ. JF is nonnegative, but JSM need not be: the constant was removed. The regularity and boundary conditions are part of Theorem 1, not optional details. With N observed samples, the usual estimator is a sample average:

J^SM(θ)=1N∑n=1N[12∥sθ(xn)∥2+∑j=1D∂sθ,j∂xj(xn)].\widehat J_{\rm SM}(\theta)=\frac1N\sum_{n=1}^{N}\left[\tfrac12\|s_\theta(x_n)\|^2+\sum_{j=1}^{D}\frac{\partial s_{\theta,j}}{\partial x_j}(x_n)\right].

This needs spatial derivatives of the model score; for an energy model those are second derivatives of the energy. Eliminating the partition function does not eliminate all computational cost.

A three-parameter model with a separate optimum

Our original model uses a quartic energy on the real line. Requiring a>0 makes its density integrable even when b is negative:

Eθ(x)=a4x4+b2x2−cx,sθ(x)=−ax3−bx+c,sθ′(x)=−3ax2−b.E_\theta(x)=\tfrac a4x^4+\tfrac b2x^2-cx,\qquad s_\theta(x)=-ax^3-bx+c,\qquad s'_\theta(x)=-3ax^2-b.

The synthetic data is a Gaussian mixture with weights (.35,.65), means (−1,1.2) and common variance .25. Define φ(x)=(−x³,−x,1) so that sθ=φᵀθ. The objective is a quadratic in θ even though the energy is quartic in x:

H=E[ϕϕ⊤],r=(−3E[x2],−1,0)⊤,JSM=12θ⊤Hθ+r⊤θ,∇θJSM=Hθ+r.H=\mathbb E[\phi\phi^\top],\quad r=(-3\mathbb E[x^2],-1,0)^\top,\qquad J_{\rm SM}=\tfrac12\theta^\top H\theta+r^\top\theta,\quad\nabla_\theta J_{\rm SM}=H\theta+r.

When H is positive definite, the unconstrained optimum is −H⁻¹r. We check that this particular solution has a>0; if it did not, it would not be a valid answer for the declared quartic density family. The iterative fit and the linear-system solution provide independent checks of optimization.

Learn from a clean/noisy pair

For a known corruption kernel qσ(y|x), denoising score matching uses a target that can be computed for each sampled pair. A Gaussian corruption y=x+σε with σ>0 gives:

∇ylog⁡qσ(y∣x)=x−yσ2=−ϵσ,JDSM=12Ex,y∥sθ(y)−∇ylog⁡qσ(y∣x)∥2.\nabla_y\log q_\sigma(y\mid x)=\frac{x-y}{\sigma^2}=-\frac\epsilon\sigma,\qquad J_{\rm DSM}=\tfrac12\mathbb E_{x,y}\|s_\theta(y)-\nabla_y\log q_\sigma(y\mid x)\|^2.

The target points toward the clean sample, but one noisy y can come from many clean x values. The optimal squared-error predictor averages over those possibilities. Under conditions allowing differentiation under the integral, the conditional target averages to the score of the smoothed density pσ:

pσ(y)=∫pdata(x)qσ(y∣x) dx,E[∇ylog⁡qσ(y∣x)∣y]=∇ylog⁡pσ(y).p_\sigma(y)=\int p_{\rm data}(x)q_\sigma(y\mid x)\,dx,\qquad \mathbb E[\nabla_y\log q_\sigma(y\mid x)\mid y]=\nabla_y\log p_\sigma(y).

This is why the denoising objective can teach a marginal score using accessible conditional targets. At positive σ, that marginal is the noisy distribution, not automatically the original data distribution. Multiple noise levels are a separate extension used in DDPM and score SDEs.

For this one-dimensional Gaussian corruption and the same admissible model score, expanding the DSM square and integrating its cross term gives a useful numerical identity:

JDSM(θ)=JSM,pσ(θ)+12σ2.J_{\rm DSM}(\theta)=J_{{\rm SM},p_\sigma}(\theta)+\frac1{2\sigma^2}.

The last term is θ-independent. This identity compares DSM with implicit score matching on the smoothed density, not with implicit score matching on the original density. Confusing those distributions would give the wrong target even if the algebra were otherwise correct.

Train, compare objectives and keep a boundary counterexample

Save as score_matching.py, using Python 3.12 and NumPy 1.26.4. The model is trained by explicit gradient descent and compared with the quadratic optimum. Gaussian quadrature evaluates polynomial expectations of the declared mixture; these are distribution-level calculations, not claims about a finite real dataset. Order four already integrates the degree-six objective exactly in exact arithmetic; the program uses order sixteen.

The denoising experiment integrates independently over clean data and Gaussian corruption. The model’s partition function is never used in training. A separate helper supplies the known synthetic data density and score only for an independent check of the Fisher identity; a real estimator would not be given those quantities.

For K mixture components and Q quadrature nodes, this fixed three-parameter objective costs O(KQ) time and space. DSM’s product quadrature costs O(KQ²). These costs describe the teaching program. A neural energy model in high dimensions must additionally compute the required derivatives; its scaling is not determined by these three-parameter counts.

"""Original quartic score fit, denoising equivalence and a boundary counterexample."""
import json
import numpy as np

MEANS=np.array([-1.,1.2]); WEIGHTS=np.array([.35,.65]); DATA_VAR=.25


def parameters(theta):
    t=np.asarray(theta,float)
    if t.shape!=(3,) or not np.all(np.isfinite(t)) or not 0<t[0]<=10 or np.max(abs(t))>20:
        raise ValueError('Expected [a,b,c] with0<a<=10 and finite magnitudes<=20.')
    return t


def quadrature(sigma=0., order=16):
    if not np.isfinite(sigma) or not 0<=sigma<=2 or type(order) is not int or not 4<=order<=128:
        raise ValueError('Require sigma in[0,2], integer quadrature order in[4,128].')
    z,w=np.polynomial.hermite.hermgauss(order)
    x=(MEANS[:,None]+np.sqrt(2*(DATA_VAR+sigma*sigma))*z).ravel()
    return x,(WEIGHTS[:,None]*w/np.sqrt(np.pi)).ravel()


def score(x,theta):
    a,b,c=parameters(theta);x=np.asarray(x,float)
    if not np.all(np.isfinite(x)) or np.max(abs(x))>100:raise ValueError('Finite inputs of magnitude<=100 required.')
    return -a*x**3-b*x+c


def objective(theta,sigma=0.):
    a,b,c=parameters(theta);x,w=quadrature(sigma)
    phi=np.column_stack([-x**3,-x,np.ones_like(x)])
    derivative=np.column_stack([-3*x*x,-np.ones_like(x),np.zeros_like(x)])
    s=phi@theta
    return float(w@(.5*s*s+derivative@theta)),phi.T@(w*s)+derivative.T@w


def analytic(sigma=0.):
    x,w=quadrature(sigma);phi=np.column_stack([-x**3,-x,np.ones_like(x)])
    h=phi.T@(w[:,None]*phi);r=np.array([-3*(w@(x*x)),-1.,0.])
    optimum=np.linalg.solve(h,-r)
    parameters(optimum)  # Normalizability checked, never silently projected.
    return optimum,h


def train():
    optimum,h=analytic();theta=np.array([.2,.5,0.]);history=[objective(theta)[0]]
    # Stable gradient descent on a positive-definite quadratic; a remains positive here.
    rate=1/np.linalg.eigvalsh(h)[-1]
    for step in range(2000):
        theta-=rate*objective(theta)[1];parameters(theta)
        if (step+1)%400==0:history.append(objective(theta)[0])
    return theta,history


def denoising(theta,sigma=.4):
    parameters(theta)
    if not np.isfinite(sigma) or not .05<=sigma<=2:raise ValueError('DSM sigma must be in[.05,2].')
    x,w=quadrature();z,v=np.polynomial.hermite.hermgauss(16);z=np.sqrt(2)*z;v=v/np.sqrt(np.pi)
    noisy=x[:,None]+sigma*z[None,:];weight=w[:,None]*v[None,:]
    target=-z[None,:]/sigma
    residual=score(noisy,theta)-target
    phi=np.stack([-noisy**3,-noisy,np.ones_like(noisy)],axis=-1)
    return float(np.sum(weight*.5*residual**2)),np.sum((weight*residual)[:,:,None]*phi,axis=(0,1))


def data_density_score(x,sigma=0.):
    if not np.isfinite(sigma) or not 0<=sigma<=2:raise ValueError('sigma must be in[0,2].')
    x=np.asarray(x,float);var=DATA_VAR+sigma*sigma
    residual=x[...,None]-MEANS
    log_components=np.log(WEIGHTS)-.5*np.log(2*np.pi*var)-.5*residual**2/var
    shift=np.max(log_components,axis=-1,keepdims=True)
    normalized=np.exp(log_components-shift);total=normalized.sum(axis=-1,keepdims=True)
    density=np.exp(shift[...,0])*total[...,0]
    return density,np.sum(normalized/total*(-residual/var),axis=-1)


def boundary_example(a):
    if not np.isfinite(a) or abs(a)>20:raise ValueError('Finite slope of magnitude<=20 required.')
    # Data uniform on[0,1], model score s(x)=a*x. The boundary term is a.
    return dict(explicit=a*a/6,implicit=a*a/6+a,boundary=a,corrected=a*a/6)


def demo():
    theta,history=train();opt,_=analytic();blur,_=analytic(.4)
    other=np.array([.4,-.2,.3])
    return dict(parameters=theta.tolist(),analytic_parameters=opt.tolist(),objective=history,
                coefficient_error=float(np.max(abs(theta-opt))),blurred_optimum=blur.tolist(),
                dsm_minus_implicit=[denoising(t)[0]-objective(t,.4)[0] for t in [theta,other]],
                boundary_zero=boundary_example(0),boundary_naive_minimum=boundary_example(-3))


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

A negative objective and a changed target

Starting at (.2,.5,0), 2,000 gradient steps with rate 1/λmax(H) reach approximately (.702753917385,−.998770754429,.340536042874). The largest coefficient difference from the linear-system optimum is about 3.66×10⁻¹⁵. JSM falls from −.597985208 to −1.11975964844. Its negative value is allowed because the θ-independent constant was removed.

With σ=.4, DSM minus the smoothed implicit objective is 3.125 for two different parameter vectors, and their gradients agree. The smoothed optimum becomes approximately (.292817253112,−.269485988057,.265398370412), which differs substantially from the original-distribution optimum. Denoising at a positive noise level changes which density’s slope is being learned.

The checks differentiate all three parameters of both objectives, compare quadrature orders and use independent data-space integration to verify the Fisher identity. No normalizer of the quartic model is needed for these training calculations.

The boundary is part of the problem

Now let data be uniform on [0,1] and let a bounded-domain model have score s(x)=ax. The data score is zero in the interior, but the classic smooth full-real-line assumptions fail at the endpoints. Direct calculation gives:

JF(a)=a26,Jnaive(a)=a26+a,[p(x)s(x)]01=a,JF=Jnaive−a.J_F(a)=\frac{a^2}{6},\qquad J_{\rm naive}(a)=\frac{a^2}{6}+a,\qquad [p(x)s(x)]_0^1=a,\qquad J_F=J_{\rm naive}-a.

Blindly dropping the boundary term selects a=−3 instead of zero: the naive objective is −1.5 there, while the true squared discrepancy is 1.5. This does not refute the conditional theorem; it shows what happens when its assumptions are ignored. Bounded supports require an appropriate boundary-aware formulation, not automatic reuse of the full-space expression.

Finite-sample fitting can also overfit, and an arbitrary vector field need not be the gradient of a normalizable density. Our quartic construction addresses that issue by deriving the score from an integrable energy family. It does not establish neural training stability, high-dimensional estimation accuracy or the convergence of a downstream sampler. Learning a score and sampling from it are distinct tasks.

Which constant and which density?

  1. Derivative. Does cancellation of Zθ mean its parameter derivative is zero? Answer: No. The score differentiates with respect to x, for which Zθ is constant. A derivative with respect to θ generally does include the normalizer.
  2. Hand calculation. With σ=.4 in the one-dimensional Gaussian DSM example, what is the constant gap to smoothed implicit score matching? Answer: 1/(2·.4²)=3.125. This does not compare the DSM objective with the original, unsmoothed data objective.
  3. Boundary. On the uniform interval example, what is wrong with choosing a=−3 because its naive objective is smaller? Answer: The missing boundary term is a. Correcting it leaves a²/6, minimized at zero; at −3 the true discrepancy is 1.5 rather than zero.
  4. Method choice. Must the model score lie between zero and one, and does fitting it provide a sampler automatically? Answer: Neither. A score is a signed spatial derivative and can exceed one in magnitude. A sampling procedure, its step size and its convergence or approximation properties need separate analysis.

Keep the original and denoising objectives distinct

Read Hyvärinen’s Theorem 1 and its conditions, then Vincent’s Section 4.2. The former removes an unknown data score using integration by parts; the latter supplies a computable conditional target whose average is a smoothed marginal score. The examples here independently check those mechanisms. They do not reproduce the papers’ image experiments or constitute a full review of their asymptotic results and appendices.

Make a prediction, then check

Why can the spatial score avoid the partition function?

Choose one answer

Learning objectives

  • Separate spatial scores from parameter gradients.
  • Derive score matching with its boundary term.
  • Compare denoising and smoothed-density targets.
  • Verify a three-parameter fit and its limits.

Prerequisites & connections

Explore related knowledge →

References

  1. Estimation of Non-Normalized Statistical Models by Score Matching
    Aapo Hyvärinen · 2005
  2. A Connection Between Score Matching and Denoising Autoencoders
    Pascal Vincent · 2011

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-20 · Single AI author checked Hyvarinen2005 theorem1/boundary assumptions and Vincent2011 section4.2. Eleven paired equations/four explained exercises; original quartic energy, all3 parameter gradients of implicit/DSM objectives, independent Fisher integration, smoothed target and uniform-boundary counterexample. No asymptotic theorem or image reproduction.

  • Single AI author checked Hyvarinen2005 theorem1/boundary assumptions and Vincent2011 section4.2. Eleven paired equations/four explained exercises; original quartic energy, all3 parameter gradients of implicit/DSM objectives, independent Fisher integration, smoothed target and uniform-boundary counterexample. No asymptotic theorem or image reproduction.
  • Four computed SVG variants per topic. Fifteen numeric/geometry tests and24 responsive cases passed; eight final Chinese-mobile/English-desktop screenshots actually inspected. Axis and evidence corrections retained. Full article-page acceptance recorded separately.

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.