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

用 SymPy 验证基本函数与组合规则

PYTHONWindows、Python 3.12.14、PyTorch 2.10 CPU。符号计算使用 SymPy 1.14。rules-lab.py
rules-lab.py82 行
"""Check symbolic derivatives and gradients of two losses."""
import argparse
import json
import math
import platform

import sympy as sp


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

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

    x = sp.Symbol("x", positive=True)
    constant = sp.diff(sp.Integer(7), x)
    check("constant", "7", "0", str(constant), "differentiate with respect to x")
    powers = [2,3,-2,sp.Rational(1,2)]
    check("powers", list(map(str,powers)), ["2*x","3*x**2","-2/x**3","1/(2*sqrt(x))"],
          [str(sp.diff(x**n,x)) for n in powers], "differentiate powers at x>0")
    exponential = sp.exp(x)
    check("exponential", "exp(x)", ["exp(x)"]*3,
          [str(sp.diff(exponential,x,n)) for n in (1,2,3)], "differentiate at orders 1 through 3")
    logarithm = sp.log(x)
    check("logarithm", "ln(x), x>0", "1/x", str(sp.diff(logarithm,x)), "differentiate natural logarithm")

    expression = x*x + 3*x + 5
    check("sum_difference", [str(expression),"x**2-3*x"], ["2*x + 3","2*x - 3"],
          [str(sp.diff(expr,x)) for expr in (expression,x*x-3*x)], "differentiate sum and difference")
    product = x*x*exponential
    check("product", str(product), True,
          sp.simplify(sp.diff(product,x) - (2*x*exponential+x*x*exponential)) == 0, "check both product terms")
    check("scalar_multiple", "4*x**3", "12*x**2", str(sp.diff(4*x**3,x)), "hold the scale fixed")
    composition = (2*x+1)**3
    check("chain", str(composition), True, sp.simplify(sp.diff(composition,x)-6*(2*x+1)**2)==0,
          "compare with outer power rule times inner derivative")
    check("quotient", str(x/(x+1)), True, sp.simplify(sp.diff(x/(x+1),x)-1/(x+1)**2)==0,
          "apply quotient rule where denominator is nonzero")

    y, target = sp.symbols("prediction target", real=True)
    loss = (y-target)**2
    check("squared_loss_variables", {"prediction": 4, "target": 7}, [-6,6],
          [int(sp.diff(loss,s).subs({y:4,target:7})) for s in (y,target)],
          "hold one quantity fixed and differentiate by the other")
    w, b, value = sp.symbols("w b value", real=True)
    model = w*value+b
    check("linear_partials", "w*value+b", ["value","1"],
          [str(sp.diff(model,p)) for p in (w,b)], "differentiate with respect to weight and bias")
    sigmoid = 1/(1+sp.exp(-x))
    check("sigmoid", str(sigmoid), True, sp.simplify(sp.diff(sigmoid,x)-sigmoid*(1-sigmoid))==0,
          "compare derivative to forward output times its complement")
    check("inverse_evaluation", 2, True,
          sp.simplify(sp.diff(exponential,x).subs(x,2)*sp.diff(logarithm,x).subs(x,sp.exp(2)))==1,
          "evaluate inverse derivatives at corresponding points")

    if args.torch:
        import torch
        versions["torch"] = torch.__version__
        for name, target in (
            ("logits_index_target",torch.tensor([0])),
            ("logits_soft_target",torch.tensor([[.25,.75]],dtype=torch.float64)),
        ):
            logits = torch.tensor([[math.log(3),0]],dtype=torch.float64,requires_grad=True)
            torch.nn.functional.cross_entropy(logits,target,reduction="sum").backward()
            expected = [-.25,.25] if name == "logits_index_target" else [.5,-.5]
            actual = [float(v) for v in logits.grad[0]]
            assert all(math.isclose(a,b,rel_tol=0,abs_tol=1e-12) for a,b in zip(actual,expected,strict=True))
            check(name, {"logits": logits.detach().tolist(),"target":target.tolist(),"abs_tol":1e-12}, expected,
                  [round(v,12) for v in actual], "backpropagate an unweighted single-sample cross-entropy loss")

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


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

运行环境:Windows、Python 3.12.14、PyTorch 2.10 CPU。符号计算使用 SymPy 1.14。

入口文件:projects/ai-math-derivative-rules-lab/rules-lab.py

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

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

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

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

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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