In the previous lesson you formulated problems of the form “minimize f(x) subject to x∈C” and saw that a local optimum is generally not global. Nearly everything we can truly solve with guarantees at scale relies on a geometric property of C: the segment joining two feasible points is feasible. This is convexity. With it, moving from one point toward another never leaves the permitted region, making traps disappear: if C and f are convex (next lesson), every local minimum is global (local and global minima).
Convex sets constantly appear in machine learning, sometimes disguised:
Probabilities. A softmax output vector, mixture weights or portfolio weights without short selling live in the simplex{x≥0,1⊤x=1}. A linear portfolio-weight constraint defines a polyhedron.
Regularization. Lasso and ridge can be written “minimize error with ∥w∥1≤r” or “with ∥w∥2≤r”: restrict to a norm ball (lasso). Its shape, edged or round, determines whether the solution is sparse.
Robustness. An admissible perturbation set {δ:∥δ∥∞≤ε} is a ball, and training or evaluating with projected-gradient attacks consists of stepping and projecting back onto it. This is an evaluation and defense technique: projection keeps the perturbation within budget.
Separation. A maximum-margin SVM’s margin is the distance between the two classes’ convex hulls (maximum-margin classifier), and finding the hyperplane means finding the closest pair of points.
Conic programming. The problems in lesson 4 (SOCP and SDP) optimize over two particular cones, second-order and semidefinite, constructed here.
This lesson supplies geometric vocabulary for the module. We start with point combinations and the sets they sweep, continue through a catalog of convex sets and cones (including the semidefinite cone you can rotate in 3D), see how to build convex sets from others, and finish with two results governing almost all later algorithms: projection onto a convex set and separation theorems, proved from each other.
Affine, convex and conic combinations
Given points x1,…,xk∈Rn and weights θ1,…,θk∈R, point p=∑iθixi is a linear combination. Imposing weight conditions changes the nature of the set of possible p. Three conditions matter:
Weight condition
Name
Set swept with x1,…,xk
none
linear combination
linear span, span{xi}
∑iθi=1
affine
affine hull, aff
θi≥0
conic
generated cone, cone
∑iθi=1 and θi≥0
convex
convex hull, conv
The figure lets you manipulate all three at once. With two points, the affine hull is their line, the convex hull their segment and the conic hull the wedge formed by rays from the origin. Weights go from “anything” to “sum to 1” to “nonnegative,” and each constraint shrinks the set.
InteractiveCombination painter
convex hull (∑θi=1, θi≥0)
cone (θi≥0)
affine hull (∑θi=1)
p and its contributions θixi
Combination weights
Sets to display
∑iθi1.00
miniθi0.20
Combinationconvex
p belongs toconvex hull · cone · affine hull
p(1.88, 1.42)
∑θi=1 and all θi≥0: a convex combination. p is inside the convex hull by construction.
Drag points xi and move weights θi: p=∑iθixi. With initial weights, p is inside the triangle (green: convex combination). Set θ1=0.8 and θ3=−0.3: weights still sum to 1 and p leaves the triangle (affine combination, magenta). Return θ3 to 0.2: weights are nonnegative but sum to 1.5, and p is outside the triangle but inside the cone (conic, not affine). Select “Normalize” to divide by ∑θi: with nonnegative weights, p returns to the convex hull. Remove a point: the affine hull goes from plane to line. Bring the three points close to a line: what happens to the cone?
Notice three things. First, the cone always passes through the origin but the convex hull need not: the origin is special for conic, not convex, combinations. Second, the convex hull lies within both others: every convex combination is both affine and conic. Third, one point p may have representations with different weights: for three noncollinear planar points affine weights are unique (barycentric coordinates), but conic weights generally are not. A set is defined by what is reachable, not particular chosen weights.
Convex sets
The empty set, a point, a line, a segment and all Rn are convex. The definition uses two points but extends naturally to any number.
Proof
One implication is the case k=2. For the other, induct on k: let p=∑i=1kθixi with xi∈C, θi≥0, ∑iθi=1. If θk=1, p=xk∈C. Otherwise write
p=(1−θk)qi<k∑1−θkθixi+θkxk,
where q is a convex combination of k−1 points of C, hence lies in C by the induction hypothesis, and p is a convex combination of two points of C. It remains that conv(S) is convex (a convex combination of convex combinations is convex) and any convex set containing S contains all its convex combinations.
∎
How many points describe a point in a convex hull? In the plane, a triangle suffices: any point inside a polygon lies in a triangle formed by three vertices. This is general.
Proof
Take a representation x=∑i=1mθixi with all θi>0 and minimal m, and suppose m≥n+2. The m−1≥n+1 vectors xi−x1 (i≥2) lie in Rn, so are linearly dependent: some μ2,…,μm, not all zero, satisfy ∑i≥2μi(xi−x1)=0. With μ1=−∑i≥2μi we get ∑iμixi=0, ∑iμi=0 and some μi>0. For every t≥0, x=∑i(θi−tμi)xi and weights still sum to 1. With t=min{θi/μi:μi>0} all weights are nonnegative and at least one is zero: a representation with fewer points, contradicting minimality.
∎
A catalog of convex sets
Almost every convex set you will use is one of these or obtained from them by the next section’s operations.
Hyperplane{x:a⊤x=b} and closed half-space{x:a⊤x≤b}, with a=0. A segment between points satisfying a⊤x≤b also satisfies it because a⊤(θx+(1−θ)y)=θa⊤x+(1−θ)a⊤y≤b.
Norm balls. Every norm gives a convex ball {x:∥x−c∥≤r}, by triangle inequality and homogeneity: ∥θx+(1−θ)y−c∥=∥θ(x−c)+(1−θ)(y−c)∥≤θ∥x−c∥+(1−θ)∥y−c∥≤r. This includes ℓ1 balls (diamond or octahedron), ℓ2 (round) and ℓ∞ (cube). With p<1 the “ball” ∑i∣xi∣p≤1 is no longer convex, which is why ∥⋅∥p with p<1 is not a norm.
Ellipsoids{x:(x−c)⊤P−1(x−c)≤1} with positive definiteP: they are images of the unit ball under affine map u↦c+P1/2u: an ellipsoid is a ball deformed by a matrix.
Probability simplexΔn={x∈Rn:x≥0,1⊤x=1}, the convex hull of canonical basis vectors.
Two types of polyhedral sets deserve their own definition because they appear in linear and quadratic programming.
A polyhedron is always convex (an intersection of convex sets). The Minkowski–Weyl theorem says more: polytopes are exactly convex hulls of finitely many points (the “vertex representation”), and polyhedra are sums of a polytope and a finitely generated cone. These describe the same object at very different costs: the unit square has 4 half-spaces and 4 vertices, but cube [−1,1]n has 2n half-spaces and 2n vertices, whereas cross-polytope {∥x∥1≤1} has 2n vertices and 2n facets. Conversion can be exponential, so algorithms choose the convenient form. Simplexes and boxes are polyhedra.
What is not convex matters as much as what is:
The union of two convex sets is not generally convex: two disjoint disks.
The complement of a ball (a disk’s exterior) and any set with a “hole.”
Sparse-vector sets {x:∥x∥0≤k} (with ∥x∥0 the number of nonzero components): a union of coordinate subspaces; for example, midpoint of (1,0) and (0,1) has two nonzero components and leaves {∥x∥0≤1}. This nonconvexity is why exact feature selection is combinatorial and ∥⋅∥0 is replaced by ∥⋅∥1 (its convex envelope on the unit ℓ∞ ball).
{x:x⊤Ax≥1} with positive definite A: an ellipsoid’s exterior.
Cones
If a condition holds for x and is homogeneous, it also holds for tx with t≥0. Sets with that property are cones.
Proper cones define generalized inequalities, x⪯Ky⟺y−x∈K, which work like ordinary order on R (reflexive, transitive, antisymmetric because K is pointed, and compatible with addition and nonnegative scalar multiplication). With K=R+n this is componentwise inequality. Three cones underpin modern convex programming.
The nonnegative orthantR+n={x:xi≥0}.
The second-order (Lorentz) cone
Ln+1={(x,t)∈Rn×R:∥x∥2≤t},
the “ice cream” cone (in R3, a right circular cone with half-angle 45°). It is convex by triangle inequality: if ∥x∥≤t and ∥y∥≤s, then ∥αx+βy∥≤αt+βs.
3. The positive semidefinite coneS+n={X∈Sn:X⪰0} in the space Sn of symmetric n×n matrices, a vector space of dimension n(n+1)/2 with trace inner product ⟨X,Y⟩=tr(XY) (its norm is Frobenius). It is convex because v⊤(αX+βY)v=αv⊤Xv+βv⊤Yv≥0: an intersection over all v of half-spaces {X:⟨vv⊤,X⟩≥0}.
The third is richest and least visual. For n=2 it fits in three dimensions. A symmetric matrix [xyyz] is positive semidefinite if and only if x≥0, z≥0 and xz≥y2 (determinant and trace are nonnegative). Changing coordinates to
p=2x−z,q=2y,r=2x+z,
which preserve Frobenius norm (∥X∥F2=x2+2y2+z2=p2+q2+r2), gives xz−y2=(r2−p2−q2)/2, so
S+2={(p,q,r):p2+q2≤r}=L3.
The 2×2 semidefinite cone is isometrically the second-order cone in R3. Not so for n≥3: the boundary of S+n mixes matrices of different ranks and has faces of several dimensions (for example, 3×3 semidefinite matrices whose image lies in a fixed plane form a face of dimension 3, a copy of S+2), whereas the second-order cone’s only nontrivial proper faces are its generating rays.
InteractiveThe semidefinite cone in 3D
cone S+2: r≥p2+q2
X (green inside, amber on boundary, red outside)
projection Π(X) onto the cone
Examples
Matrix entries
X=[1.400.500.501.00]
λmax1.739
λmin0.661
detX=xz−y21.150
trX2.400
Positioninterior
λmin=0.66>0: positive definite, inside the cone (its interior), with det>0.
Each point is a symmetric matrix [xyyz], drawn in coordinates (p,q,r) above. Rotate the scene. Inside the cone both eigenvalues are positive; on its surface λmin=0 and determinant is zero (rank 1); outside λmin<0. Move t to add tI: the point moves vertically, parallel to the cone axis, crossing the boundary exactly when t=−λmin. For a point outside the cone its projection appears: truncating the negative eigenvalue takes it to the nearest cone point.
The cone is pointed (its only point in S+n∩(−S+n) is 0), closed and has nonempty interior (positive definite matrices). The figure shows a useful property: interior consists of strictly positive definite matrices and boundary of singular ones, so “inside” is equivalent to λmin>0, and matrix inequality X⪰0 constrains one number, λmin(X)≥0. In semidefinite programming (SDP) it becomes an optimization constraint.
The dual cone
A cone can be viewed “from outside”: which directions form an acute angle with all its points?
In the plane, the dual of a wedge of aperture α≤π is a wedge of aperture π−α, with edges perpendicular to those of the first. The figure shows it: drag generators of K and watch K∗ open and close.
InteractiveThe dual cone
cone K (generated by gi)
dual cone K∗
lines ⟨y,gi⟩=0 (colored by gi)
test point y
Initial configuration
Generators
K iswedge of 29°
K∗ iswedge of 151°
⟨y,g1⟩3.69
⟨y,g2⟩4.38
y∈K∗yes
K opens 29° and K∗ opens 151°: the larger K is, the smaller K∗ is. The two angles add to 180°.
K (blue) is generated by vectors gi and K∗ (orange) is the set of y with ⟨y,gi⟩≥0 for all of them. Each dashed line, in its generator's color, marks ⟨y,gi⟩=0, and K∗ is the intersection of half-planes facing gi. Open and close K: what happens to K∗? Move K to the quadrant with the “Quadrant” preset: K∗=K. Place two opposite generators (a line) or, with three, open it past 180°: what is the dual of a non-pointed cone? Drag y and inspect products with generators.
Three calculation rules visible in the figure: if K1⊆K2 then K2∗⊆K1∗ (more generators, more conditions, fewer valid y); a subspace’s dual is its orthogonal complement; and the dual of cone(g1,…,gm) is polyhedron {y:⟨y,gi⟩≥0}. Generally a cone’s dual is easier to describe when the cone is given by generators.
The three cones are self-dual
Proof
Orthant.y∈K∗ if and only if ⟨y,ei⟩=yi≥0 for every canonical vector (which generates the cone), i.e. y≥0.
Second-order. Let (y,s). If ∥y∥≤s, then for every (x,t) with ∥x∥≤t, the Cauchy–Schwarz inequality gives ⟨y,x⟩+st≥−∥y∥∥x∥+st≥−st+st=0 (here ∥y∥∥x∥≤st). Conversely let (y,s)∈K∗. If y=0, test (−y/∥y∥,1)∈K: −∥y∥+s≥0. If y=0, point (0,1)∈K gives s≥0=∥y∥.
Semidefinite. This is a lesson exercise: implication S+n⊆(S+n)∗ follows from tr(XY)=tr(X1/2YX1/2)≥0, and the converse by testing X=vv⊤.
∎
Second-order cone self-duality is Cauchy–Schwarz in cone form and generalizes: the dual of a norm cone, {(x,t):∥x∥≤t}, is the cone of its dual norm, {(y,s):∥y∥∗≤s}. The dual of ℓ2 is itself, hence self-duality; the dual of ℓ1 is ℓ∞, so the ℓ1 norm cone is not self-dual for n≥2 (see an exercise). Later, in duality, self-duality of these three cones will make primal and dual problems (LP, SOCP, SDP) look alike.
Operations preserving convexity
Checking the segment definition for each set is tedious. In practice recognize a convex set because it is obtained from the catalog using operations preserving convexity.
Proof
(1) If x,y are in every Cα, their segment is in each. (2) f(θx+(1−θ)y)=θf(x)+(1−θ)f(y): the image of a segment is the segment of images, hence in f(C) and, if f(x),f(y)∈D, in D. (3) The product is the intersection of two convex cylinders, and C+C′ is the image of C×C′ under linear map (x,x′)↦x+x′.
(4) Let (x,t) and (y,s) have t,s>0 and θ∈[0,1]. Then
Since θ↦μ is an increasing bijection from [0,1] onto itself, the segment’s image is the segment between x/t and y/s. This gives image and preimage: if x/t and y/s lie in a convex set, their image segment does too, hence the original segment is in the preimage.
∎
This identifies many convex sets without calculation:
A polyhedron is an intersection of half-spaces (1), and {x:Ax≤b} is also the preimage of orthant R−m under an affine map (2).
An ellipsoid is an affine image of the unit ball (2).
{x:∥Ax+b∥2≤c⊤x+d} is the second-order cone’s preimage under x↦(Ax+b,c⊤x+d) (2): a convex second-order constraint.
{x∈Rk:A0+x1A1+⋯+xkAk⪰0} is the semidefinite cone’s preimage under an affine map (2): a linear matrix inequality (LMI). Its solution set is a spectrahedron, the typical SDP constraint.
The intersection of infinitely many half-spaces⋂v{X:v⊤Xv≥0} is the semidefinite cone (1): a convexity proof already seen.
A norm cone, {(x,t):∥x∥≤t}, is (except its vertex) the unit ball {∥u∥≤1} preimage under perspective (4): ∥x/t∥≤1 with t>0 is equivalent to ∥x∥≤t. Therefore it is convex for any norm.
Projection onto a convex set
Given closed convex C and any point x, which point of C is nearest to x? If C is the ℓ∞ ball of admissible perturbations, it is the nearest feasible perturbation; if C is a simplex, the most similar probability distribution; if C is a semidefinite cone, the nearest valid covariance matrix.
If C is a subspace, this is the familiar orthogonal projection. What makes convex sets special is that the minimum exists, is unique and is characterized by a simple geometric inequality: the angle at the projection between “toward x” and “toward any other point of C” is at least 90°.
Proof
(1) Let δ=infy∈C∥x−y∥ and yk∈C satisfy ∥x−yk∥→δ. The parallelogram identity, ∥a+b∥2+∥a−b∥2=2∥a∥2+2∥b∥2 with a=x−yk and b=x−ym, gives
because the midpoint lies in C (convexity) and its distance to x is at least δ. The right-hand side tends to 0, so (yk) is Cauchy, converges to p and p∈C since C is closed; by continuity ∥x−p∥=δ. If p,p′ attain δ, the same inequality with yk=p and ym=p′ gives ∥p−p′∥2≤2δ2+2δ2−4δ2=0.
(2) (⇒) For y∈C and t∈(0,1], point p+t(y−p) lies in C, so ∥x−p−t(y−p)∥2≥∥x−p∥2, i.e. −2t⟨x−p,y−p⟩+t2∥y−p∥2≥0. Divide by t and take t→0+. (⇐) For y∈C,
∥x−y∥2=∥x−p∥2+∥p−y∥2−2⟨x−p,y−p⟩≥∥x−p∥2.
(3) With p=ΠC(x) and p′=ΠC(x′), apply (2) twice: ⟨x−p,p′−p⟩≤0 and ⟨x′−p′,p−p′⟩≤0. Add them: ⟨(x−x′)−(p−p′),p′−p⟩≤0, or ∥p−p′∥2≤⟨x−x′,p−p′⟩. The second inequality is Cauchy–Schwarz: ∥p−p′∥2≤∥x−x′∥∥p−p′∥.
∎
The geometric interpretation of (2) is key. The hyperplane through p perpendicular to x−p leaves all of C on one side (opposite x): it supports C at p. The circle centered at x with radius dist(x,C) touches C only at p.
InteractiveProjections onto convex sets
set C
segment x→ΠC(x)
supporting hyperplane at p
test point z∈C
tangent circle of radius dist(x,C)
Set C
∥x−ΠC(x)∥=dist(x,C)1.202
ΠC(x)(1.55, 0.25)
Angle x-p-z157.2°
Projection onto the ℓ1 ball subtracts the same threshold θ=0.85 from each ∣xi∣ and zeros coordinates with ∣xi∣≤θ: opposite each vertex, p falls exactly on an axis (sparsity). Zero coordinates: 0.
Drag x over five convex sets. The display draws p=ΠC(x), tangent circle of radius dist(x,C) and supporting hyperplane perpendicular to x−p. Green point z is always inside C: move z throughout C and check angle xpz is never below 90°. With the ℓ1 ball, observe projection when x lies in an axis region. Enable second point y and find points whose projections get closer (or farther): distance ratio never exceeds 1. Drag the polytope's vertices.
See what happens as C changes. In a box projection clips coordinates independently. In an ℓ2 ball it is radial scaling. In the simplex and ℓ1 ball the structure differs: some coordinates become exactly zero. This sparsity is why the ℓ1 norm selects variables, and the proximal operator of ∥⋅∥1 (proximal-methods lesson) sends small coefficients to zero.
Projection is used directly in projected gradient descent: take a descent step and project back, xk+1=ΠC(xk−η∇f(xk)) (projected gradient descent, lesson 12). It is the proximal operator of C‘s indicator function, and nonexpansiveness is what proves convergence.
Separating and supporting hyperplanes
You now have everything to prove the central result of convex geometry: a point outside a closed convex set can be separated from it by a hyperplane.
Proof
Let p=ΠC(x) and a=x−p. Since x∈/C, a=0. The variational inequality gives ⟨a,y−p⟩≤0 for every y∈C, i.e. ⟨a,y⟩≤⟨a,p⟩=⟨a,x⟩−∥a∥2. Thus supy∈C⟨a,y⟩≤⟨a,x⟩−∥a∥2<⟨a,x⟩.
∎
The proof is also an algorithm: the separating hyperplane is perpendicular to the shortest segment through its midpoint. The same holds for two sets.
Proof
The set C−D={y−z} is convex (affine image of C×D). It is closed: if yk−zk→w and C is compact, a subsequence yk→y∈C, then zk→y−w∈D (closed), so w∈C−D. Also 0∈/C−D because C∩D=∅. Apply the previous theorem to 0 and C−D (with p=ΠC−D(0)=c∗−d∗): some a=0 satisfies 0>supy,z⟨a,y−z⟩=supC⟨a,⋅⟩−infD⟨a,⋅⟩. The particular choice follows from a=0−p.
∎
Boundedness is not a technical detail: C={(x1,x2):x1>0,x2≥1/x1} and D={x2≤0} are convex, closed and disjoint, but their distance is 0 and no line strictly separates them. Nor is convexity a detail: the next figure shows what breaks without it.
InteractiveSeparating two convex sets
separating hyperplane (through midpoint)
margin: band between supports
line that fails (closest pair of sets)
Set A (blue)
Set B (orange)
A convexyes
B convexyes
Distance dist(A,B)2.46
Separating hyperplane?yes
Unit normal n(−0.94, 0.35)
Margin ∥a∗−b∗∥2.460
All points on their sideyes
A separating hyperplane exists. Its normal follows the shortest segment between the convex hulls, and the margin is 2.46.
Drag centers of A and B. For disjoint convex sets, the shortest segment (gray) determines the separating hyperplane (thick solid line through midpoint perpendicular to segment); the blue strip is margin. Make them overlap: the hyperplane disappears (if merely touching, a line still separates them without slack, margin 0). Change B to the “C” and put A in its gap: sets are disjoint and the perpendicular bisector (red dashed) cuts B. No line separates A from the “C” (its convex hull, thin line, contains A). Move A out through the opening to restore separation.
Supporting hyperplanes and cone biduality
If x is on C‘s boundary, strict separation is impossible, but an inequality can hold: the hyperplane “touches” the set.
Proof
Because x0 is on the boundary, some xk∈/C satisfy xk→x0. Let ak=(xk−ΠC(xk))/∥xk−ΠC(xk)∥, a unit vector. The preceding proof gives ⟨ak,y⟩≤⟨ak,xk⟩ for every y∈C. The unit sphere is compact, so a subsequence of ak converges to a unit a, and taking limits gives ⟨a,y⟩≤⟨a,x0⟩.
∎
An immediate corollary clarifies the relationship between a cone and its dual.
Proof
K⊆K∗∗ is immediate: if x∈K, ⟨y,x⟩≥0 for every y∈K∗. Conversely, let x∈/K. Separation gives a with ⟨a,x⟩>supy∈K⟨a,y⟩. Since K is a cone, the supremum is 0 (if any ⟨a,y⟩ were positive, multiplying y by t→∞ would make it infinite, and 0∈K keeps it ≥0). Then ⟨−a,y⟩≥0 for every y∈K, so −a∈K∗, and ⟨−a,x⟩<0 proves x∈/K∗∗.
∎
One of optimization’s most used tools follows: Farkas’ lemma. If K=cone(g1,…,gm) (a finitely generated cone, always closed), then for every b exactly one of two things holds: either b=∑iθigi with θi≥0, or some y has ⟨y,gi⟩≥0 for every i and ⟨y,b⟩<0. This is biduality K=K∗∗ in words; such “alternatives” are developed in the duality lesson (theorems of alternatives) and underpin lesson 5’s optimality conditions.
Closed-form projections
Projection is useful when cheap. Catalog sets have exact formulas, all checkable using the variational inequality.
Box.C={l≤x≤u}: the problem is coordinatewise separable and the solution is clipping, [ΠC(v)]i=min{ui,max{li,vi}}. In PyTorch it is torch.clamp.
ℓ2 ball.C={∥x−c∥≤r}: if v is inside, it is itself; otherwise ΠC(v)=c+r(v−c)/∥v−c∥, a radial rescaling.
Simplex.C=Δn (or {x≥0,1⊤x=z}): the solution has threshold form,
ΠC(v)=max(v−θ1,0),θ such that the sum is z.Proof
It suffices to show x=max(v−θ1,0) satisfies the variational inequality and lies in C. First the threshold separates exactly the ρ largest components. Let θj=(∑i≤jui−z)/j, so θ=θρ and jθj=(j−1)θj−1+uj. Rearranging, for j≥2,
uj>θj⟺juj>(j−1)θj−1+uj⟺uj>θj−1.
By definition of ρ, uρ>θρ; if ρ<n, maximality gives uρ+1≤θρ+1, equivalent by the above to uρ+1≤θρ. Since uj are sorted, u1≥⋯≥uρ>θ≥uρ+1≥⋯≥un. Thus S={i:xi>0}={i:vi>θ} has ρ elements and ∑ixi=∑i∈S(vi−θ)=∑i≤ρui−ρθ=z, so x∈C. For y∈C, split indices: on S, vi−xi=θ; outside S, xi=0 and vi−xi=vi≤θ. Then
where the inequality uses yi≥0 and vi≤θ outside S. By projection theorem part (2), x=ΠC(v).
∎
ℓ1 ball.C={∥x∥1≤r}: if ∥v∥1≤r, the solution is v. Otherwise the solution is on the boundary (an interior point would be an unconstrained minimum, namely v, outside) and retains signs of v (changing a component of x to match v cannot increase distance). Thus reduce to the size-r simplex applied to ∣v∣: ΠC(v)=sign(v)⊙Π{x≥0,1⊤x=r}(∣v∣), the soft thresholdsign(vi)max(∣vi∣−θ,0). With v=(2,2) and r=1: θ=(4−1)/2=1.5 and Π(v)=(0.5,0.5), at distance 1.52≈2.121.
Semidefinite cone. With X∈Sn and X=Qdiag(λ1,…,λn)Q⊤ (spectral theorem),
ΠS+n(X)=Qdiag(max(λ1,0),…,max(λn,0))Q⊤.
Truncate negative eigenvalues. Verification uses self-duality: let Π be the matrix above and N=Π−X=Qdiag(max(−λi,0))Q⊤⪰0. Spectral supports of Π and N are disjoint, so ⟨N,Π⟩=0. For Y⪰0,
⟨X−Π,Y−Π⟩=−⟨N,Y⟩+⟨N,Π⟩=−tr(NY)≤0,
the variational inequality. The result is the 3D figure’s semidefinite cone: in S2 it equals projection onto the second-order cone in (x,t), solved by cases: if ∥x∥≤t the point is already in the cone; if ∥x∥≤−t projection is (0,0); otherwise it is (2∥x∥+t∥x∥x,2∥x∥+t), the nearest boundary point. Project a nonsymmetric matrix by first symmetrizing it: antisymmetric part A is orthogonal to Sn, so ∥X−Y∥F2=21(X+X⊤)−YF2+∥A∥F2 for every symmetric Y: distance to every cone element increases by the same constant and the nearest is unchanged.
Implementation from scratch
Checking a definition by computer can refute it, not prove it. The following “falsifier” takes pairs of points in a set, forms a random convex combination of each pair and measures the fraction leaving the set. Apply it to the first exercise’s four sets (two convex and two nonconvex) in dimension 3: for λmax, each symmetric 2×2 matrix is the point (x,y,z) of its entries. Each set has a sampler generating its points.
[ ]A convexity falsifierBrowser
import numpy as np
rng = np.random.default_rng(0)
def falsador(pertenece, muestrea, n=20000):
"""Fracción de combinaciones convexas de pares del conjunto que NO están en el conjunto."""
a, b = muestrea(n), muestrea(n)
theta = rng.uniform(size=(n, 1))
medio = theta * a + (1 - theta) * b
return 1 - pertenece(medio).mean()
def por_rechazo(pertenece, R=2.0, d=3):
"""Muestreador: puntos uniformes de la caja [-R, R]^d que cumplen la condición."""
def muestrea(n):
salida = np.empty((0, d))
while len(salida) < n:
x = rng.uniform(-R, R, size=(4 * n, d))
salida = np.vstack([salida, x[pertenece(x)]])
return salida[:n]
return muestrea
def lambda_max(X): # X = filas (x, y, z) de la matriz [[x, y], [y, z]]
return (X[:, 0] + X[:, 2]) / 2 + np.hypot((X[:, 0] - X[:, 2]) / 2, X[:, 1])
A = np.array([[2.0, 1.0, 0.0], [1.0, 2.0, 0.0], [0.0, 0.0, 0.5]]) # definida positiva
def dispersos(n): # puntos con a lo sumo 1 componente no nula
x = np.zeros((n, 3))
x[np.arange(n), rng.integers(0, 3, n)] = rng.normal(size=n)
return x
casos = {
"||x||_0 <= 1": (lambda x: (np.abs(x) > 1e-12).sum(axis=1) <= 1, dispersos),
"x'Ax <= 1, A > 0": (lambda x: np.einsum("ni,ij,nj->n", x, A, x) <= 1, None),
"lambda_max(X) <= 1": (lambda x: lambda_max(x) <= 1, None),
"||x|| >= 1 (complemento)": (lambda x: np.linalg.norm(x, axis=1) >= 1, None),
}
for nombre, (pert, muestreo) in casos.items():
muestreo = muestreo or por_rechazo(pert)
print(f"{nombre:26s} fracción de combinaciones fuera: {falsador(pert, muestreo):.3f}")
A fraction of 0.000 proves nothing (both convex sets give 0, but we have not proved them, only failed to find a counterexample), whereas a positive fraction refutes convexity: one pair suffices. Both nonconvex sets give clearly positive values.
Now the module’s projection library. It will be used unchanged in proximal and constrained-method lessons, so every function should be exact, vectorized where possible and verifiable. Verification uses what you just proved: variational inequality ⟨v−p,z−p⟩≤0 with points z in the set, and nonexpansiveness.
[ ]Projection libraryBrowser
import numpy as np
def project_box(v, lo, hi):
return np.clip(v, lo, hi)
def project_ball2(v, r=1.0, c=0.0):
d = v - c
n = np.linalg.norm(d)
return v.copy() if n <= r else c + r * d / n
def project_simplex(v, z=1.0):
"""Proyección sobre {x >= 0, sum x = z} por ordenación, O(n log n)."""
u = np.sort(v)[::-1]
css = np.cumsum(u) - z
j = np.arange(1, len(v) + 1)
rho = np.nonzero(u - css / j > 0)[0][-1] # último índice que cumple la condición
theta = css[rho] / (rho + 1)
return np.maximum(v - theta, 0.0)
def project_l1_ball(v, r=1.0):
if np.abs(v).sum() <= r:
return v.copy()
return np.sign(v) * project_simplex(np.abs(v), r)
def project_psd(X):
X = (X + X.T) / 2 # simetriza: evita autovalores complejos
w, Q = np.linalg.eigh(X)
return (Q * np.maximum(w, 0.0)) @ Q.T
rng = np.random.default_rng(1)
n = 6
conjuntos = {
"caja [-1, 2]^n": lambda v: project_box(v, -1.0, 2.0),
"bola l2 (r=1.5)": lambda v: project_ball2(v, 1.5),
"bola l1 (r=1)": lambda v: project_l1_ball(v, 1.0),
"simplex": project_simplex,
}
print(f"{'conjunto':16s} {'max <v-p, z-p>':>16s} {'max |Pa-Pb|/|a-b|':>20s}")
for nombre, P in conjuntos.items():
peor_vi, peor_lip = -np.inf, 0.0
for _ in range(300):
v, w = rng.normal(scale=3, size=n), rng.normal(scale=3, size=n)
p, z = P(v), P(rng.normal(scale=3, size=n)) # z es un punto cualquiera del conjunto
peor_vi = max(peor_vi, (v - p) @ (z - p))
peor_lip = max(peor_lip, np.linalg.norm(p - P(w)) / np.linalg.norm(v - w))
print(f"{nombre:16s} {peor_vi:16.2e} {peor_lip:20.4f}")
# cono semidefinido: se compara con una matriz del cono tomada al azar
peor = -np.inf
for _ in range(200):
X = rng.normal(size=(4, 4))
B = rng.normal(size=(4, 4))
Z = B @ B.T # semidefinida positiva
P = project_psd(X)
peor = max(peor, np.sum((((X + X.T) / 2) - P) * (Z - P)))
print(f"{'cono semidefinido':16s} {peor:16.2e}")
v = np.array([2.0, 2.0])
print("\nproyección de (2, 2) sobre la bola l1:", project_l1_ball(v), " distancia:", round(np.linalg.norm(v - project_l1_ball(v)), 4))
print("simplex de (1.2, 0.5, -0.3):", project_simplex(np.array([1.2, 0.5, -0.3])))
The variational inequality is always ≤0 (up to rounding) and distance ratio always ≤1. Two code observations. In project_simplex, index rho is the last with uj−θj>0 and theta is the theorem’s threshold. project_psd symmetrizes first as theory warned: for a matrix not exactly symmetric, eigh reads only the lower triangle and would silently project a matrix different from the symmetrized one, and eig might return complex eigenvalues.
Second exercise: separate two point clouds. The hyperplane separating two convex hulls comes from their closest pair, a convex problem in combination weights: minimize ∑iαiai−∑jβjbj2 with α,β∈Δ. Solve two ways: a general optimizer (scipy.optimize.minimize) and alternating projections between hulls, the geometric idea.
[ ]Separating two point cloudsBrowser
import numpy as np
from scipy.optimize import minimize
from scipy.spatial import ConvexHull
rng = np.random.default_rng(3)
A = rng.normal(size=(40, 2)) * [0.7, 0.5] + [-2.0, 0.6] # nube de la clase +
B = rng.normal(size=(40, 2)) * [0.6, 0.6] + [1.8, -0.4] # nube de la clase -
# 1) problema de puntos más cercanos en los pesos (SLSQP con restricciones de símplex)
def objetivo(w):
a, b = w[:len(A)] @ A, w[len(A):] @ B
return np.sum((a - b) ** 2)
cons = [{"type": "eq", "fun": lambda w: w[:len(A)].sum() - 1},
{"type": "eq", "fun": lambda w: w[len(A):].sum() - 1}]
w0 = np.concatenate([np.full(len(A), 1 / len(A)), np.full(len(B), 1 / len(B))])
res = minimize(objetivo, w0, constraints=cons, bounds=[(0, 1)] * (len(A) + len(B)), method="SLSQP")
a1, b1 = res.x[:len(A)] @ A, res.x[len(A):] @ B
# 2) proyecciones alternas entre las dos envolventes
def proyecta_poligono(p, V):
"""Proyección exacta de un punto EXTERIOR sobre el polígono convexo de vértices V (el lado más cercano)."""
mejor, dmin = None, np.inf
for i in range(len(V)):
s, t = V[i], V[(i + 1) % len(V)]
e = t - s
c = s + np.clip((p - s) @ e / (e @ e), 0, 1) * e
d = np.linalg.norm(p - c)
if d < dmin:
mejor, dmin = c, d
return mejor
HA, HB = A[ConvexHull(A).vertices], B[ConvexHull(B).vertices]
a2, b2 = HA.mean(axis=0), HB.mean(axis=0)
for k in range(60):
a2 = proyecta_poligono(b2, HA) # el punto de A más cercano al actual de B
b2 = proyecta_poligono(a2, HB)
for nombre, a, b in [("SLSQP en los pesos", a1, b1), ("proyecciones alternas", a2, b2)]:
print(f"{nombre:22s} distancia = {np.linalg.norm(a - b):.5f}")
# hiperplano separador: normal w = a - b, por el punto medio
a, b = a2, b2
w = a - b
c = w @ (a + b) / 2
print("\nmargen (distancia entre las envolventes):", round(np.linalg.norm(w), 4))
print("A al lado positivo:", bool(np.all(A @ w >= c - 1e-9)), " B al lado negativo:", bool(np.all(B @ w <= c + 1e-9)))
Both methods give the same distance and the hyperplane separates clouds: every ai satisfies ⟨w,ai⟩≥c and every bj satisfies ⟨w,bj⟩≤c. Alternating projections require exact projection onto each hull, so use their vertices (ConvexHull); as hulls are disjoint, the projected point is always outside the polygon, the case covered by proyecta_poligono. For two disjoint closed convex sets, one bounded, alternating projections converge to a minimum-distance pair (Cheney and Goldstein, 1959). This is literally the maximum-margin SVM problem for separable data, revisited there.
The library version
In a real problem projections are solved with a convex-programming modeler, and checking against an independent implementation helps catch sign errors. First, cvxpy expresses each projection as its optimization problem and calls a conic solver:
import numpy as npimport cvxpy as cpx, v = cp.Variable(5), np.random.randn(5)cp.Problem(cp.Minimize(cp.sum_squares(x - v)), [cp.sum(x) == 1, x >= 0]).solve() # proyección sobre el símplexcp.Problem(cp.Minimize(cp.sum_squares(x - v)), [cp.norm1(x) <= 1]).solve() # sobre la bola l1
scipy suffices to check our implementation without installing anything else, although a general optimizer is much slower and less precise than the closed form.
In PyTorch, projection onto an ℓ∞ ball of radius ε around data x0 is one line, x = x0 + (x - x0).clamp(-eps, eps), and projection onto admissible pixel range [0,1] another: x = x.clamp(0, 1). This keeps the perturbation inside budget in adversarial training, a defense mechanism training on the worst perturbations within the ball.
Common errors
Exercises
QuizWhich are convex?
Which of these sets are convex?
More than one answer may be correct.
QuizThe dual of the l1 norm cone
Let K={(x,t)∈Rn×R:∥x∥1≤t}. What is its dual cone K∗?
NumericDistance to the l1 ball
Calculate Euclidean distance from (2,2) to the unit ℓ1 ball {x∈R2:∣x1∣+∣x2∣≤1}.
NumericProjection onto the simplex
Project v=(0.9,0.7,0.4,−0.2) onto probability simplex Δ4 and give the first component of Π(v).
NumericProjection onto an intersection
Let C1 be the closed unit disk in R2 and C2={x:x1≥0.8}. Calculate the second coordinate of ΠC1∩C2(0,2).
NumericDistance to the semidefinite cone
Calculate Frobenius distance from X=[1221] to S+2.
ProofThe semidefinite cone is self-dual
Prove: In Sn with inner product ⟨X,Y⟩=tr(XY), the dual of K=S+n is K∗={Y∈Sn:tr(XY)≥0∀X∈K}. Prove K∗=K.
0
Prove two inclusions: K⊆K∗ and K∗⊆K.
Step 1 of 3. For K⊆K∗, let X,Y⪰0. How do you see tr(XY)≥0?
ProofSeparate a point from a closed convex set
Prove: Let C⊆Rn be convex, closed and nonempty, and x∈/C. Some a=0 satisfies ⟨a,x⟩>supy∈C⟨a,y⟩.
0
Construct a from Euclidean projection onto C, which exists, is unique and satisfies ⟨x−p,y−p⟩≤0 for every y∈C.
Step 1 of 4. Which vector do you choose for a?
CodeProjection onto the simplex
Implement project_simplex(v, z=1.0), returning Euclidean projection of v onto {x >= 0, sum(x) = z} in O(nlogn) time: sort, calculate cumulative thresholds, choose the last index with uj>θj and clip. Do not use an optimizer. Output must satisfy the variational inequality with every simplex point.
import numpy as np
def project_simplex(v, z=1.0):
"""Proyección euclídea de v sobre {x >= 0, sum(x) = z}."""
v = np.asarray(v, dtype=float)
# tu código: ordena v de mayor a menor, calcula theta_j = (suma_acumulada_j - z) / j,
# elige el último j con u_j > theta_j, y devuelve max(v - theta, 0)
return v.copy()
Shift+Enter to run
QuizWhich operation preserves convexity?
Let C⊆Rn be convex. Which sets are always convex?
More than one answer may be correct.
Summary
Key idea
A set is convex if it contains the segment between any two points; convex cones (orthant, second-order and semidefinite, all self-dual) are the geometry of convex programming, and every closed convex set has a unique projection characterized by an obtuse angle, implying any exterior point can be separated by a hyperplane.
Affine (∑θi=1), conic (θi≥0) and convex (both) combinations sweep lines or planes, cones and convex hulls; Carathéodory says n+1 points suffice in Rn.
Half-spaces, norm balls, ellipsoids, polyhedra and the simplex are convex. Unions, complements and {∥x∥0≤k} are not.
Important convex cones are R+n, Lorentz and semidefinite; in S2 the last two coincide. All are self-dual: K∗=K. Generally K∗∗=K for closed cones.
Intersection, affine image and preimage, product, sum and perspective preserve convexity. Union does not.
Projection onto a closed convex set exists, is unique, satisfies ⟨x−p,y−p⟩≤0 and is 1-Lipschitz; closed forms exist for boxes, ℓ2 balls, simplex (sorting, O(nlogn)), ℓ1 balls (soft threshold) and the semidefinite cone (eigenvalue truncation).
That inequality is the separating hyperplane theorem: a point outside a closed convex set is separated by the hyperplane perpendicular to the shortest segment. Separation of two convex sets, cone biduality and Farkas’ lemma follow.