在Python优化中向目标函数传递参数。

2024-10-01 04:55:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我用optimize.root来寻找方程组的数值解。我需要将每个条件表示为一个单独的函数,还需要将参数传递给某些条件。但是,optimize.root似乎只有在目标函数本身内而不是在目标函数调用的单独函数中进行计算时,才能正确传递参数。在

以下代码复制了该问题:

# Conditions to be solved
def fSSBj(inp):
    return (0.5*inp[1])/(1+inp[1])-0.9*inp[0]
def fSSBJ(inp):
    return inp[0]-inp[2]*inp[1]

# Objective function with conditions inserted directly
def objFunc1(inp,pM):
    out = empty(2)
    out[0] = (0.5*inp[1])/(1+inp[1])-0.9*inp[0]
    out[1] = inp[0]-pM*inp[1]
    return out

# Objective function that calls the functions with the conditions
def objFunc2(inp,pM):
    out = empty(2)
    out[0] = fSSBj(inp+[pM])
    out[1] = fSSBJ(inp+[pM])
    return out

请注意,两个目标函数使用相同的输入;它们也给出相同的输出:

^{pr2}$

这两个命令都会返回

[-0.65  0.8 ]

但是,问题是,以下两个命令给出的结果截然不同:

Out1 = optimize.root(objFunc1, [1.0,1.0], args = (0.2), method='hybr')
Out2 = optimize.root(objFunc2, [1.0,1.0], args = (0.2), method='hybr')

第一个很好;第二个给出一个错误消息(Index is out of bounds)。optimize.root如何将参数传递给函数会有问题吗?在

这对我来说是个问题,因为(1)我有不同的条件集要解决;(2)我需要用一阶导数来构造雅可比函数。基于这两个原因,我使用SymPy的lambdify函数来生成函数及其导数,并将它们包含在目标函数中。在


Tags: 函数目标returndefwithfunctionrootout
2条回答

我假设numpy将您的输入列表转换为ndarray。在

不幸的是

>> [1,1] + [0.2]
[1, 1, 0.2]

>> np.array([1,1]) + [0.2]
array([ 1.2,  1.2])

因此,您将得到一个IndexError。在

这就是我需要的暗示!当我使用numpy.concatenate时,它是有效的。工作代码如下:

# Conditions to be solved
def fSSBj(inp):
    return (0.5*inp[1])/(1+inp[1])-0.9*inp[0]
def fSSBJ(inp):
    return inp[0]-inp[2]*inp[1]

# Objective function that calls the functions with the conditions
# Use numpy.concatenate to concatenate the numpy arrays
def objFunc(inp,pM):
    out = empty(2)
    allInp = concatenate((inp,pM))
    out[0] = fSSBj(allInp)
    out[1] = fSSBJ(allInp)
    return out

# Be sure to give the argument as a list:
Out = optimize.root(objFunc, [1.0,1.0], args = ([0.2]), method='hybr')

相关问题 更多 >