AI Wiki中文/EN

Constrained optimization

约束优化

Model the feasible set, project correctly, and check feasibility separately from objective quality.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

A lower loss is no use if the weights are impossible

Three mixture weights must be nonnegative and sum to one. A calibration model proposes (0.8,0.3,−0.2). The proposal is not a valid mixture. Clipping negative values and renormalizing gives feasible weights, but does it give the closest feasible weights under squared distance?

No. Euclidean projection gives (0.75,0.25,0), while clipping and renormalizing gives (8/11,3/11,0), with a slightly larger squared-distance objective. “Make it feasible somehow” and “solve the stated constrained problem” are different tasks.

Constrained optimization begins by specifying variables, objective, allowed set and what counts as an acceptable result. Convex Optimization, Chapter 4 develops this modeling discipline. This chapter uses a continuous convex example with an exact projection; it does not assume every constraint set is so convenient.

Let the feasible set participate in the algorithm

The probability simplex and our projection problem are:

Δ={x∈Rd:xi≥0, ∑ixi=1},ΠΔ(v)=arg⁡min⁡x∈Δ12∥x−v∥22.\Delta=\{x\in\mathbb R^d:x_i\ge0,\ \sum_i x_i=1\},\qquad \Pi_\Delta(v)=\arg\min_{x\in\Delta}\frac12\|x-v\|_2^2.

The set is nonempty, closed and convex for positive d. The squared-distance objective is strictly convex, so the projection is unique. It preserves the coordinate order of the input; sorting is only an internal step for finding a threshold.

Introduce a multiplier θ for the sum constraint and nonnegative lower-bound multipliers. Stationarity and complementary slackness from KKT imply:

xi=max⁡{vi−θ,0},∑imax⁡{vi−θ,0}=1.x_i=\max\{v_i-\theta,0\},\qquad\sum_i\max\{v_i-\theta,0\}=1.

Positive coordinates all have the same additive shift. They are not generally rescaled by a common multiplicative factor. A sufficiently negative original coordinate becomes zero. The threshold itself may be negative when all inputs are low; nonnegativity is required of the weights, not of θ.

Find the active coordinates by sorting

Sort the input into u₁≥…≥u_d. If exactly ρ coordinates remain positive, the sum constraint gives θ=(Σᵢ≤ρuᵢ−1)/ρ. Select the largest prefix whose last value remains positive after that shift:

ρ=max⁡{j:uj−∑i=1jui−1j>0},θ=∑i=1ρui−1ρ.\rho=\max\left\{j:u_j-\frac{\sum_{i=1}^{j}u_i-1}{j}>0\right\},\qquad \theta=\frac{\sum_{i=1}^{\rho}u_i-1}{\rho}.

The first prefix always qualifies because u₁−(u₁−1)=1. As the thresholded coordinates are ordered, the active entries form a prefix. At the last valid prefix the next value, if present, is no larger than the threshold, giving a nonnegative vector with sum one. Together with the KKT construction, this proves the sorting procedure returns the unique projection.

For our input, θ=1/20. Subtract it from the first two coordinates to obtain 3/4 and 1/4, and threshold the negative third coordinate to zero. The associated lower multiplier for the third coordinate is 1/4. These values satisfy the sum, sign, stationarity and complementary conditions.

Projected gradient keeps every reported iterate feasible

For a smooth convex objective f and a closed convex set C with an available projection, use:

xk+1=ΠC(xk−t∇f(xk)).x^{k+1}=\Pi_C\bigl(x^k-t\nabla f(x^k)\bigr).

This is proximal gradient with the indicator of C as the nonsmooth term, as explained in the Parikh–Boyd author manuscript, §4.2. With an L-Lipschitz gradient, a fixed step in (0,1/L] provides the usual convex descent guarantee when the projection is exact.

Our objective f(x)=||x−a||²/2 has gradient x−a and L=1. We use t=1/2 to show several feasible iterates. A full t=1 step would directly project a and solve this special objective in one step. That shortcut does not generalize to arbitrary constrained objectives.

Compare feasibility repair with an actual optimum

Run the complete Python 3.12 standard-library program. The projection accepts 1–64 rational coordinates, including all-negative inputs. It returns weights and the sum-constraint threshold. The projected-gradient step requires a feasible starting vector of matching dimension and a rational step in (0,1]. Booleans and floating-point values are rejected.

from fractions import Fraction as F


def vector(values):
    if type(values) not in (list,tuple) or not 1 <= len(values) <= 64:
        raise ValueError('1 to 64 coordinates required')
    if any(type(v) not in (int,F) for v in values):
        raise ValueError('integer or Fraction coordinates required')
    return [F(v) for v in values]


def project_simplex(values):
    v=vector(values);ordered=sorted(v,reverse=True)
    prefix=F(0);threshold=None
    for j,u in enumerate(ordered,1):
        prefix+=u
        candidate=(prefix-1)/j
        if u > candidate:
            threshold=candidate
    assert threshold is not None
    x=[max(u-threshold,F(0)) for u in v]
    assert sum(x)==1
    return x,threshold


def loss(x,a):
    return sum((u-v)**2 for u,v in zip(x,a))/2


def projected_step(x,a,step=F(1,2)):
    x,a=vector(x),vector(a)
    if len(x)!=len(a) or min(x)<0 or sum(x)!=1:
        raise ValueError('matching dimensions and feasible starting weights required')
    if type(step) not in (int,F) or not 0 < step <= 1:
        raise ValueError('this quadratic uses a rational step in (0,1]')
    return project_simplex([u-step*(u-v) for u,v in zip(x,a)])[0]


