本文介绍了SciPy的optimize.minimize中的多个变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据 SciPy文档,可以使用多个变量来最小化函数,但是并没有告诉我们如何在此类函数上进行优化.

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

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)

上面的代码确实尝试最小化函数f,但是对于我的任务,我需要针对三个变量进行最小化.

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

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

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

最小化多个变量时minimize的工作原理.

How does minimize work when minimizing with multiple variables.

推荐答案

将多个变量打包到单个数组中:

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)

收益

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

这篇关于SciPy的optimize.minimize中的多个变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-22 21:53