Quadratic forms
二次型
Read coupled squared terms as matrix geometry, derive gradients, and distinguish symmetric parts, curvature, and coordinate changes.
quadratic-formsA score that couples two errors
Suppose two numerical errors are and . A score such as penalizes both their combined effect and the second error separately. Expanding gives . 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 . “Homogeneous” means : 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 , split it into a symmetric part and a skew-symmetric part . Since , the scalar equals its own transpose and must be zero. Therefore
The opening score uses . It can also be represented by the nonsymmetric 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:
For a fixed matrix A, differentiating each product yields
Writing is valid when A is symmetric; it is wrong for the nonsymmetric example. If an objective is with symmetric S, the gradient is 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 arithmetic operations and 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 , and set . Then
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 gives positive values on both coordinate axes, but gives −2 at . Off-diagonal coupling can reveal behavior invisible in coordinate-wise checks.
For a general invertible coordinate change , the matrix becomes . This is a congruence transformation, not the similarity transform 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 .
Locate the missing factor
- Which symmetric matrix represents ? Answer: ; the off-diagonal entry is three, not six.
- What is the gradient at for the opening form? Answer: , using either the expanded polynomial or .
- Does adding a skew-symmetric matrix change the form? Answer: no, because .
- 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?
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
- Mathematics for Machine Learning — mathematical foundations (2024-01-15 draft)
Marc Peter Deisenroth; A. Aldo Faisal; Cheng Soon Ong · 2020 - 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:
- Mathematics for Machine Learning — mathematical foundations (2024-01-15 draft) · §3.2.3, positive forms and inner-product matrix interpretation
- Convex Optimization · §§3.1.3–3.1.4 and Example 3.2, printed pp.69–71 / PDF pp.83–85; Appendix A.5.2
Related topics