AI Wiki中文/EN

Quadratic forms

二次型

Read coupled squared terms as matrix geometry, derive gradients, and distinguish symmetric parts, curvature, and coordinate changes.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

A score that couples two errors

Suppose two numerical errors are x1x_1 and x2x_2. A score such as 2(x1+x2)2+2x222(x_1+x_2)^2+2x_2^2 penalizes both their combined effect and the second error separately. Expanding gives 2x12+4x1x2+4x222x_1^2+4x_1x_2+4x_2^2. The cross term means that changing one error alters the effect of changing the other.

A quadratic form writes such a homogeneous degree-two polynomial as q(x)=x⊤Axq(x)=x^\top Ax. “Homogeneous” means q(cx)=c2q(x)q(cx)=c^2q(x): there are no linear or constant terms. Quadratic objectives may additionally contain those terms, but then the full function is no longer a pure quadratic form. This distinction keeps gradient and curvature formulas clear. Convex Optimization, Sections 3.1.3–3.1.4

Only the symmetric part contributes

For any real square AA, split it into a symmetric part S=(A+A⊤)/2S=(A+A^\top)/2 and a skew-symmetric part K=(A−A⊤)/2K=(A-A^\top)/2. Since K⊤=−KK^\top=-K, the scalar x⊤Kxx^\top Kx equals its own transpose −x⊤Kx-x^\top Kx and must be zero. Therefore

q(x)=x⊤Ax=x⊤Sx,S=A+A⊤2.q(x)=x^\top Ax=x^\top Sx,\qquad S=\frac{A+A^\top}{2}.

The opening score uses S=[2224]S=\begin{bmatrix}2&2\\2&4\end{bmatrix}. It can also be represented by the nonsymmetric A=[2314]A=\begin{bmatrix}2&3\\1&4\end{bmatrix} because the two cross coefficients add to four. A quadratic form does not uniquely determine an arbitrary nonsymmetric matrix; it does uniquely determine its symmetric representative.

Expanding by coordinates makes the cross-term convention visible:

x⊤Sx=∑iSiixi2+2∑i<jSijxixj.x^\top Sx=\sum_i S_{ii}x_i^2+2\sum_{i<j}S_{ij}x_ix_j.

For a fixed matrix A, differentiating each product yields

∇q(x)=(A+A⊤)x=2Sx,∇2q(x)=A+A⊤=2S.\nabla q(x)=(A+A^\top)x=2Sx,\qquad \nabla^2q(x)=A+A^\top=2S.

Writing 2Ax2Ax is valid when A is symmetric; it is wrong for the nonsymmetric example. If an objective is f(x)=12x⊤Sx+b⊤x+cf(x)=\tfrac12x^\top Sx+b^\top x+c with symmetric S, the gradient is Sx+bSx+b and the Hessian is S. The factor one-half was chosen precisely to cancel the two.

Check the cross term and every derivative

The program computes both value and gradient for a finite real matrix. It compares the nonsymmetric representation with its symmetric part, checks the completed-square expression, and finite-differences each coordinate. The skew-symmetric test catches a mistaken assumption that every matrix entry contributes independently to the value.

import math

def quadratic_value_gradient(a, x):
    n = len(a)
    if not n or len(x) != n or any(len(row) != n for row in a):
        raise ValueError("matching nonempty square matrix and vector required")
    if any(not math.isfinite(v) for row in a for v in row) or any(not math.isfinite(v) for v in x):
        raise ValueError("finite real inputs required")
    ax = [sum(a[i][j]*x[j] for j in range(n)) for i in range(n)]
    value = sum(x[i]*ax[i] for i in range(n))
    gradient = [sum((a[i][j]+a[j][i])*x[j] for j in range(n)) for i in range(n)]
    if not math.isfinite(value) or not all(math.isfinite(g) for g in gradient):
        raise ArithmeticError("nonfinite quadratic computation")
    return value, gradient

a = [[2.,3.],[1.,4.]]
symmetric = [[2.,2.],[2.,4.]]
assert quadratic_value_gradient(a,[1.,-1.]) == (2.,[0.,-4.])
for x in ([1.,-1.],[.4,-.7],[0.,0.]):
    value,gradient = quadratic_value_gradient(a,x)
    assert abs(value-quadratic_value_gradient(symmetric,x)[0]) < 1e-12
    assert abs(value-(2*(x[0]+x[1])**2+2*x[1]**2)) < 1e-12
    for i in range(2):
        plus,minus = list(x),list(x)
        plus[i] += 1e-5; minus[i] -= 1e-5
        numeric = (quadratic_value_gradient(a,plus)[0]-quadratic_value_gradient(a,minus)[0])/2e-5
        assert abs(numeric-gradient[i]) < 1e-8
