最小化函数scipy

时间:2016-12-29 03:34:15

标签: python scipy

我得到了一个函数(类似错误),我必须最小化并获得新参数alpha和r:

#!/usr/bin/env python
import numpy as np
from scipy.integrate import quad
import scipy.optimize as opt

def integrand(t, alpha, r):
    return np.exp(-alpha*(t-r))**2

def my_function(alpha, r):
    return quad(integrand, 0, 5.0, args=(alpha, r))[0]

alpha = np.arange(1.0, 2.0, 0.1)
r = np.arange(1.0, 2.0, 0.1)
x0 = np.array([1.3, 0.7, 0.8, 1.9, 1.2])
res = opt.minimize(my_function, x0, args=(alpha, r), method='CG', tol=1.e-2, options={'gtol': 0.01, 'maxiter': 5})

我的第一个问题是我是否采用了正确的最小化方法。如果是这样,任何人都可以详细说明我必须传递给最小化方法的参数吗?

目前返回错误消息:

File "./test.py", line 15, in <module>
    res = opt.minimize(my_function, x0, args=(alpha, r), method='CG', tol=1.e-2, options={'gtol': 0.01, 'maxiter': 5})
  File "/usr/local/lib/python2.7/site-packages/scipy/optimize/_minimize.py", line 439, in minimize
    return _minimize_cg(fun, x0, args, jac, callback, **options)
  File "/usr/local/lib/python2.7/site-packages/scipy/optimize/optimize.py", line 1159, in _minimize_cg
    gfk = myfprime(x0)
  File "/usr/local/lib/python2.7/site-packages/scipy/optimize/optimize.py", line 289, in function_wrapper
    return function(*(wrapper_args + args))
  File "/usr/local/lib/python2.7/site-packages/scipy/optimize/optimize.py", line 622, in approx_fprime
    return _approx_fprime_helper(xk, f, epsilon, args=args)
  File "/usr/local/lib/python2.7/site-packages/scipy/optimize/optimize.py", line 556, in _approx_fprime_helper
    f0 = f(*((xk,) + args))
  File "/usr/local/lib/python2.7/site-packages/scipy/optimize/optimize.py", line 289, in function_wrapper
    return function(*(wrapper_args + args))
TypeError: my_function() takes exactly 2 arguments (3 given)

1 个答案:

答案 0 :(得分:0)

如果你想最小化r和alpha,那么你必须传递一个起始点,即初始值。

我的解决方案:

dictionary={}
while ans!="end":
  dictionary[function()[0]]=function()[1]
  ans=input("Enter?")

输出:

import numpy as np
from scipy.integrate import quad
import scipy.optimize as opt


def integrand(t, alpha, r):
    return np.exp(-alpha*(t-r))**2


def my_function(parameters):
    alpha = parameters[0]
    r = parameters[1]
    return quad(integrand, 0, 5.0, args=(alpha, r))[0]

alpha_0 = 1
r_0 = 1

res = opt.minimize(my_function, np.asarray([alpha_0, r_0]), method='CG', tol=1.e-2, options={'gtol': 0.01, 'maxiter': 5})
print(res)