AI Wiki中文/EN

Nonnegative matrix factorization: additive components and exact coordinate steps

非负矩阵分解

Derive a Frobenius NMF solver, track exact rational losses, and distinguish a stationary point from an optimal factorization.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

Build a record by adding components

A catalogue records three nonnegative measurements for each of four objects. Could a few reusable patterns explain the table? NMF, or nonnegative matrix factorization, approximates every column by adding nonnegative multiples of nonnegative component columns. A component cannot explain one feature by adding it and then subtracting another component’s contribution.

That restriction can make a decomposition easier to inspect. It does not guarantee that each component is sparse, unique, or a meaningful physical part. The choice of measurements, scaling, loss and number of components still determines what the model can express. Lee and Seung’s algorithms paper studies nonnegative factors under two different reconstruction criteria; the present chapter uses squared error.

Our table is small enough to check exactly. Its columns are (4,0,4), (0,3,3), (4,3,7) and (2,3,5). There is a zero-error representation using components (1,0,1) and (0,1,1). The third measurement adds the first two in this constructed example. We keep that factorization as an independent certificate and start the algorithm from different factors, so the calculation can show both progress and unfinished work.

A product constraint changes the optimization

Put the observations in the columns of a matrix with m rows and n columns. Choose r components, collect them in W, and place each object’s component weights in a column of H. The Frobenius objective used here is:

V∈R≥0m×n,W∈R≥0m×r,H∈R≥0r×n,min⁡W,H≥0f(W,H)=12∥V−WH∥F2.V\in\mathbb R_{\ge0}^{m\times n},\quad W\in\mathbb R_{\ge0}^{m\times r},\quad H\in\mathbb R_{\ge0}^{r\times n}, \qquad \min_{W,H\ge0} f(W,H)=\frac12\|V-WH\|_F^2.

The factor of one half simplifies derivatives. Fixing W gives a convex nonnegative least-squares problem in H; fixing H gives one in W. Jointly the problem is nonconvex because the unknowns multiply. With the scalar observation 1, the points (W,H)=(1,1) and (2,1/2) both have zero loss, but their midpoint has product 9/8 and positive loss. This violates the convexity inequality. Thus solving individual convex subproblems does not turn the joint problem into a convex one.

Even a zero-error factorization need not be unique. For any positive diagonal matrix D, W*D and D⁻¹*H reconstruct the same table. A matching permutation of component columns and weight rows also preserves the product. Additional nonuniqueness can remain after normalizing scales. Unlike PCA, NMF does not impose orthogonal components or order them by explained variance. Nonnegative factors alone do not imply independent components as in ICA.

A transparent way to minimize the objective is to change one coordinate at a time. Hold every entry except H[a,j]=t fixed and remove component a from the residual. With all sums evaluated at the current factors:

Rij(−a)=Vij−∑b≠aWibHbj,q=∑iWia2,c=∑iWiaRij(−a),t∗=max⁡{0,c/q}(q>0).R_{ij}^{(-a)}=V_{ij}-\sum_{b\ne a}W_{ib}H_{bj},\qquad q=\sum_iW_{ia}^2,\qquad c=\sum_iW_{ia}R_{ij}^{(-a)}, \qquad t^*=\max\{0,c/q\}\quad(q>0).

The coordinate-dependent part of the loss is q*t²/2 - c*t. Complete the square to obtain the minimizer, then enforce the lower bound zero. If q is zero, the entire column W[:,a] is zero, so c is also zero: the objective is flat in this coordinate. We keep its previous value. Updating W[i,a] uses the same argument with the corresponding row of H. The residual excluding one component may be negative even though V, W and H are nonnegative.

Each coordinate step is an exact constrained minimization, so it cannot increase f. Repeating steps gives a nonincreasing loss sequence bounded below by zero, which therefore has a limit. This statement concerns the loss values. It does not prove that the factors converge, that finitely many sweeps reach a stationary point, or that the limiting loss is globally minimal.

For a stopping check, differentiate the full objective and impose the nonnegative-bound KKT conditions:

