Python SciPy 的 optimize.minimize 中的多个变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13670333/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 09:21:09  来源:igfitidea点击:

Multiple variables in SciPy's optimize.minimize

pythonmathscipy

提问by Henrik Hansen

According to the SciPy documentationit is possible to minimize functions with multiple variables, yet it doesn't tell how to optimize on such functions.

根据SciPy 文档,可以最小化具有多个变量的函数,但它没有说明如何优化这些函数。

from scipy.optimize import minimize
from math import *

def f(c):
  return sqrt((sin(pi/2) + sin(0) + sin(c) - 2)**2 + (cos(pi/2) + cos(0) + cos(c) - 1)**2)

print minimize(f, 3.14/2 + 3.14/7)

The above code does try to minimize the function f, but for my task I need to minimize with respect to three variables.

上面的代码确实尝试最小化 function f,但是对于我的任务,我需要最小化三个变量。

Simply introducing a second argument and adjusting minimize accordingly yields an error (TypeError: f() takes exactly 2 arguments (1 given)).

简单地引入第二个参数并相应地调整最小化会产生错误(TypeError: f() takes exactly 2 arguments (1 given))。

How does minimizework when minimizing with multiple variables.

minimize使用多个变量进行最小化时如何工作。

采纳答案by unutbu

Pack the multiple variables into a single array:

将多个变量打包成一个数组:

import scipy.optimize as optimize

def f(params):
    # print(params)  # <-- you'll see that params is a NumPy array
    a, b, c = params # <-- for readability you may wish to assign names to the component variables
    return a**2 + b**2 + c**2

initial_guess = [1, 1, 1]
result = optimize.minimize(f, initial_guess)
if result.success:
    fitted_params = result.x
    print(fitted_params)
else:
    raise ValueError(result.message)

yields

产量

[ -1.66705302e-08  -1.66705302e-08  -1.66705302e-08]