多变量函数的最小化
Minimisation of a multivariable function
import math
import numpy
import scipy
def chisq1a(a,b,NN):
return (NN/(a**2)*b**2*(1+3/(a**2))*(1+(math.tan((math.pi)/2*(a+b*math.log(b/0.45))))**2))
x0 = numpy.array([0,0,0])
from scipy.optimize import minimize
result = scipy.optimize.minimize(chisq1a, x0)
我正在尝试使用上面的代码最小化 Python 3 中的多变量函数,但我得到一个错误
TypeError: chisq1a() missing 2 required positional arguments: 'b' and 'NN'
这是什么意思?在随后编写一个函数的上下文中出现了这个错误,最初用 n 个参数定义,作为一个带有例如 n-1 个参数的函数,所以存在不匹配,但这似乎不是这里的问题。可能解决方案很简单,但我几天前才开始使用 python,所以还在学习 :) 谢谢!
我不确定为什么 minimize
函数是这样设计的,但看起来您必须在要最小化的函数中解压参数。我无法以任何其他方式提供多个参数(例如,作为元组)。我从下面的例子 in the docs 中得到了提示,他们使用了:
fun = lambda x: (x[0] - 1)**2 + (x[1] - 2.5)**2
作为多个参数的示例,即单个参数 x
然后它们在函数内部索引。他们使用 lambda
的事实并没有什么不同。
我不得不更新你从 [0, 0, 0]
开始的猜测以避免出现 ZeroDivisionError
。以下似乎有效:
import math
import numpy as np
import scipy
def chisq1a(x):
a, b, NN = x
return (NN/(a**2)*b**2*(1+3/(a**2))*(1+(math.tan((math.pi)/2*(a+b*math.log(b/0.45))))**2))
x0 = np.array([1, 1, 1])
result = scipy.optimize.minimize(chisq1a, x0)
至于访问结果,文档链接较早状态:
res : OptimizeResult
The optimization result represented as a OptimizeResult object.
Important attributes are: x the solution array, success a Boolean flag
indicating if the optimizer exited successfully and message which
describes the cause of the termination. See OptimizeResult for a
description of other attributes.
因此,x
是您可以再次解压的结果数组。
result = scipy.optimize.minimize(chisq1a, x0)
a, b, NN = result.x
import math
import numpy
import scipy
def chisq1a(a,b,NN):
return (NN/(a**2)*b**2*(1+3/(a**2))*(1+(math.tan((math.pi)/2*(a+b*math.log(b/0.45))))**2))
x0 = numpy.array([0,0,0])
from scipy.optimize import minimize
result = scipy.optimize.minimize(chisq1a, x0)
我正在尝试使用上面的代码最小化 Python 3 中的多变量函数,但我得到一个错误
TypeError: chisq1a() missing 2 required positional arguments: 'b' and 'NN'
这是什么意思?在随后编写一个函数的上下文中出现了这个错误,最初用 n 个参数定义,作为一个带有例如 n-1 个参数的函数,所以存在不匹配,但这似乎不是这里的问题。可能解决方案很简单,但我几天前才开始使用 python,所以还在学习 :) 谢谢!
我不确定为什么 minimize
函数是这样设计的,但看起来您必须在要最小化的函数中解压参数。我无法以任何其他方式提供多个参数(例如,作为元组)。我从下面的例子 in the docs 中得到了提示,他们使用了:
fun = lambda x: (x[0] - 1)**2 + (x[1] - 2.5)**2
作为多个参数的示例,即单个参数 x
然后它们在函数内部索引。他们使用 lambda
的事实并没有什么不同。
我不得不更新你从 [0, 0, 0]
开始的猜测以避免出现 ZeroDivisionError
。以下似乎有效:
import math
import numpy as np
import scipy
def chisq1a(x):
a, b, NN = x
return (NN/(a**2)*b**2*(1+3/(a**2))*(1+(math.tan((math.pi)/2*(a+b*math.log(b/0.45))))**2))
x0 = np.array([1, 1, 1])
result = scipy.optimize.minimize(chisq1a, x0)
至于访问结果,文档链接较早状态:
res : OptimizeResult
The optimization result represented as a OptimizeResult object. Important attributes are: x the solution array, success a Boolean flag indicating if the optimizer exited successfully and message which describes the cause of the termination. See OptimizeResult for a description of other attributes.
因此,x
是您可以再次解压的结果数组。
result = scipy.optimize.minimize(chisq1a, x0)
a, b, NN = result.x