if __name__ == '__main__':
    a=[F(4,5),F(3,10),F(-1,5)]
    optimum,threshold=project_simplex(a)
    print('projection:',[str(v) for v in optimum],'threshold='+str(threshold))
    clipped=[max(v,F(0)) for v in a]
    normalized=[v/sum(clipped) for v in clipped]
    print('normalization excess loss:',loss(normalized,a)-loss(optimum,a))
    x=[F(1,3)]*3
    for k in range(5):
        print('iteration='+str(k),'weights='+str([str(v) for v in x]),'sum='+str(sum(x)))
        if k < 4:
            new=projected_step(x,a)
            assert loss(new,a)<=loss(x,a)
            x=new
    assert projected_step(optimum,a)==optimum
    print('optimal objective:',loss(optimum,a))

Output:

projection: ['3/4', '1/4', '0'] threshold=1/20
normalization excess loss: 1/1936
iteration=0 weights=['1/3', '1/3', '1/3'] sum=1
iteration=1 weights=['7/12', '1/3', '1/12'] sum=1
iteration=2 weights=['11/16', '5/16', '0'] sum=1
iteration=3 weights=['23/32', '9/32', '0'] sum=1
iteration=4 weights=['47/64', '17/64', '0'] sum=1
optimal objective: 9/400

The normalized clipping baseline has excess objective 1/1936. It is feasible but not optimal for the Euclidean objective. The exact optimum has objective 9/400. During the four half-step iterations, sums remain exactly one and all coordinates remain nonnegative; the program checks objective decrease and separately verifies the optimum is a fixed point.

Sorting costs O(d log d), with O(d) additional storage. The gradient of this objective costs O(d), so projection dominates each iteration at large d. A different constraint set may have a much harder projection. The fraction implementation is for exact small checks; bit costs grow with the represented numbers.

Choose a method that matches the constraints

Projection is attractive when the feasible-set projection is cheap. Penalty methods add a term for violations, but a finite penalty need not enforce exact feasibility. Barrier methods keep iterates inside inequalities and require a suitable interior. Sequential quadratic programming builds local constrained quadratic models and needs its own safeguards. None of these names guarantees a global solution to an arbitrary nonlinear problem.

Discrete constraints change the question. If mixture weights must be one-hot, the continuous simplex optimum (3/4,1/4,0) is forbidden. For the current a, the best one-hot point is (1,0,0), with objective 17/200. The continuous optimum is a lower bound for this more restrictive problem, not an integer solution.

Even for continuous problems, an infeasible low-loss point is not an acceptable incumbent. Report objective, feasibility residuals and a relevant optimality measure separately. With floating-point arithmetic, tolerances must be stated; this exact demonstration does not pick universal tolerances for real systems.

Hard constraints also need to express the actual requirement. Replacing a sum-equality by an approximate penalty or renormalizing after a different optimization changes the procedure. Check whether the final output still solves the intended objective rather than merely satisfying a convenient post-processing rule.

Identify the feasible set before judging the result

  1. Project (0.8,0.3,−0.2) onto the simplex in Euclidean distance.

Answer 1: The threshold is 1/20, giving (3/4,1/4,0). The two positive coordinates receive an equal additive shift.

  1. Can the projection threshold be negative? Try input (−2,−2).

Answer 2: Yes. θ=−5/2 gives projected weights (1/2,1/2). The equality multiplier’s sign is unrestricted.

  1. Why is clipping and renormalizing not enough for this objective?

Answer 3: It gives (8/11,3/11,0), a feasible point with excess loss 1/1936. Feasibility alone does not establish minimum distance.

  1. If only one-hot weights are allowed, is the simplex optimum still an admissible solution?

Answer 4: No. The best one-hot point here is (1,0,0), with loss 17/200. The continuous relaxation’s loss 9/400 is a lower bound, leaving an optimal-value difference of 1/16.

Separate modeling, solving and checking

Boyd and Vandenberghe supply the constrained modeling and optimality framework; Parikh and Boyd connect projection with proximal algorithms. The threshold construction here is derived from the simplex’s KKT conditions and checked on exact rational data, without claiming an implementation of a general-purpose optimizer.

As a project, compare projected gradient with a squared sum-violation penalty on the same calibration target. Track constraint violation and the original objective separately as the penalty changes. Then read duality for lower bounds and numerical stability before introducing floating-point tolerances.

Make a prediction, then check

Does clipping negative weights and renormalizing always give the Euclidean simplex projection?

Choose one answer

Learning objectives

  • Derive and compute a probability-simplex projection.
  • Distinguish feasibility repair, continuous optimality and discrete constraints.

Prerequisites & connections

Explore related knowledge →

References

  1. Convex Optimization
    Stephen Boyd; Lieven Vandenberghe · 2004
  2. Proximal Algorithms — author PDF with 2013 draft cover
    Neal Parikh; Stephen Boyd · 2013

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-06 · Codex single-agent authored technical review: primary-source locations, explicit assumptions, derivations, literal or exact computational checks, and bilingual review; not independent human or second-agent peer review.

  • Single-agent authored technical review: source locations, stated domains and assumptions, derivations, literal or exact reference cases and matching bilingual programs/exercises. Not independent human or second-agent peer review.
  • Four focused tests passed on CPython 3.12.4. Exact Fraction examples are used except for the explicitly floating-point damped Newton experiment. Strict bilingual MDX/KaTeX rendering gives four equations, six anchors and four answers per language; repository publication checks are recorded separately.
  • 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.

Source locations checked:

  • Convex Optimization · Chapter 4: optimization modeling, convex feasible sets and restrictions; §5.5: multiplier certificates used in original simplex derivation.
  • Proximal Algorithms — author PDF with 2013 draft cover · §1.1 and §4.2: indicator-function proximal operator is projection, and projected gradient as a proximal-gradient special case. Author draft cover identified in shared source record.

Related topics

No matches. Try a synonym or acronym.

0 results shown

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