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

用四组有理数检查左右极限

PYTHONWindows、Python 3.12、Chromium,自动微分使用 PyTorch 2.10 CPU。limit-numerics.py
limit-numerics.py104 行
"""Compare nearby samples, function values, and local derivatives."""
import argparse
from fractions import Fraction
import json
from math import isclose
import platform


def hole(x):
    return (x*x - 1) / (x - 1)


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--torch", action="store_true")
    args = parser.parse_args()
    cases = []
    versions = {}

    def observe(name, inputs, expected, actual, operation):
        assert actual == expected, (name, expected, actual)
        cases.append(dict(name=name, input=inputs, operation=operation, expected=expected,
                          actual=actual, passed=True))

    radii = [Fraction(1, 10**n) for n in range(1, 5)]
    pairs = [[hole(1-d), hole(1+d)] for d in radii]
    observe("two_sided_samples", [str(d) for d in radii],
            [["19/10","21/10"], ["199/100","201/100"],
             ["1999/1000","2001/1000"], ["19999/10000","20001/10000"]],
            [[str(y) for y in p] for p in pairs], "evaluate at 1-d and 1+d using exact rational arithmetic")

    try:
        hole(Fraction(1))
    except ZeroDivisionError:
        at_one = "undefined"
    else:
        at_one = "defined"
    observe("hole_undefined", "1", "undefined", at_one, "evaluate original quotient")

    extended = lambda x: x + 1
    reassigned = lambda x: 3 if x == 1 else hole(x)
    observe("different_point_values_same_neighborhood", ["0.99","1","1.01"],
            [["199/100", "2", "201/100"], ["199/100","3","201/100"]],
            [[str(rule(x)) for x in (1-radii[1], Fraction(1), 1+radii[1])]
             for rule in (extended, reassigned)], "evaluate two extensions at neighbors and at the center")

    jump = lambda x: 0 if x < 1 else 1
    observe("jump_left_and_right", [str(d) for d in radii], [[0, 1]]*4,
            [[jump(1-d), jump(1+d)] for d in radii], "sample a jump on both sides")

    def position(t):
        return t*t

    h_values = [-radii[0], -radii[2], radii[2], radii[0]]
    rates = [(position(3+h)-position(3))/h for h in h_values]
    observe("velocity_at_three", [str(h) for h in h_values],
            ["59/10","5999/1000","6001/1000","61/10"], [str(v) for v in rates],
            "compute average velocities around t=3 for position t²")

    x = Fraction(3)
    derivative = 2*x
    steps = [Fraction(1,4), Fraction(1), Fraction(5,4)]
    losses = [(x-alpha*derivative)**2 for alpha in steps]
    observe("step_size_and_loss", [str(a) for a in steps], ["9/4","9","81/4"],
            [str(loss) for loss in losses], "apply the same exact gradient with three learning rates")

    if args.torch:
        import torch
        import torch.nn.functional as functional

        versions["torch"] = torch.__version__

        def grad_at(operation, x):
            value = torch.tensor(x, dtype=torch.float64, device="cpu", requires_grad=True)
            operation(value).backward()
            return float(value.grad)

        activations = [torch.relu, lambda x: functional.leaky_relu(x, 0.1)]
        observe("relu_family_backward", [-1,0,1], [[0,0,1],[0.1,0.1,1]],
                [[grad_at(op, x) for x in (-1,0,1)] for op in activations],
                "run PyTorch autograd for ReLU and LeakyReLU")
        d = 1e-6
        leaky = lambda x: max(x, 0.1*x)
        observe("leaky_relu_one_sided_slopes", d, [0.1,1.0], [leaky(-d)/(-d), leaky(d)/d],
                "compute one-sided quotients at zero")
        gelu = lambda x: functional.gelu(x, approximate="none")
        observe("gelu_derivative_at_zero", 0, True, isclose(grad_at(gelu, 0), .5, abs_tol=1e-12),
                "run autograd on exact GELU at zero")
        hinge = lambda x: torch.relu(1-x)
        observe("hinge_margins", [0,1,2], [-1.0,0.0,0.0], [grad_at(hinge, x) for x in (0,1,2)],
                "differentiate the ReLU realization of hinge loss by margin")
        observe("mse_gradient", [3,1], 4.0, grad_at(lambda x: (x-1)**2, 3),
                "differentiate a one-sample squared loss")
        logits = torch.tensor([[0.0,0.0]], dtype=torch.float64, device="cpu", requires_grad=True)
        functional.cross_entropy(logits, torch.tensor([1], dtype=torch.long, device="cpu")).backward()
        observe("cross_entropy_logit_gradient", [[0,0],1], [[.5,-.5]], logits.grad.tolist(),
                "differentiate cross-entropy with respect to finite logits")

    print(json.dumps(dict(version=platform.python_version(), library_versions=versions, cases=cases)))


if __name__ == "__main__":
    main()
本例需在 Windows、Python 3.12、Chromium,自动微分使用 PyTorch 2.10 CPU。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows、Python 3.12、Chromium,自动微分使用 PyTorch 2.10 CPU。

入口文件:projects/ai-math-function-limit-lab/limit-numerics.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 limit-numerics.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows、Python 3.12、Chromium,自动微分使用 PyTorch 2.10 CPU。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

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

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

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

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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