什么是优化问题What Is an Optimization Problem?
机器人几乎所有的"智能",最后都能写成同一句话:在所有可选的方案里,挑一个"最好"的,而且不许违反规矩。"方案"叫决策变量,"最好"由代价函数衡量,"规矩"是约束。把这三样东西说清楚,问题就有了形状:一片起伏的地形,而你要找最低的那个谷底。 Almost every "smart" thing a robot does boils down to one sentence: among all the options, pick the best one without breaking the rules. The options are the decision variables, "best" is measured by a cost function, and the rules are the constraints. State those three clearly and the problem takes shape: a rolling landscape in which you hunt for the lowest valley.
1为什么机器人需要它Why robots need this
想一想机器人每天要回答的问题:
- 手爪要碰到杯子,每个关节该转到多少度?(逆运动学)
- 相机装歪了一点点,外参到底是多少,才能让点云和地图对齐?(标定)
- 从 A 到 B 有无数条路径,走哪一条最短、最平滑、又不会撞到障碍物?(轨迹规划)
- 神经网络有上亿个参数,取什么值,才能让机器人在示范数据上的动作误差最小?(学习)
这四个问题长得完全不同,骨架却一样:有一组可以调的数,有一个衡量好坏的数,还有一些不能越界的规矩。一旦写成这个形式,你就可以用同一套工具去解它们,这正是本章(第 6 章)要教的全部内容。这一节先把"问题长什么样"讲清楚;怎么解,从 6.3 节开始。
Think about the questions a robot answers every day:
- The gripper must touch the cup: what angle should each joint take? (inverse kinematics)
- The camera is mounted slightly crooked: what exactly are its extrinsics, so that the point cloud lines up with the map? (calibration)
- There are infinitely many paths from A to B: which one is shortest, smoothest and avoids obstacles? (trajectory planning)
- A neural network has hundreds of millions of parameters: what values minimize the action error on the demonstrations? (learning)
These four look nothing alike, yet they share one skeleton: a set of numbers you may adjust, one number that says how good the result is, and a few rules you must not break. Write a problem in that form and the same tools solve all of them, which is the whole point of this chapter (Chapter 6). This lesson is about what such a problem looks like; how to solve it starts with Lesson 6.3.
2直觉:地形与小球Intuition: a landscape and a ball
把决策变量 \(\x\) 想成你在地图上的位置,把代价 \(f(\x)\) 想成这个位置的海拔。优化就是找海拔最低的地方。\(\x\) 有几个分量,地图就有几个维度:两个关节角是一张二维地图;上亿个神经网络参数是一张上亿维的地图,画不出来,但"起伏的地形"这个比喻仍然成立。
地形好不好走,取决于它有几个谷底。只有一个谷底的地形,把小球扔在哪里,它都滚到同一处。但机器人的代价函数常常有好几个谷:滚到哪个,取决于你从哪里出发。下面这张地形有四个谷,其中只有一个是全局最低(全局最小值),其余的只是"附近最低"(局部最小值)。
Think of the decision variable \(\x\) as your position on a map and the cost \(f(\x)\) as the altitude there. Optimization means finding the lowest ground. \(\x\) has as many dimensions as it has components: two joint angles give a 2D map; a neural network with a hundred million parameters gives a hundred-million-dimensional map that cannot be drawn, but the "rolling landscape" picture still holds.
How hard the terrain is depends on how many valleys it has. With a single valley, the ball rolls to the same place wherever you drop it. But robot cost functions often have several valleys, and which one you reach depends on where you start. The terrain below has four valleys, only one of which is the lowest overall (the global minimum); the rest are merely "lowest nearby" (local minima).
3动手玩:把球放在哪里?Play: where do you drop the ball?
点击地图(或拖动空心圆)放下小球,它会沿着最陡的下坡方向滚(这就是 6.3 节要讲的梯度下降,这里先当黑盒用)。打开"盆地图",每个颜色格子表示:从这一格出发,最终会滚进哪个谷。
Click the map (or drag the hollow circle) to drop the ball; it rolls along the steepest downhill direction (that is gradient descent, the topic of Lesson 6.3; treat it as a black box for now). Switch on the basin map: each colored cell shows which valley a ball started there ends up in.
- 让小球滚进全局最低的谷(右侧列表第 1 项)。Get the ball into the global minimum (first entry in the list).
- 让小球掉进一个局部最小值,困在那里出不来:算法并没有出错,它只是不知道别处还有更低的谷。Trap the ball in a local minimum. The algorithm did nothing wrong; it simply cannot know that a lower valley exists elsewhere.
- 打开"盆地图",把起点在两个颜色的交界处来回拖动:相隔不到 0.5 的两个起点,终点可以完全不同。Switch on the basin map and drag the start across a border between two colors: two starts less than 0.5 apart can end in completely different valleys.
注意:算法停下的地方,只是"梯度为零"的地方,它自己无法判断这是全局还是局部最低。想知道,只能换几个起点重来,比较结果。这就是机器人里"多起点重启"(multi-start)这种朴素方法的来历。
Notice that the algorithm stops wherever the gradient vanishes, and it cannot tell by itself whether that is the global or merely a local floor. The only way to find out is to restart from several places and compare. That is where the humble robotics trick of "multi-start" comes from.
优化器给你的是"从这个起点出发能走到的最近的谷底",不是"全世界最好的答案"。所以一个优化问题的难度,一半在于怎么走,一半在于地形本身有多少个谷。下一节(6.2 凸性)会讲:什么样的地形保证只有一个谷。
An optimizer hands you "the nearest valley floor reachable from where you started", not "the best answer in the world". So the difficulty of a problem lies half in how you walk and half in how many valleys the terrain has. The next lesson (6.2 Convexity) covers which terrains are guaranteed to have just one.
4三个要素:变量、代价、约束Three ingredients: variables, cost, constraints
现在把问题拆成三件事。决策变量(黄色的"你的猜测")是你能动的东西,它决定了你站在哪里。代价函数(青色的等高线)给每个位置打分,分越低越好,它的最低点(目标 \(\mathbf c\))是"如果没有任何限制,你最想去的地方"。约束(划掉的红色区域)规定哪些位置根本不能去。
有了约束,最优解常常不在代价最低的地方,而是被推到可行区域的边界上。下图里,拖动目标 \(\mathbf c\),看最优点 \(\x^\star\)(紫色)怎样被约束拦住;再拖动黄色的猜测点,亲自当一回优化器。
Now split a problem into three parts. The decision variable (the amber "your guess") is what you can move; it decides where you stand. The cost function (the cyan contours) scores every position, lower is better, and its lowest point (the target \(\mathbf c\)) is "where you would most like to be if nothing stopped you". The constraints (the red hatched region) forbid certain places altogether.
With constraints, the optimum is often not at the cheapest place but pushed to the boundary of the feasible region. In the figure, drag the target \(\mathbf c\) and watch the optimum \(\x^\star\) (purple) get stopped by the constraint; then drag the amber guess and play the optimizer yourself.
- 把目标 \(\mathbf c\) 拖到不可行区域里,观察 \(\x^\star\) 落在边界上,而不是 \(\mathbf c\) 处。Drag the target \(\mathbf c\) into the infeasible region and see \(\x^\star\) land on the boundary rather than at \(\mathbf c\).
- 目标 \(\mathbf c\) 留在不可行区域(例如默认位置)时,不看紫色圆圈,把黄色猜测点拖到可行且代价与最优值相差不到 0.03 的位置。With the target \(\mathbf c\) left in the infeasible region (e.g. where it starts), and ignoring the purple circle, drag the amber guess to a feasible place whose cost is within 0.03 of the optimum.
- 选"障碍物",把 \(\mathbf c\) 放在障碍物正中,看最优点跳到障碍物的哪一侧。再微微挪动 \(\mathbf c\),它会不会突然跳到另一侧?Choose "obstacle" and place \(\mathbf c\) at the obstacle's center; see on which side the optimum lands. Nudge \(\mathbf c\) slightly: does the optimum suddenly jump to the other side?
5例子:把圆拟合到测量点上Example: fitting a circle to measurements
标定问题是最典型的"代价 = 误差平方和"。设想一个激光雷达只扫到了一个圆柱的一段弧,你想知道圆柱的圆心和半径。决策变量是三个数 \(\boldsymbol\theta=(c_x,c_y,r)\);代价是每个测量点到圆的距离的平方和:
Calibration is the classic "cost = sum of squared errors" problem. Imagine a lidar that sees only an arc of a cylinder, and you want the cylinder's center and radius. The decision variable is three numbers \(\boldsymbol\theta=(c_x,c_y,r)\); the cost is the sum of squared distances from each measured point to the circle:
红色短线就是每个点的残差。先自己拖动圆心和半径手柄,把代价压低;再按"优化",让梯度下降(带回溯线搜索,6.5)接手。最后打开"离群点",看两个错误测量如何把答案拉歪:代价函数本身,决定了"最好"是什么意思。
The short red segments are each point's residual. First drag the center and radius handles yourself to push the cost down, then press "Optimize" and let gradient descent (with backtracking line search, Lesson 6.5) take over. Finally switch on the outliers and watch two bad measurements drag the answer sideways: the cost function itself defines what "best" means.
- 不用优化器,只靠拖动手柄,把代价压到最优值附近(差不到 0.05)。Without the optimizer, drag the handles until the cost is within 0.05 of the best possible.
- 按"优化",看代价在几十步里降到最低(梯度小于 1e-6)。Press "Optimize" and watch the cost fall to its minimum within a few dozen steps (gradient below 1e-6).
- 打开"含离群点",再优化:新的最优圆和干净数据的最优圆差得多远?Switch to "with outliers" and optimize again: how far is the new best circle from the clean one?
6再看数学The math
提示:悬停在公式中带底色的符号上,FIG 2 中对应的部分(代价、约束、猜测点、最优点)会被高亮。Tip: hover the highlighted symbols; the matching parts of FIG 2 (cost, constraints, guess, optimum) light up.
一个优化问题的标准写法是:
The standard way to write an optimization problem is:
- \(\x\in\R^n\):决策变量(也叫优化变量、参数)。机器人里可以是关节角、位姿、路径点、网络权重。
- \(f:\R^n\to\R\):代价函数(目标函数、损失)。必须是一个实数;多个目标要先加权合成一个,如 \(f=f_{\text{误差}}+\lambda f_{\text{能耗}}\)。
- \(g_i(\x)\le0\)、\(h_j(\x)=0\):不等式约束与等式约束。满足全部约束的 \(\x\) 组成可行集 \(\Omega\)。没有约束时 \(\Omega=\R^n\),称为无约束优化。
最大化只是换个符号:\(\max f\) 等价于 \(\min(-f)\),所以只需要研究最小化。
- \(\x\in\R^n\): the decision variable (also optimization variable or parameters). In robotics it can be joint angles, a pose, path points or network weights.
- \(f:\R^n\to\R\): the cost function (objective, loss). It must return a single real number; several goals have to be combined by weighting, e.g. \(f=f_{\text{error}}+\lambda f_{\text{energy}}\).
- \(g_i(\x)\le0\), \(h_j(\x)=0\): inequality and equality constraints. The \(\x\) satisfying all of them form the feasible set \(\Omega\). With no constraints, \(\Omega=\R^n\) and the problem is unconstrained.
Maximizing is only a change of sign: \(\max f\) is equivalent to \(\min(-f)\), so we only need to study minimization.
什么叫"最小值"What "minimum" means
在没有约束、\(f\) 光滑的情形,局部最小值一定满足一阶必要条件 \(\nabla f(\x^\star)=\mathbf 0\)(3.2 节:梯度为零,谷底不倾斜),以及二阶必要条件 \(\nabla^2 f(\x^\star)\succeq0\)(3.5 节:向各个方向都是"向上弯"的)。注意这只是必要条件:梯度为零的点还可能是山顶或鞍点。有了约束,最优点处梯度一般不再为零,条件变成 6.7 节的 KKT 条件。
With no constraints and a smooth \(f\), a local minimizer must satisfy the first-order necessary condition \(\nabla f(\x^\star)=\mathbf 0\) (Lesson 3.2: the gradient vanishes, the valley floor is level) and the second-order necessary condition \(\nabla^2 f(\x^\star)\succeq0\) (Lesson 3.5: the surface curves upward in every direction). These are only necessary: a point with zero gradient can also be a hilltop or a saddle. With constraints the gradient generally no longer vanishes at the optimum, and the condition becomes the KKT conditions of Lesson 6.7.
| 机器人问题Robot problem | 决策变量 \(\x\)Variable \(\x\) | 代价 \(f\)Cost \(f\) | 约束Constraints |
|---|---|---|---|
| 逆运动学Inverse kinematics | 关节角 \(\mathbf q\)joint angles \(\mathbf q\) | \(\tfrac12\|\mathrm{FK}(\mathbf q)-\mathbf t\|^2\) | 关节限位,避碰joint limits, collisions |
| 标定Calibration | 外参、内参、偏置extrinsics, intrinsics, offsets | 重投影误差平方和sum of squared reprojection errors | 旋转矩阵须正交rotations must stay orthogonal |
| 轨迹优化Trajectory optimization | 各时刻的路径点 / 控制量waypoints / controls at every step | 平滑度 + 能耗 + 到达误差smoothness + energy + goal error | 动力学、避障、力矩上限dynamics, obstacles, torque limits |
| 策略学习Policy learning | 网络权重 \(\mathbf w\)network weights \(\mathbf w\) | 动作预测误差action prediction error | 通常无约束usually none |
7机器人中的它:逆运动学的"关节空间地形"In robotics: the joint-space landscape of inverse kinematics
两连杆机械臂,连杆长 1.0 和 0.8。把手爪送到目标 \(\mathbf t\),就是最小化 \(f(\mathbf q)=\tfrac12\|\mathrm{FK}(\mathbf q)-\mathbf t\|^2\)。决策变量是两个关节角,所以代价是一张二维地形,右图就是它。横轴 \(q_1\),纵轴 \(q_2\),都在 \(-\pi\) 到 \(\pi\) 之间。
你会看到两个谷底:一个是"肘朝上",一个是"肘朝下",手爪都碰到了目标,代价同样为零。它们都是全局最小值,而且别忘了地形是周期的:\(q_1=\pi\) 的右边缘和 \(-\pi\) 的左边缘其实是同一个位置(后面的 6.10 节会把这叫做"流形")。拖动右图的黄色手柄选择起点,按"下降",看机械臂最终选了哪一种肘姿态。
A two-link arm with link lengths 1.0 and 0.8. Bringing the gripper to a target \(\mathbf t\) means minimizing \(f(\mathbf q)=\tfrac12\|\mathrm{FK}(\mathbf q)-\mathbf t\|^2\). The decision variables are the two joint angles, so the cost is a 2D landscape, the panel on the right, with \(q_1\) horizontal and \(q_2\) vertical, both between \(-\pi\) and \(\pi\).
You will see two valley floors: "elbow up" and "elbow down". The gripper touches the target in both and the cost is zero in both, so both are global minima. And remember the landscape is periodic: the right edge \(q_1=\pi\) and the left edge \(-\pi\) are the same position (Lesson 6.10 calls this a "manifold"). Drag the amber handle on the right to pick a start, press "Descend", and see which elbow posture the arm settles into.
- 固定一个目标,分别从两个不同的起点下降,让机械臂各落到肘朝上和肘朝下两种姿态。Fix a target and descend from two different starts so that the arm lands once in elbow up and once in elbow down.
- 把目标拖出臂展(虚线圆之外),看两个谷如何合并、最低点为何不再是 0。Drag the target beyond the reach (outside the dashed circle) and see how the two valleys merge and why the floor is no longer 0.
几乎所有数值 IK 求解器都是"迭代 + 从上一个姿态出发":控制循环每个周期都把上一周期的解当作起点(热启动),这样机械臂总在同一个谷里连续运动,不会突然从肘朝上翻到肘朝下。TRAC-IK 等库还会在求解失败时随机重启:这就是前面的"多起点"。7 自由度机械臂有无穷多个解(零空间),代价地形里的谷底变成一整条同样低的"谷底曲线",6.7 节的约束和 6.8 节的二次规划会处理这种冗余。
Nearly every numerical IK solver is "iterate, starting from the previous posture": at each control cycle the previous solution is the starting point (a warm start), so the arm moves continuously within one valley and never flips from elbow up to elbow down. Libraries such as TRAC-IK also restart from random seeds when a solve fails: that is the "multi-start" idea from earlier. A 7-DOF arm has infinitely many solutions (the null space), so the valley floor becomes a whole curve of equally low ground in the landscape; the constraints of Lesson 6.7 and the quadratic programs of Lesson 6.8 deal with that redundancy.
8常见误区Common pitfalls
它只保证(在好的情形下)找到一个局部最小值。除非问题是凸的(6.2 节),否则要用多起点、热启动或全局方法去弥补。拿到结果后,至少检查它是不是你想要的那个"姿态"。
At best it finds a local minimum. Unless the problem is convex (Lesson 6.2), make up for it with multi-start, warm starts or global methods. Once you have a result, at least check it is the "posture" you actually wanted.
FIG 3 的离群点就是例子:平方误差对大残差格外敏感,两个坏点就把整个圆拽歪了。代价函数是对"好"的数学翻译,翻译错了,优化得越成功,结果越离谱。强化学习里的"奖励黑客"(reward hacking)是同一件事。
The outliers in FIG 3 show it: squared error is extremely sensitive to large residuals, and two bad points drag the whole circle off. The cost is your mathematical translation of "good"; if the translation is wrong, the more successfully you optimize, the more absurd the result. "Reward hacking" in reinforcement learning is the same thing.
给越界加一个惩罚项确实常用(6.7 节会讲),但它给的是"尽量别越界",而不是"绝不越界"。关节限位、力矩上限这类硬约束,用惩罚项可能在极端情况下被突破;需要保证时,要用真正的约束优化方法。
Adding a penalty for violations is common (Lesson 6.7 covers it), but it says "try not to violate", not "never violate". For hard constraints like joint limits and torque caps, a penalty can be breached in extreme cases; when you need a guarantee, use a genuine constrained method.
关节角 \(\pi\) 和 \(-\pi\) 是同一个姿态,但在数值上相差 \(2\pi\)。若直接把角度当普通实数做差,代价会在 \(\pm\pi\) 处出现假的"悬崖"。旋转矩阵、四元数等姿态的优化更需要小心:它们不是普通向量空间,这是 6.10 节"流形上的优化"的出发点。
The joint angles \(\pi\) and \(-\pi\) are the same posture, yet differ by \(2\pi\) numerically. Subtract angles as ordinary reals and the cost grows a false "cliff" at \(\pm\pi\). Orientations as rotation matrices or quaternions need even more care, because they do not live in a plain vector space; that is the starting point of Lesson 6.10, "Optimization on manifolds".
9小练习Check yourself
10延伸阅读Further reading
- S. Boyd & L. Vandenberghe, Convex Optimization, Ch. 1 & 4.1 — 优化问题的标准形式、可行集与最优性的定义(可免费下载)The standard form, feasible sets and definitions of optimality (free to download)
- J. Nocedal & S. Wright, Numerical Optimization, 2nd ed., Ch. 1–2 — 数学形式、局部与全局解、无约束最优性条件Mathematical formulation, local versus global solutions, unconstrained optimality conditions
- K. Lynch & F. Park, Modern Robotics, Ch. 6.2 — 用牛顿类迭代求解数值逆运动学Numerical inverse kinematics by Newton-type iteration