我想尽量减少我的二维功能:
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
我应该如何正确地减少?
答案 0 :(得分:1)
您的最小化调用是错误的:
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