蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

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

PYTHONWindows、Python 3.12.14。只需标准库。finite-difference-descent.py
finite-difference-descent.py80 行
"""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()

本例需在 Windows、Python 3.12.14。只需标准库。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

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

入口文件:projects/ai-math-derivative-hill-climbing-lab/finite-difference-descent.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 finite-difference-descent.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows、Python 3.12.14。只需标准库。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:AI 数学基础

课程关联工程包(登记关联54章) · 含当前章节或实例 · mbskycom202612a33.zip

下载课程关联工程包:AI 数学基础

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a47.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习