最小化给出 TypeError: bound1Expr() 缺少 2 个必需的位置参数

问题描述

调用函数 optimization() 时定义为

def optimization():
    bound1 = {
            'type': 'eq','fun': bound1Expr}
    bound2 = {
            'type': 'eq','fun': bound2Expr}
    optimizeResult = minimize(
                    toOptimize,(0,0),method = "SLSQP",options = {'disp': False},constraints = (
                            bound1,bound2
                            )
                        )
    return optimizeResult.x

def bound1Expr(x,y,z):
    return x + y + z -1
    
def bound2Expr(x,z):
    return x^2 + y^2 + z^2 - 10

def toOptimize(x,z):
    return (x^2 + y^2 + z^2)**0.5 

我收到错误

File "C:\ProgramData\Anaconda3\lib\site-packages\scipy\optimize\slsqp.py",line 313,in <listcomp>
        for c in cons['eq']]))
    
TypeError: bound1Expr() missing 2 required positional arguments: 'y' and 'z'

我查看了我能找到的所有资源,但都出现了同样的错误,但我仍然不知道该怎么做。通常发生的错误Self 变量有关,但我不在这里处理类。即使 Self 被隐式添加到 lambda 函数中,我也不知道为什么当我不使用它时会出现问题。

解决方法

您的代码修改为采用一个参数,而不是 3 个参数。我还将 ^ 更改为 ** 次幂。

In [105]: def optimization():
     ...:     bound1 = {
     ...:             'type': 'eq',...:             'fun': bound1Expr}
     ...:     bound2 = {
     ...:             'type': 'eq',...:             'fun': bound2Expr}
     ...:     optimizeResult = minimize(
     ...:                     toOptimize,...:                     (0,0),...:                     method = "SLSQP",...:                     options = {'disp': False},...:                     constraints = (
     ...:                             bound1,...:                             bound2
     ...:                             )
     ...:                         )
     ...:     return optimizeResult.x
     ...: 
     ...: def bound1Expr(xyz):
     ...:     x,y,z=xyz
     ...:     return x + y + z -1
     ...: 
     ...: def bound2Expr(xyz):
     ...:     x,z=xyz
     ...:     return x**2 + y**2 + z**2 - 10
     ...: 
     ...: def toOptimize(*args):
     ...:     print('args',args)
     ...:     x,z=args[0]
     ...:     return (x**2 + y**2 + z**2)**0.5
     ...: 
In [106]: optimization()
args (array([0.,0.,0.]),)
args (array([1.49011612e-08,0.00000000e+00,0.00000000e+00]),)
args (array([0.00000000e+00,1.49011612e-08,1.49011612e-08]),)
Out[106]: array([0.,0.])

toOptimize 所示,minimize 传递一个值,一个数组作为参数(如果您提供 args 参数,它将传递更多)。该数组有 3 个元素,对应于初始值数组(元组)。

在使用这些 scipy 函数时,正确获得函数定义通常是一个问题。用户忽略或不理解文档定义

fun : callable
    The objective function to be minimized.

        ``fun(x,*args) -> float``

    where ``x`` is an 1-D array with shape (n,) and ``args``
    is a tuple of the fixed parameters needed to completely

我的第一条评论是回应你关于查看“来源”的最后一段。看起来您在网络上搜索了有关缺少或必需位置参数的错误。这是一个比较普遍的问题。是的,当人们不考虑类方法的 self 参数时,通常会发生这种情况。但这里的情况并非如此,因此网络搜索效率低下。

(新)用户经常转向网络(或 SO)搜索,这时他们应该首先检查文档。有一个网页搜索的地方(例如独特的错误或最新的错误版本),但对于像这样的基本使用问题,您应该首先确保您了解如何正确使用该功能。