GW=(WH−V)H⊤,GH=W⊤(WH−V),GW≥0,GH≥0,W⊙GW=0,H⊙GH=0.G_W=(WH-V)H^\top,\qquad G_H=W^\top(WH-V),\qquad G_W\ge0,\quad G_H\ge0,\quad W\odot G_W=0,\quad H\odot G_H=0.

At a positive entry, its gradient must be zero. At a zero entry, its gradient must be nonnegative; a negative gradient would allow improvement by increasing the entry. The program reports the largest absolute gradient at positive entries or the largest negative-gradient magnitude at zeros. This violation is zero exactly when the feasible factors satisfy these first-order conditions. Lin’s analysis distinguishes stationarity from local optimality and explains why a small change in objective is not enough as a stopping test.

Exact coordinate steps, explicit remaining error

The complete Python program accepts nonnegative integers and Fraction entries. It rejects floating-point numbers, booleans, ragged or empty matrices and incompatible factor shapes. Supply the initial W and H explicitly; there is no hidden random initialization or automatic choice of r. The dimensions are positive, but r need not be smaller than both matrix dimensions.

One sweep visits H in component-then-column order, followed by W in row-then-component order. Updates take effect immediately. fit_nmf copies inputs; coordinate_sweep and report are internal helpers for those validated dimensions. losses includes the initial loss and one value per completed sweep. The program checks stationarity before the first sweep and after every sweep. Thus even a zero budget can return stationary if the supplied factors satisfy KKT; otherwise it returns sweep-limit with the actual factors and violation. There is no claim that the exact zero-violation test must pass in a finite number of sweeps.

from fractions import Fraction as F


def matrix(rows):
    try:
        result = tuple(tuple(value for value in row) for row in rows)
    except TypeError as exc:
        raise ValueError('expected a nonempty rectangular matrix') from exc
    if not result or not result[0] or any(len(row) != len(result[0]) for row in result):
        raise ValueError('expected a nonempty rectangular matrix')
    if any(type(value) not in (int, F) or value < 0 for row in result for value in row):
        raise ValueError('entries must be nonnegative int or Fraction, not bool/float')
    return tuple(tuple(F(value) for value in row) for row in result)


def checked(V, W, H):
    V, W, H = matrix(V), matrix(W), matrix(H)
    m, n, r = len(V), len(V[0]), len(H)
    if len(W) != m or len(W[0]) != r or len(H[0]) != n:
        raise ValueError('expected V:m*n, W:m*r and H:r*n')
    return V, W, H


def report(V, W, H):
    m, n, r = len(V), len(V[0]), len(H)
    residual = tuple(tuple(sum((W[i][a]*H[a][j] for a in range(r)), F(0))-V[i][j]
                          for j in range(n)) for i in range(m))
    loss = sum((value*value for row in residual for value in row), F(0))/2
    violation = F(0)
    for i in range(m):
        for a in range(r):
            g = sum((residual[i][j]*H[a][j] for j in range(n)), F(0))
            violation = max(violation, abs(g) if W[i][a] > 0 else max(F(0), -g))
    for a in range(r):
        for j in range(n):
            g = sum((W[i][a]*residual[i][j] for i in range(m)), F(0))
            violation = max(violation, abs(g) if H[a][j] > 0 else max(F(0), -g))
    return loss, violation


def coordinate_sweep(V, W, H):
    # Internal routine: validated dimensions, mutable W/H, exact arithmetic.
    m, n, r = len(V), len(V[0]), len(H)
    for a in range(r):
        for j in range(n):
            curvature = sum((W[i][a]**2 for i in range(m)), F(0))
            if curvature:
                numerator = sum((W[i][a]*(V[i][j]-sum(
                    (W[i][b]*H[b][j] for b in range(r) if b != a), F(0)))
                    for i in range(m)), F(0))
                H[a][j] = max(F(0), numerator/curvature)
    for i in range(m):
        for a in range(r):
            curvature = sum((H[a][j]**2 for j in range(n)), F(0))
            if curvature:
                numerator = sum((H[a][j]*(V[i][j]-sum(
                    (W[i][b]*H[b][j] for b in range(r) if b != a), F(0)))
                    for j in range(n)), F(0))
                W[i][a] = max(F(0), numerator/curvature)


