SciPy 的 optimize.minimize 中的多个变量 [英] Multiple variables in SciPy's optimize.minimize

查看:27
本文介绍了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() 只需要 2 个参数(给定 1 个)).

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 中的多个变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