如何处理scipy最小化ValueError:没有足够的值要解压预期4,得到3?

问题描述

I am trying to minimize the following function by use of the scipy library:
from scipy.optimize import minimize

def constraint1(bet):
    a,b = bet
    return 100 - a + b

con1 = {'type': 'ineq','fun': constraint1}
cons = [con1]
b0,b1 = (0,100),(0,100)   
bnds = (b0,b1)

def f(bet,sign = -1,*args):
    d0,d1,p0,p1 = args
    a,b = bet
    wins0 = a * (d0-1)
    wins1 = b * (d1-1)
    loss0 = b
    loss1 = a
    log0 = np.log(bank + wins0 - loss0)
    log1 = np.log(bank + wins1 - loss1)
    
    objective = (log0 * p0 + log1 * p1)
    return sign * objective

bet = [0,0]
minimize(f,bet,args = (1,2,3,4,),method = 'trust-constr',bounds = bnds,constraints = cons)

但这会导致ValueError:

 d0,p1 = args (Think this is where the error occurs)
 ValueError: not enough values to unpack (expected 4,got 3)

试图省略,,使其看起来像这样:(1,4),但这也不起作用。

有什么用!

解决方法

您无法minimize使用可选参数。该功能必须如下所示:

fun(x,*args)

没有位置放置可选参数。因此,您要做的就是调用您的函数,以显式提供-1作为args之一:

minimize(f,bet,args = (-1,1,2,3,4,),method = 'trust-constr',bounds = bnds,constraints = cons)

这是documentation的链接。

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...