Convex sets, convex functions, and Jensen’s inequality

Environment

Python 3.14.6, NumPy 2.5.4, SciPy 1.18.1, Matplotlib 3.11.2 (Jupyter Notebook).

This article is a rewrite of a post from around 2021, with calculations performed in the environment described above.

Overview

A convex set contains the line segment joining any two of its points. A convex function lies no higher than the chord joining two points on its graph. We derive Jensen’s inequality from these definitions and connect them to calculations with disks, annuli, the square function, and random variables with finitely many values.

This article corresponds to Chapter 2, “Convex analysis and optimality conditions,” in Theory and Practice of Mathematical Optimization.

Setup

Run the cells from top to bottom. Round numbers to three significant digits only for display.

Check versions, import libraries, and configure plots
import platform
from pathlib import Path
from pprint import pprint

import numpy as np
import scipy
from scipy import optimize
import matplotlib
import matplotlib.pyplot as plt
from matplotlib import font_manager, ticker
from IPython.display import display, Math, SVG

# 計算値は丸めず、表示するときだけ有効数字3桁にそろえる。
def sig3(value):
    return f"{float(value):#.3g}"


np.set_printoptions(formatter={"float_kind": sig3})
available = {font.name for font in font_manager.fontManager.ttflist}
font = next((name for name in ["Hiragino Sans", "Noto Sans CJK JP",
                             "IPAexGothic"] if name in available), "DejaVu Sans")
plt.rcParams.update({"font.family": [font, "DejaVu Sans"], "font.size": 11,
                     "axes.unicode_minus": False, "svg.fonttype": "path"})
OUT = Path("104_nb_files")
OUT.mkdir(exist_ok=True)


def save_svg(fig, name):
    """SVGを保存し、同じ画像をノートブックの出力欄に表示する。"""
    for ax in fig.axes:
        for axis in (ax.xaxis, ax.yaxis):
            if isinstance(axis.get_major_formatter(),
                          (ticker.ScalarFormatter, ticker.LogFormatter)):
                axis.set_major_formatter(ticker.FuncFormatter(lambda x, _: sig3(x)))
    path = OUT / f"104_{name}.svg"
    fig.savefig(path, format="svg", bbox_inches="tight", metadata={"Date": None})
    display(SVG(filename=str(path)))
    plt.close(fig)


print("実行環境: wa-src(3.14.6)")
print(f"Python: {platform.python_version()}")
pprint({"NumPy": np.__version__, "SciPy": scipy.__version__,
        "Matplotlib": matplotlib.__version__})
実行環境: wa-src(3.14.6)
Python: 3.14.6
{'Matplotlib': '3.11.2', 'NumPy': '2.5.4', 'SciPy': '1.18.1'}

1. Definition of a convex set

A set $C\subseteq\mathbb R^n$ is convex if the following holds for all $\mathbf{x},\mathbf{y}\in C$ and $0\le t\le1$.

$$ (1-t)\mathbf{x}+t\mathbf{y}\in C. $$

At $t=0$ we obtain $\mathbf{x}$, and at $t=1$ we obtain $\mathbf{y}$; values between them trace the line segment. For the unit disk $C=\{\mathbf{x}:\|\mathbf{x}\|_2\le1\}$, the triangle inequality gives:

$$ \begin{aligned} \|(1-t)\mathbf{x}+t\mathbf{y}\|_2 &\le(1-t)\|\mathbf{x}\|_2+t\|\mathbf{y}\|_2\\ &\le(1-t)+t=1. \end{aligned} $$

Thus the disk is convex. The annulus $1/2\le\|\mathbf{x}\|_2\le1$, however, is not convex: it contains $(-1,0)^{\mathsf T}$ and $(1,0)^{\mathsf T}$, but not their midpoint $\mathbf{0}$.

A half-space defined by a linear inequality is also convex. Assuming $\mathbf{a}^{\mathsf T}\mathbf{x}\le b$ and $\mathbf{a}^{\mathsf T}\mathbf{y}\le b$, we have:

