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

验证可行极小值、凸性和多起点结果

PYTHONWindows、Python 3.12.14。numpy 2.5.4。optimization-lab.py
optimization-lab.py62 行
"""Compare feasible minima, curvature, and results from multiple starts."""
import json
from math import cos,pi,sin
import platform

import numpy as np


def main():
    cases=[]

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

    choices={"河边":8,"校园外":5,"绕行":12}
    best=min(choices,key=choices.__getitem__)
    check("route_objective",choices,["校园外",5],[best,choices[best]],"enumerate the feasible routes")
    position=0.
    for _ in range(20):
        position=float(np.clip(position-.2*2*(position-3),0.,1.))
    check("constraint_projection",{"start":0,"bounds":[0,1],"unconstrained_minimum":3},[1,4],
          [position,(position-3)**2],"project each quadratic descent step to the given interval")

    q=lambda x:x*x
    curve=lambda x:sin(x)+.1*x*x
    start,end=0.,pi
    midpoint=pi/2
    check("midpoint_convexity_test",[start,midpoint,end],[True,True],
          [q(midpoint)<(q(start)+q(end))/2,curve(midpoint)>(curve(start)+curve(end))/2],
          "compare a midpoint with the chord for both objectives")
    grad=lambda x:cos(x)+.2*x
    final=[]
    for start in (-1.,4.):
        point=start
        for _ in range(160):
            point-=.15*grad(point)
        final.append(point)
    check("nonconvex_multiple_initializations",{"starts":[-1,4],"eta":.15,"steps":160},
          [True,True,True,True],
          [abs(grad(final[0]))<1e-6,abs(grad(final[1]))<1e-6,
           all(-sin(value)+.2>0 for value in final),curve(final[0])<curve(final[1])],
          "run gradient descent from two starts and check curvature and objective values")
    cases[-1]["endpoints"]=final
    cases[-1]["objective_values"]=[curve(point) for point in final]
    convex_outcomes=[start*(1-2*.2)**30 for start in (-4,2)]
    check("convex_gradient_reaches_neighborhood",{"starts":[-4,2],"eta":.2},True,
          all(abs(x)<1e-5 for x in convex_outcomes),"compare two starts on x squared")
    x=np.array([[1.,2.],[2.,4.],[3.,6.]])
    hessian=2*x.T@x/len(x)
    check("rank_deficient_convex_mse",x.tolist(),[True,1,True],
          [bool(np.all(np.linalg.eigvalsh(hessian)>=-1e-12)),int(np.linalg.matrix_rank(x)),
           bool(np.allclose(x@[2.,1.],x@[0.,2.]))],"verify convexity with equivalent parameter solutions")
    terrain=lambda x,y:sin(x)*cos(y)+.05*(x*x+y*y)
    check("two_surface_height_samples",[[0,0],[1,0],[1,2]],[0.,1.,.891471,-.100175],
          [0.,1.,round(terrain(1,0),6),round(terrain(1,2),6)],"check one shared point and the two nonconvex probes")
    print(json.dumps(dict(version=platform.python_version(),library_versions={"numpy":np.__version__},cases=cases)))


if __name__=="__main__":
    main()
本例需在 Windows、Python 3.12.14。numpy 2.5.4。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows、Python 3.12.14。numpy 2.5.4。

入口文件:projects/ai-math-optimization-intro-lab/optimization-lab.py

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

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

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

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

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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