小白教程
所有教程
关于
Search
172.69.58.253
172.69.58.253
参数设置
贡献
退出
操作
编辑
移动
保护
信息
历史
删除
查看“SciPy 优化器”的源代码
本页内容
上一节:
SciPy_常量模块
下一节:
SciPy_稀疏矩阵
因为以下原因,您没有权限编辑本页:
您请求的操作仅限属于该用户组的用户执行:
用户
您可以查看和复制此页面的源代码。
{{DISPLAYTITLE:SciPy 优化器}}[[Category:SciPy 教程|5]] = SciPy 优化器 = SciPy 的 optimize 模块提供了常用的最优化算法函数实现,我们可以直接调用这些函数完成我们的优化问题,比如查找函数的最小值或方程的根等。 NumPy 能够找到多项式和线性方程的根,但它无法找到非线性方程的根,如下所示: <sample title="" desc="" lang="python" hererun="1"> x + cos(x) </sample> 因此我们可以使用 SciPy 的 optimze.root 函数,这个函数需要两个参数: * fun - 表示方程的函数。 * x0 - 根的初始猜测。 该函数返回一个对象,其中包含有关解决方案的信息。 实际解决方案在返回对象的属性 x ,查看如下实例: 查找 x + cos(x) 方程的根: <sample title="" desc="" lang="python" hererun="1"> from scipy.optimize import root from math import cos def eqn(x): return x + cos(x) myroot = root(eqn, 0) print(myroot.x) # 查看更多信息 #print(myroot) </sample> 执行以上代码,输出结果如下: <sample title="" desc="" lang="python" hererun="1"> -0.73908513] </sample> 看更多信息: <sample title="" desc="" lang="python" hererun="1"> from scipy.optimize import root from math import cos def eqn(x): return x + cos(x) myroot = root(eqn, 0) print(myroot) </sample> 执行以上代码,输出结果如下: <sample title="" desc="" lang="python" hererun="1"> fjac: array([[-1.]]) fun: array([0.]) message: 'The solution converged.' nfev: 9 qtf: array([-2.66786593e-13]) r: array([-1.67361202]) status: 1 success: True x: array([-0.73908513]) </sample> === 最小化函数 === 函数表示一条曲线,曲线有高点和低点。 高点称为最大值。 低点称为最小值。 整条曲线中的最高点称为全局最大值,其余部分称为局部最大值。 整条曲线的最低点称为全局最小值,其余的称为局部最小值。 可以使用 scipy.optimize.minimize() 函数来最小化函数。 minimize() 函接受以下几个参数: <p>fun - 要优化的函数</p> <p>x0 - 初始猜测值</p> <p>method - 要使用的方法名称,值可以是:'CG','BFGS','Newton-CG','L-BFGS-B','TNC','COBYLA',,'SLSQP'。</p> <p>callback - 每次优化迭代后调用的函数。</p> <p>options - 定义其他参数的字典:</p> <sample title="" desc="" lang="python" hererun="1"> { "disp": boolean - print detailed description "gtol": number - the tolerance of the error } </sample> x^2 + x + 2 使用 BFGS 的最小化函数: <sample title="" desc="" lang="python" hererun="1"> from scipy.optimize import minimize def eqn(x): return x**2 + x + 2 mymin = minimize(eqn, 0, method='BFGS') print(mymin) </sample> 执行以上代码,输出结果如下: <sample title="" desc="" lang="python" hererun="1"> fun: 1.75 hess_inv: array([[0.50000001]]) jac: array([0.]) message: 'Optimization terminated successfully.' nfev: 8 nit: 2 njev: 4 status: 0 success: True x: array([-0.50000001]) </sample>
返回至“
SciPy 优化器
”。
上一节:
SciPy_常量模块
下一节:
SciPy_稀疏矩阵