assert quadratic_value_gradient([[0.,2.],[-2.,0.]],[3.,4.]) == (0.,[0.,0.])
assert quadratic_value_gradient([[1.,2.],[2.,1.]],[1.,-1.])[0] == -2.
for a,x in (([],[]), ([[1.]], [1.,2.]), ([[float('nan')]], [1.])):
    try:
        quadratic_value_gradient(a,x)
    except ValueError:
        pass
    else:
        raise AssertionError("invalid input accepted")

The dense computation costs O(n2)O(n^2) arithmetic operations and O(n)O(n) working storage beyond the supplied matrix. These are exact quadratic derivatives up to arithmetic error. Finite differences are verification tools with their own step-size error, not the method used to compute the returned gradient.

Shapes of the surface depend on directions

Apply the spectral theorem to S=QΛQ⊤S=Q\Lambda Q^\top, and set y=Q⊤xy=Q^\top x. Then

q(x)=∑iλiyi2.q(x)=\sum_i\lambda_i y_i^2.

Positive eigenvalues produce a bowl with a unique minimum at the origin. Nonnegative values with some zeros leave flat directions. A mixture of positive and negative values produces a saddle. All negative values give an upside-down bowl. These statements refer to the form over the entire real vector space; constraints can change an optimization problem’s feasible minima. MML, Section 3.2.3, Convex Optimization, Appendix A.5.2

Testing a few directions cannot prove that all quadratic values are nonnegative. The matrix [1221]\begin{bmatrix}1&2\\2&1\end{bmatrix} gives positive values on both coordinate axes, but gives −2 at (1,−1)(1,-1). Off-diagonal coupling can reveal behavior invisible in coordinate-wise checks.

For a general invertible coordinate change x=Bzx=Bz, the matrix becomes B⊤SBB^\top SB. This is a congruence transformation, not the similarity transform B−1SBB^{-1}SB for a linear operator. It preserves positive/negative character, but need not preserve individual eigenvalues. With orthogonal B the two coordinate descriptions line up because B−1=B⊤B^{-1}=B^\top.

Locate the missing factor

  1. Which symmetric matrix represents x12+6x1x2+5x22x_1^2+6x_1x_2+5x_2^2? Answer: [1335]\begin{bmatrix}1&3\\3&5\end{bmatrix}; the off-diagonal entry is three, not six.
  2. What is the gradient at (1,−1)(1,-1) for the opening form? Answer: (0,−4)(0,-4), using either the expanded polynomial or 2Sx2Sx.
  3. Does adding a skew-symmetric matrix change the form? Answer: no, because x⊤Kx=0x^\top Kx=0.
  4. What happens to q when x is multiplied by −3? Answer: q is multiplied by nine; the sign of x alone does not reverse the value of a quadratic form.

Curvature, distances, and probability

Squared-error losses and local second-order approximations use quadratic forms. A positive-definite matrix also defines an inner product and an ellipsoidal distance. A nondegenerate Gaussian density uses a quadratic form involving the inverse covariance in its exponent. Keep the matrix’s role explicit: covariance, precision, Hessian, and metric are related in some models, but are not interchangeable names. The positive-definite matrices article develops tests and factorization methods for the required sign conditions.

Make a prediction, then check

For A=[[2,3],[1,4]] and x=(1,−1), what is the gradient of xᵀAx?

Choose one answer

Learning objectives

  • Write cross terms with a symmetric matrix and show that the skew-symmetric part vanishes.
  • Derive values, gradients, Hessians, and directional curvature.

Prerequisites & connections

Explore related knowledge →

References

  1. Mathematics for Machine Learning — mathematical foundations (2024-01-15 draft)
    Marc Peter Deisenroth; A. Aldo Faisal; Cheng Soon Ong · 2020
  2. Convex Optimization
    Stephen Boyd; Lieven Vandenberghe · 2004

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-05 · Codex technical check: cited-source comparison, derivation and numerical checks, bilingual argument comparison, and executed Python assertions; no independent human peer review.

  • Checked symmetric parts, homogeneous scaling and every finite-difference gradient for 60 random small matrices; checked skew-symmetric cancellation and cross-term factors.
  • Distinguished pure forms, quadratic objectives with linear terms and congruence transformations; curvature claims are scoped to the corresponding symmetric matrix.
  • Compared claims, assumptions, examples, exercises and citations across languages; structural validation additionally compares display equations, code and source lists.

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.