>>> from env_helper import info; info()
页面更新时间: 2023-06-24 12:31:03
运行环境:
    Linux发行版本: Debian GNU/Linux 12 (bookworm)
    操作系统内核: Linux-6.1.0-9-amd64-x86_64-with-glibc2.36
    Python版本: 3.11.2

2.2. 函数最小值

optimize库提供了几个求函数最小值的算法:fmin, fmin_powell, fmin_cg, fmin_bfgs。下面的程序 通过求解卷积的逆运算演示fmin的功能。 对于一个离散的线性时不变系统h, 如果它的输入是x,那么其输出y可以用x和h的卷积表示: y = x ∗ h 现在的问题是如果已知系统的输入x和输出y,如何计算系统的传递函数h;或者如果已知系统的传递函 数h和系统的输出y,如何计算系统的输入x。这种运算被称为反卷积运算,是十分困难的,特别是在实 际的运用中,测量系统的输出总是存在误差的。 下面用fmin计算反卷积,这种方法只能用在很小规模的数列之上,因此没有很大的实用价值,不过用 来评价fmin函数的性能还是不错的。

>>> import scipy.optimize as opt
>>> import numpy as np

定义函数: x (*) h = y, (*)表示卷积, yn为在y的基础上添加一些干扰噪声的结果, x0为求解x的初始值:

>>> def test_fmin_convolve(fminfunc, x, h, y, yn, x0):
>>>     """
>>>
>>>     """
>>>     def convolve_func(h):
>>>         """
>>>         计算 yn - x (*) h 的power
>>>         fmin将通过计算使得此power最小
>>>         """
>>>         return np.sum((yn - np.convolve(x, h))**2)
>>>
>>>     # 调用fmin函数,以x0为初始值
>>>     h0 = fminfunc(convolve_func, x0)
>>>
>>>     print(fminfunc.__name__)
>>>     print("---------------------")
>>>     # 输出 x (*) h0 和 y 之间的相对误差
>>>     print("error of y:", np.sum((np.convolve(x, h0)-y)**2)/np.sum(y**2))
>>>     # 输出 h0 和 h 之间的相对误差
>>>     print("error of h:", np.sum((h0-h)**2)/np.sum(h**2))
>>>     print

随机产生x, h, y, yn, x0等数列,调用各种fmin函数求解b。 m为x的长度, n为h的长度, nscale为干扰的强度。

>>> def test_n(m, n, nscale):
>>>     """
>>>
>>>     """
>>>     x = np.random.rand(m)
>>>     h = np.random.rand(n)
>>>     y = np.convolve(x, h)
>>>     yn = y + np.random.rand(len(y)) * nscale
>>>     x0 = np.random.rand(n)
>>>
>>>     test_fmin_convolve(opt.fmin, x, h, y, yn, x0)
>>>     test_fmin_convolve(opt.fmin_powell, x, h, y, yn, x0)
>>>     test_fmin_convolve(opt.fmin_cg, x, h, y, yn, x0)
>>>     test_fmin_convolve(opt.fmin_bfgs, x, h, y, yn, x0)

然后运行程序,检查最后的结果:

>>> test_n(200, 20, 0.1)
/tmp/ipykernel_90398/2448148131.py:13: RuntimeWarning: Maximum number of function evaluations has been exceeded.
  h0 = fminfunc(convolve_func, x0)
fmin
---------------------
error of y: 0.005994275135018886
error of h: 0.2794636011128184
Optimization terminated successfully.
         Current function value: 0.195992
         Iterations: 48
         Function evaluations: 7978
fmin_powell
---------------------
error of y: 9.017479367932174e-05
error of h: 0.0002650539372040704
Optimization terminated successfully.
         Current function value: 0.195957
         Iterations: 24
         Function evaluations: 1008
         Gradient evaluations: 48
fmin_cg
---------------------
error of y: 8.996490734810005e-05
error of h: 0.0002585586139662521
Optimization terminated successfully.
         Current function value: 0.195957
         Iterations: 29
         Function evaluations: 798
         Gradient evaluations: 38
fmin_bfgs
---------------------
error of y: 8.996480826347273e-05
error of h: 0.0002585542642647939