蓝色天空网mbsky.com · 知识 · 实践 · 创造AI 数学基础 · 本地阅读预览
教程 / AI / 智能开发 / AI 数学基础

用导数找函数最小值

实测中心差分、两侧更新、步长边界、浮点误差和历史轨迹。

本站独立整理的内容草稿。实例显示的是预期结果;浏览器、服务端运行与技术内容验收尚待完成,本页只用于阅读和图文核对。

学完这一章,你能够

用局部坡度决定更新方向

在碗形函数上,当前位置导数为正时,可以试着把 x 减小。导数为负时则增加 x。f(x) = (x−3)²+2 在 x=3 取到最小值 2。步子越大越可能越过谷底,坡陡本身无法保证损失会下降。

分开选择差分尺度和学习率

中心差分取 [f(x+h)−f(x−h)]/(2h),需要两处都在函数定义域。用它近似 f′(x) 后,更新 x ← x−η·f′(x)。h 决定测坡距离,η 决定移动幅度。h 太小会被浮点舍入吞掉。导数接近零时可停止迭代,还要根据函数性质区分极小、极大或平坦点。

核对整条轨迹与失效边界

从 10 出发,η=0.1,第一步约为 8.6。解析梯度下误差每步乘 0.8,50 步后数值差分得到 x≈3.00009991,对应 f(x)≈2.00000001。解析二次例要求 0<η<1 才收敛。η=1 时在两边等幅往返,η>1 时振幅增长。

数值梯度适合对照反向传播或小函数的导数。贝叶斯优化会用已观测结果拟合代理模型,并由采集函数选择下一次试验。目标本身可以是黑盒,采集函数的内部优化方法取决于实现。

梯度和优化中的三种任务

场景此处验证的关系
梯度下降训练多参数更新沿损失的负梯度。此处核对一维先减后收敛的条件。
数值梯度检查比较已知导数和有限差分,确保改用多尺度时能识别舍入误差。
黑盒参数搜索网格可直接评估离散候选。贝叶斯优化再用代理与采集函数安排评估,目标梯度可缺失。

数值测坡、移动并验证收敛和失效

python · 阅读源码
"""Trace scalar descent and investigate finite differences with fixed inputs."""
import json
from math import isclose
import platform


CASES = []


def record(name, operation, inputs, expected, actual):
    assert actual == expected, (name, expected, actual)
    CASES.append(dict(name=name, operation=operation, inputs=inputs,
                      expected=expected, actual=actual, passed=True))


def objective(x):
    return (x - 3) ** 2 + 2


def difference(func, x, h):
    if h <= 0 or x + h == x or x - h == x:
        raise ValueError("Choose a positive, resolvable difference scale")
    return (func(x + h) - func(x - h)) / (2 * h)


def trace(start, step, iterations, gradient):
    points = [start]
    for _ in range(iterations):
        x = points[-1]
        points.append(x - step * gradient(x))
    return points


def main():
    numeric_gradient = lambda x: difference(objective, x, 1e-5)
    analytic_gradient = lambda x: 2 * (x - 3)
    history = trace(10, .1, 50, numeric_gradient)
    record("replay_historical_trace", "sample numerical derivatives in 50 updates and audit the complete sequence",
           {"start": 10, "difference_scale": 1e-5, "rate": .1, "updates": 50},
           [[10, 8.6, 7.48, 6.584, 5.8672], 3.00009991, 2.00000001, True],
           [[round(x, 4) for x in history[:5]], round(history[-1], 8),
            round(objective(history[-1]), 8),
            all(isclose(value, 3 + 7 * .8 ** index, abs_tol=1e-8)
                for index, value in enumerate(history))])
    starts = [1, 3, 5]
    record("check_direction_on_both_sides", "start below, at, and above the minimum",
           starts, [1.4, 3., 4.6],
           [round(trace(start, .1, 1, numeric_gradient)[-1], 8) for start in starts])
    schedules = [trace(10, step, 3, analytic_gradient) for step in (.5, 1, 1.2)]
    record("step_size_changes_convergence", "compare exact step, oscillation and growth",
           [.5, 1., 1.2], [[3., 3., 3.], [-4., 10., -4.], [-6.8, 16.72, -16.208]],
           [[round(x, 5) for x in route[1:]] for route in schedules])
    errors = [abs(difference(lambda x: x ** 3, 2., h) - 12.) for h in (.1, .01)]
    record("central_difference_error", "compare central differences of a cubic to its exact derivative",
           {"x": 2, "scales": [.1, .01]}, [.01, .0001], [round(value, 9) for value in errors])
    try:
        difference(objective, 1e20, 1e-5)
    except ValueError as error:
        lost_increment = type(error).__name__
    else:
        lost_increment = "accepted"
    record("floating_point_increment_lost", "detect a difference scale too small for this float",
           [1e20, 1e-5], "ValueError", lost_increment)
    plateau_gradient = difference(lambda x: -(x - 3) ** 2, 3, .1)
    record("stationary_can_be_maximum", "check stationary point and adjacent scores for a negative quadratic",
           {"x": 3}, [0., True], [round(plateau_gradient, 6), -((4 - 3) ** 2) < 0])
    record("nondifferentiable_kink", "compare central difference with left and right slopes at an absolute-value kink",
           {"x": 0, "h": .01}, [0., -1., 1.],
           [difference(abs, 0, .01), (abs(0) - abs(-.01)) / .01, (abs(.01) - abs(0)) / .01])
    discrete = {"窄": 1.4, "中": .7, "宽": 1.2}
    best = min(discrete, key=discrete.get)
    record("discrete_choices_need_no_derivative", "select the best observed value for a categorical candidate",
           discrete, ["中", .7], [best, discrete[best]])
    print(json.dumps(dict(version=platform.python_version(), library_versions={}, cases=CASES), ensure_ascii=False))


if __name__ == "__main__":
    main()

预期结果 · 待实际运行核验
  • η=0.1 从 10 移动第一步到 8.6,50 步到约 3.00009991。过大的学习率使二次损失上升。
数值测坡、移动并验证收敛和失效

所需环境:Windows、Python 3.12.14。只需标准库。

当前源码 SHA256:a32e9adb4237b9816b2137f633738f64ec1a8c71a9620cbdc5c7c011d5c3e121

下载本站示例源码

复跑实验

解压后按 README 运行自编程序。

下载用导数找函数最小值实验

所需环境:Windows、Python 3.12.14。只需标准库。

ZIP SHA256:01484e4637f697943d7a297b7a3f57db54d2e973abbf2e2619e7a0179935b2ac

常见错误与边界

  • 步长选择取决于函数曲率。
  • 差分近似需对照数值误差、定义域及不可导点。

练习与解答

把学习率改成 0.5,在精确导数下会怎样?

展开参考解答

误差因子 1−2η 为零,二次示例的一次更新落在 3。

规范与官方依据