二维函数的SciPy极小化

2024-09-28 19:08:42 发布

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

我想最小化我的二维函数:

def error(w0, w1):
    sum = 0
    for index, row in data.head(5).iterrows():
        sum += (row['Height'] - (w0 + w1*row['Weight']))**2
    return sum

使用scipy optimize包,使用minimize函数。你知道吗

我设置初始变量:

w0 = 0
w1 = 0

并描述了边界:

bnds = ((-100, 100), (-5, 5))

但是,当我试图最小化我的函数

res = opt.minimize(error,w0,w1,method='L-BFGS-B', bounds=bnds)

我收到一个错误:

ValueError: length of x0 != length of bounds

我应该如何适当地最小化?你知道吗


Tags: of函数inforindexdeferrorlength
1条回答
网友
1楼 · 发布于 2024-09-28 19:08:42

您的最小化调用是错误的:

res = opt.minimize(error, [w0, w1], method='L-BFGS-B', bounds=bnds)

x0需要是一些数组。按照您所做的方式,初始点的第二维度被解释为该函数signature中的其他参数(意思是:只有w0被解释为x0,它是标量,而不是大小为2的数组->;与这些边界不兼容)。你知道吗

同样的原则也适用于您的职能:

def error(x):
    w0, w1 = x
    sum = 0
    for index, row in data.head(5).iterrows():
        sum += (row['Height'] - (w0 + w1*row['Weight']))**2
    return sum

相关问题 更多 >