如何使用 Python 在 SciPy 中找到标量函数的最小值?


求解标量函数的最小值是一个优化问题。优化问题有助于提高解决方案的质量,从而以更高的性能获得更好的结果。优化问题还用于曲线拟合、根拟合等。

我们看一个示例 −

示例

import matplotlib.pyplot as plt
from scipy import optimize
import numpy as np
print("The function is defined")
def my_func(a):
   return a*2 + 20 * np.sin(a)
plt.plot(a, my_func(a))
print("Plotting the graph")
plt.show()
print(optimize.fmin_bfgs(my_func, 0))

输出

Optimization terminated successfully.
   Current function value: -23.241676
   Iterations: 4
   Function evaluations: 18
   Gradient evaluations: 6
[-1.67096375]

Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.

说明

  • 导入了所需的包。
  • 定义了一个生成数据的函数。
  • 使用 matplotlib 库将此数据绘制到图表上。
  • 接下来,通过将函数作为参数传递来使用“fmin_bgs”函数。
  • 此数据显示在控制台上。

更新时间:10-12-2020

132 次浏览

开启您的 职业生涯

完成本课程即可获得认证

开始
广告