def fit_nmf(V, W, H, max_sweeps=5):
    if type(max_sweeps) is not int or max_sweeps < 0:
        raise ValueError('max_sweeps must be a nonnegative integer')
    V, W, H = checked(V, W, H)
    W, H = [list(row) for row in W], [list(row) for row in H]
    loss, violation = report(V, W, H)
    losses, sweeps = [loss], 0
    while violation != 0 and sweeps < max_sweeps:
        coordinate_sweep(V, W, H)
        sweeps += 1
        loss, violation = report(V, W, H)
        losses.append(loss)
    return {'W': tuple(map(tuple, W)), 'H': tuple(map(tuple, H)),
            'losses': tuple(losses), 'violation': violation, 'sweeps': sweeps,
            'status': 'stationary' if violation == 0 else 'sweep-limit'}


def main():
    V = ((4, 0, 4, 2), (0, 3, 3, 3), (4, 3, 7, 5))
    W = ((1, 0), (0, 1), (1, 0))
    H = ((1, 1, 1, 1), (1, 1, 1, 1))
    fit = fit_nmf(V, W, H, max_sweeps=3)
    print('catalogue:', fit['status'], fit['sweeps'])
    print('losses:', tuple(round(float(v), 6) for v in fit['losses']))
    print('positive KKT violation:', fit['violation'] > 0)
    certificate_W = ((1, 0), (0, 1), (1, 1))
    certificate_H = ((4, 0, 4, 2), (0, 3, 3, 3))
    exact = fit_nmf(V, certificate_W, certificate_H, max_sweeps=0)
    print('known zero-loss certificate:', exact['losses'][0], exact['status'])
    rank_one = fit_nmf(((1, 0), (0, 1)), ((1,), (1,)), ((1, 1),))
    print('rank-one identity:', rank_one['losses'][-1], rank_one['status'])
    bad = fit_nmf(((1,),), ((0,),), ((0,),))
    print('zero factors:', bad['losses'][0], bad['status'], bad['sweeps'])
    revived = fit_nmf(((2,),), ((1,),), ((0,),))
    print('revived H:', revived['H'][0][0], revived['losses'][-1])


if __name__ == '__main__':
    main()

The output is:

catalogue: sweep-limit 3
losses: (49.0, 2.139918, 1.627602, 1.220837)
positive KKT violation: True
known zero-loss certificate: 0 stationary
rank-one identity: 1/2 stationary
zero factors: 1/2 stationary 0
revived H: 2 0

The displayed decimals summarize exact rational losses. After three sweeps, the catalogue fit has improved but still violates KKT. The separate known factors achieve loss zero, which is a global certificate because the objective cannot be negative. That certificate does not say the iterative fit found those factors.

The identity-matrix example has a different certificate. For V=I₂, any rank-one product w*hᵀ obeys ||w*hᵀ||²_F=||w||²*||h||² and wᵀh ≤ ||w||*||h||. Let t=||w||*||h||. Its squared error is at least 2 - 2*t + t² = 1 + (t-1)². Hence the half-squared loss is at least 1/2, attained by the returned product. The lower bound applies even without nonnegativity, so it also certifies this NMF solution. A low score in a different problem would need its own evidence.

This deliberately direct implementation recomputes the excluded-component sum. With m, n and r positive and T completed sweeps, it uses O(m*n*r + T*m*n*r²) rational arithmetic operations and O(m*n + m*r + r*n + T) stored numbers. The initial report, input copies and loss history are included. Fraction numerators and denominators can grow rapidly; these counts do not give bit complexity or imply that long exact runs are inexpensive.

Nonnegative does not mean identifiable or optimal

The scalar case V=1, W=H=0 passes KKT and stops before any sweep. Each gradient is zero because it is multiplied by the other factor. Yet setting both factors to a small positive ε changes the loss to (1-ε²)²/2, which is smaller for 0<ε<sqrt(2). This is a nonoptimal stationary point; looking at either coordinate alone misses the joint direction of improvement. Initialization matters.

The classic multiplicative update takes a different route. For the squared-error objective, one H block update is, entry by entry:

H←H⊙W⊤VW⊤WH.H\leftarrow H\odot\frac{W^\top V}{W^\top W H}.