$$ \mathbf{a}^{\mathsf T}((1-t)\mathbf{x}+t\mathbf{y}) \le(1-t)b+tb=b. $$

Intersections of convex sets are convex, so a set defined by several simultaneous linear inequalities is convex. A union of convex sets need not be convex.

from matplotlib.patches import Circle

fig, axes = plt.subplots(1, 2, figsize=(9, 3.80), layout="constrained")
for ax, hole, title in zip(axes, [False, True], ["円板:凸", "円環:非凸"]):
    ax.add_patch(Circle((0, 0), 1, facecolor="lightsteelblue"))
    if hole:
        ax.add_patch(Circle((0, 0), 0.500, facecolor="white"))
    ax.plot([-1, 1], [0, 0], "o-", color="crimson", label="2点を結ぶ線分")
    ax.scatter(0, 0, color="black", zorder=5)
    ax.set(xlim=(-1.20, 1.20), ylim=(-1.20, 1.20), aspect="equal",
           xlabel="$x_1$", ylabel="$x_2$", title=title)
fig.suptitle("図1:線分が集合の外へ出るか")
save_svg(fig, "01_convex_sets")

2. A convex function lies below its chords

A function $f$ on a convex set $C$ is convex if the following holds for all $\mathbf{x},\mathbf{y}\in C$:

$$ f((1-t)\mathbf{x}+t\mathbf{y}) \le(1-t)f(\mathbf{x})+tf(\mathbf{y}),\qquad 0\le t\le1 $$

The right side is the height of the chord connecting the two points on the graph. If the inequality is strict for every pair of distinct points and $0<t<1$, the function is strictly convex.

For $f(x)=x^2$, subtract the left side from the right and expand.

$$ \begin{aligned} &(1-t)x^2+ty^2-((1-t)x+ty)^2\\ &=(1-t)x^2+ty^2-(1-t)^2x^2-2t(1-t)xy-t^2y^2\\ &=t(1-t)(x^2-2xy+y^2)\\ &=t(1-t)(x-y)^2\ge0. \end{aligned} $$

The difference is positive when $x\ne y$ and $0<t<1$, so the square function is strictly convex. Convexity does not mean that a function is increasing. For example, $x^2$ decreases on the negative half-line but is convex on the whole real line.

left, right = -1, 2
grid = np.linspace(-1.50, 2.50, 250)
t = np.linspace(0, 1, 100)
segment = (1 - t) * left + t * right
chord = (1 - t) * left**2 + t * right**2
gap = chord - segment**2
assert np.allclose(gap, t * (1 - t) * (left - right) ** 2)
fig, ax = plt.subplots(figsize=(6, 3.80), layout="constrained")
ax.plot(grid, grid**2, label="$f(x)=x^2$")
ax.plot(segment, chord, "--", label="2点を結ぶ弦")
ax.fill_between(segment, segment**2, chord, alpha=0.200)
ax.scatter([left, right], [left**2, right**2])
ax.set(xlabel="$x$", ylabel="高さ", title="図2:弦と関数の差は非負")
ax.legend()
save_svg(fig, "02_chord")

$$ \displaystyle (1-t)x^2+ty^2-((1-t)x+ty)^2=t(1-t)(x-y)^2\ge0 $$

3. Extend from two points to finitely many points

For weights $p_i\ge0$ satisfying $\sum_{i=1}^m p_i=1$, Jensen’s inequality is:

$$ f\left(\sum_{i=1}^m p_i\mathbf{x}_i\right) \le\sum_{i=1}^m p_i f(\mathbf{x}_i). $$

The case $m=2$ is the definition of convexity. Assume the result holds for $m-1$ points. Equality is immediate if $p_m=1$; otherwise, take $p_m<1$ and combine the remaining points into one.

$$ \mathbf{z}=\sum_{i=1}^{m-1}\frac{p_i}{1-p_m}\mathbf{x}_i, \qquad \sum_{i=1}^m p_i\mathbf{x}_i=(1-p_m)\mathbf{z}+p_m\mathbf{x}_m. $$

