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

验证偏导、混合顺序与冻结参数

PYTHONWindows、Python 3.12.14、PyTorch 2.10 CPU。符号计算使用 SymPy 1.14。partial-lab.py
partial-lab.py73 行
"""Check coordinate slices, mixed derivatives, and frozen parameters."""
import argparse
from fractions import Fraction
import json
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 actual == expected, (name, expected, actual)
        cases.append(dict(name=name,input=inputs,expected=expected,actual=actual,operation=operation,passed=True))

    x, y = sp.symbols("x y", real=True)
    f = x*x + x*y + y*y
    check("quadratic_partials", str(f), ["2*x + y","x + 2*y"], [str(sp.diff(f,p)) for p in (x,y)],
          "derive the two coordinate partials")
    check("pure_and_mixed_orders", str(f), [2,2,1,1],
          [int(sp.diff(f,*variables)) for variables in ((x,x),(y,y),(x,y),(y,x))],
          "differentiate twice in each ordered pair")
    nonsymmetric = x*y*y
    check("ordered_steps_are_visible", str(nonsymmetric), ["y**2","2*x*y","2*y","2*y"],
          [str(sp.diff(nonsymmetric,*variables)) for variables in ((x,),(y,),(x,y),(y,x))],
          "observe the intermediate result for each differentiation order")

    h = Fraction(1,100)
    def value(a,b):
        return a*a+a*b+b*b
    first = (value(2+h,1)-value(2,1))/h
    second = (value(2,1+h)-value(2,1))/h
    both = (value(2+h,1+h)-value(2,1))/h
    check("coordinate_slice_quotients", {"point":[2,1],"h":str(h)}, ["501/100","401/100","903/100"],
          list(map(str,(first,second,both))), "change x alone, y alone, then both")
    w, b, sample, target = sp.symbols("w b sample target", real=True)
    loss = (w*sample+b-target)**2
    at = {w:2,b:1,sample:3,target:4}
    check("linear_square_gradient", {"w":2,"b":1,"sample":3,"target":4}, [18,6],
          [int(sp.diff(loss,p).subs(at)) for p in (w,b)], "differentiate loss by weight and bias independently")
    check("addition_and_product_local", ["x+y","x*y"], ["1","y"],
          [str(sp.diff(node,x)) for node in (x+y,x*y)], "compute the local derivative for a graph node")
    shared = (x*x+x)**2
    check("shared_node_gradients_add", {"x":2,"graph":"(x*x + x)**2"}, 60, int(sp.diff(shared,x).subs(x,2)),
          "add contributions from direct and squared paths")

    if args.torch:
        import torch
        versions["torch"] = torch.__version__
        frozen = torch.nn.Parameter(torch.tensor(2.,dtype=torch.float64),requires_grad=False)
        bias = torch.nn.Parameter(torch.tensor(1.,dtype=torch.float64))
        input_value = torch.tensor(3.,dtype=torch.float64,requires_grad=True)
        optimizer = torch.optim.SGD([bias],lr=.125)
        loss = (frozen*input_value+bias-4)**2
        loss.backward()
        check("freeze_keeps_input_gradient", {"w":2,"b":1,"x":3,"target":4}, [None,6,12],
              [frozen.grad,float(bias.grad),float(input_value.grad)],
              "backpropagate with the weight frozen but the input requiring gradient")
        optimizer.step()
        check("freeze_optimizer_step", {"learning_rate":.125}, [2,.25],
              [float(frozen.detach()),float(bias.detach())], "step only the included trainable bias")

    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-partial-derivative-lab/partial-lab.py

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

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

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

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

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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