With the needed positive denominators, Lee and Seung derive objective nonincrease through an auxiliary function. This is not the coordinate-minimization algorithm above. Multiplication can preserve zero entries even when reviving them would help; zero denominators also require an explicit policy. Blindly adding a small constant changes the update and is not a proof of convergence. In contrast, our coordinate rule revives H=0 to 2 when V=2,W=1, because that coordinate has positive curvature and a positive minimizing value. When both factors are zero, its curvature is zero and the earlier failure remains.

A zero measurement, a missing measurement and a signed measurement are different inputs. This implementation treats every zero as observed data and includes it in the squared-error loss. It has no missing-value mask. Subtracting feature means generally creates negative values and changes the problem; rescaling rows also changes their relative weight in the error. Larger r can reduce training reconstruction error, but choosing r or preprocessing by repeatedly inspecting a final test set compromises that evaluation. Assess held-out reconstruction under a specified masking or encoding protocol, stability across initializations, and whether the resulting components support the intended use.

Read the factorization and its certificate

  1. Check the known catalogue factors. Reconstruct the fourth column using components (1,0,1) and (0,1,1). What proves optimality here?
Add the weighted components

Answer: Weights 2 and 3 give 2*(1,0,1)+3*(0,1,1)=(2,3,5). The stated H reconstructs the other three columns too. The loss is zero and all squared-error losses are nonnegative, so these factors are globally optimal. This says nothing about uniqueness or about the three-sweep fit reaching them.

  1. Solve a coordinate step. A current residual column excluding one component is (3,-1), and that component is (1,2). What is the new nonnegative weight?
Use curvature and correlation

Answer: The curvature is 1²+2²=5, and the numerator is 1*3+2*(-1)=1. The update is 1/5. Negative residual entries are allowed because other components may over-reconstruct part of the observation. If the component itself were all zero, both curvature and numerator would be zero, and the old weight would be retained.

  1. Interpret the stationary zero factors. Why does KKT pass for V=1,W=H=0, and why is that insufficient?
Move both factors together

Answer: Both gradients vanish because each includes the other zero factor. The bound and complementarity conditions hold. But (W,H)=(ε,ε) has smaller loss for sufficiently small positive ε. KKT is a first-order necessary condition, not a global or local minimum certificate for this nonconvex problem.

  1. Change the component scale. Double the first column of W. How can H compensate, and what does this imply when comparing two fitted models?
Preserve the product

Answer: Halve the first row of H. Every reconstruction and the objective stay the same. Compare reconstructed values or align scales and component permutations before interpreting differences between raw factors. Even after alignment, distinct valid factorizations can remain; nonnegativity alone does not establish a unique component meaning.

The representation and the solver are separate choices

Lee and Seung’s NIPS 2000 algorithms paper analyzes multiplicative updates for squared error and generalized KL divergence. Changing that criterion changes how reconstruction discrepancies are treated; the present squared-error derivation cannot simply be reused for the divergence objective. The paper’s auxiliary-function argument is useful for understanding objective descent, while claims about factors, boundary points and optimality require their own conditions.

Lin’s 2007 work develops projected-gradient approaches and emphasizes bound constraints, stationarity and meaningful stopping conditions. The exact scalar-coordinate solver here is a separate teaching implementation of the same Frobenius objective, not a reproduction of Lin’s algorithms. Continue with sparse autoencoders to compare a different representation constraint, or matrix factorization for recommendation to examine what changes when most entries are unobserved rather than zero.

Make a prediction, then check

For V=1 and W=H=0, what does the program’s stationary status establish?

Choose one answer

Learning objectives

  • Specify the nonnegative Frobenius objective and distinguish scale ambiguity from reconstruction error.
  • Derive a constrained scalar-coordinate minimizer and handle zero curvature without epsilon clipping.
  • Interpret KKT stationarity, fixed budgets and independently certified optimal examples.

Prerequisites & connections

Explore related knowledge →