Apply convexity and then the induction hypothesis:

$$ \begin{aligned} f\left(\sum_{i=1}^m p_i\mathbf{x}_i\right) &\le(1-p_m)f(\mathbf{z})+p_m f(\mathbf{x}_m)\\ &\le(1-p_m)\sum_{i=1}^{m-1}\frac{p_i}{1-p_m}f(\mathbf{x}_i) +p_m f(\mathbf{x}_m)\\ &=\sum_{i=1}^m p_i f(\mathbf{x}_i). \end{aligned} $$

This proves the finite case. The weights must be nonnegative and sum to 1; arbitrary coefficients cannot replace them.

4. Jensen’s inequality for random variables

If $X$ takes values $x_i$ with probabilities $p_i$, the finite version becomes $f(\mathbb E[X])\le\mathbb E[f(X)]$. The inequality also holds for general random variables whose values lie in the convex domain, provided the relevant expectations exist appropriately.

For a variable taking $X=-2,1,3$ with probabilities $1/4,1/2,1/4$, we obtain:

$$ \begin{aligned} \mathbb E[X]&=-2\cdot\frac14+1\cdot\frac12+3\cdot\frac14=\frac34,\\ \mathbb E[X^2]&=4\cdot\frac14+1\cdot\frac12+9\cdot\frac14=\frac{15}{4},\\ \mathbb E[X^2]-(\mathbb E[X])^2 &=\frac{60}{16}-\frac9{16}=\frac{51}{16}. \end{aligned} $$

The final difference is the variance. The square of the mean and the mean of the squares are different in this example.

values = np.array([-2, 1, 3])
probability = np.array([0.250, 0.500, 0.250])
mean = probability @ values
second = probability @ values**2
variance = probability @ (values - mean) ** 2
pprint({"平均": sig3(mean), "平均の二乗": sig3(mean**2),
        "二乗の平均": sig3(second), "Jensenの差": sig3(second - mean**2)})
assert np.isclose(variance, 51 / 16)
assert mean**2 <= second
fig, axes = plt.subplots(1, 2, figsize=(9, 3.60), layout="constrained")
axes[0].bar([str(x) for x in values], probability)
axes[0].set(xlabel="$X$の値", ylabel="確率", title="有限分布")
bars = axes[1].bar(["平均の二乗", "二乗の平均"], [mean**2, second])
axes[1].bar_label(bars, labels=[sig3(mean**2), sig3(second)], padding=3)
axes[1].set(ylim=(0, 4.50), ylabel="値", title="Jensenの不等式")
fig.suptitle("図3:順序を変えると値が変わる")
save_svg(fig, "03_jensen")
{'Jensenの差': '3.19', '二乗の平均': '3.75', '平均': '0.750', '平均の二乗': '0.562'}

$$ \displaystyle \mathbb{E}[X^2]-(\mathbb{E}[X])^2=\operatorname{Var}(X)=51/16 $$

5. Points to check in optimization

The sublevel set $\{\mathbf{x}:f(\mathbf{x})\le a\}$ of a convex function is convex: if $f\le a$ at two points, convexity bounds the function at their convex combinations by $a$ as well. In contrast, a level set $f(\mathbf{x})=a$ need not be convex. For example, $x_1^2+x_2^2=1$ is a circle without its interior.

For a strictly convex function, equality in finite Jensen holds when all points with positive weight coincide; if they include distinct points, the inequality is strict. Drawing a chord of the square function helps confirm the direction of the inequality.

Conclusion

Starting from convex sets and functions, we derived finite Jensen’s inequality and the nonnegativity of variance.

For a set, check whether it contains the relevant line segments; for a function, check whether it lies below its chords. Moving an expectation inside or outside a function requires checking convexity, weights, and existence of the expectations.

Reference: Boyd and Vandenberghe, Convex Optimization, Chapters 2–3 .