References

  1. Algorithms for Non-negative Matrix Factorization
    Daniel D. Lee; H. Sebastian Seung · 2000
  2. Projected Gradient Methods for Nonnegative Matrix Factorization
    Chih-Jen Lin · 2007

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-05 · Codex technical check: primary-source locations, original runnable models, independent mathematical and computational references, bilingual review and second-agent cross-checks; not independent human peer review.

  • Eight tests pass. Independent three-point scalar-loss interpolation and symmetric exact differences check 36 small seeded reports plus the complete three-sweep catalogue report: factors, loss history, KKT violation, completed sweeps and status. This reference does not use excluded-component residuals or the author’s matrix-gradient formula.
  • Verified zero-loss product and rank-one identity lower-bound certificates, nonoptimal all-zero stationarity, zero-coordinate revival, flat/clamped coordinates, scale/permutation preservation, iterator inputs, budget boundaries and 80-digit rational inputs. The seven-line stdout reports rounded summaries only; all fitting and checks use exact Fraction arithmetic.
  • Complete original bilingual text has identical code, four matching displays, six anchors and four answers; strict MDX/KaTeX and actual React HTML/MathML pass. Only article_text controls paths. Written means AI author checking, not human review. No library benchmark, general convergence proof or whole-site build is claimed.
  • Root fully reread both articles, full code, four formulas and four exercises. All eight author tests and strict MDX/KaTeX/actual React HTML pass: four corresponding displays, six standard anchors and four answers. No revision requested; all final five SHA values match the frozen manifest.
  • Independent Fenchel dual certificates check all 56 actual coordinate assignments in six instrumented sweeps: 44 positive optima and 12 boundary-zero optima. Each residual witness satisfies dual feasibility, complementarity and exact primal-dual equality, using neither the update ratio nor the author’s three-point interpolation reference. Zero-curvature skipped assignments are not counted as certified updates.
  • Four diagonal rank-one problems attain the unrestricted singular-value residual lower bound min(a,b)²/2 with nonnegative factors. Separately reviewed the supplied zero-loss certificate, nonoptimal zero-factor KKT point, scalar joint-improvement path, scale/permutation ambiguities, zero-denominator policy and growth of rational bit lengths. These finite certificates do not establish general global convergence.
  • 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.
  • Publication verification found a remaining draft-status substring assertion. It now parses the formal JSON frontmatter and expects checked, independent of serialization whitespace. The numerical tests, their references and article program are unchanged.

Source locations checked:

  • Algorithms for Non-negative Matrix Factorization · Actually read the official seven-page PDF §§2–5: nonnegative factors, squared-error versus generalized divergence objectives, separate convexity/joint nonconvexity, multiplicative updates and diagonal rescaling. Read §6 Lemmas 1–2 and the Euclidean nonincrease argument on physical pages 4–6. Official abstract record https://proceedings.neurips.cc/paper/2000/hash/f9d1152547c0bde01830b7e8bd60024c-Abstract.html identifies NIPS 2000 and volume 13. Do not adopt the paper’s informal statements equating objective descent with convergence to a local minimum. Teaching code is original scalar coordinate minimization, not the paper’s update.
  • Projected Gradient Methods for Nonnegative Matrix Factorization · Actually read author PDF §§1–2, especially physical pages 2–5: objective, positive-diagonal scaling, gradient/KKT equations (2)–(3), distinction between stationarity and local minimum, and limits of multiplicative-update convergence claims. Also read §5 (physical pages 14–15) projected-gradient stopping and preceding zero-factor stationary-point discussion. Publisher and author NMF publication records identify 2007, Neural Computation 19, 2756–2779. No projected-gradient implementation or benchmark was reproduced.
  • Algorithms for Non-negative Matrix Factorization · Root independently opened the official seven-page NIPS paper and read extracted squared-error/multiplicative-update and auxiliary-function discussion. Reviewed the article’s distinction between the source algorithm and original exact coordinate minimization; no source benchmark or full proof reproduction claimed.
  • Projected Gradient Methods for Nonnegative Matrix Factorization · Root independently opened the 27-page author PDF and read extracted physical pp.4–5 lines 113–180: gradients, KKT equations (2)–(3), local-minimum versus stationary-point distinction, multiplicative rule and warning that descent does not establish convergence. Root does not attribute the separate scalar coordinate solver’s convergence to the paper’s full-block alternating-minimization theorem.

Related topics

No matches. Try a synonym or acronym.

0 results shown

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