【发布时间】:2018-12-12 15:31:55
【问题描述】:
我想使用 fmin 找到函数的最小值,但出现以下错误:
TypeError: <lambda>() takes 1 positional argument but 2 were given
有问题的代码如下:
import numpy as np
from scipy.optimize import fmin
g = lambda alpha: np.sum(np.square(np.subtract(D, (avec[0]-alpha*grad)*f((avec[1]-alpha*grad),y))))
b = fmin(g,0.0)
您能告诉我如何解决这个问题吗?
完整的代码在这里:
from scipy.optimize import fmin
from scipy import interpolate
import numpy as np
Emax = 10;
bins = 200;
x = np.linspace(1, Emax, num = Emax, dtype=np.int) #create grid of indexes
y = np.linspace(1, bins, num = bins, dtype=np.int)
z = np.random.rand(bins, Emax) # response matrix
f = interpolate.interp2d(x,y,z, kind='cubic') # make the matrix continious
D= np.zeros(bins)
D = 1*f(1.5, y) + 3*f(2.5, y) # signal
iterations = 1000
step = 1e-5
avec = np.array([1.0,2.0]) # chosen starting parameters
grad = np.array([0.0,0.0])
chix_current = np.arange(iterations, dtype=float)
#gradient unfolding
for i in range(0, iterations):
fx = avec[0]*f(avec[1], y) # evaluation in every layer
chi = np.square(np.subtract(D,fx)) #chi function
chi_a = np.square(np.subtract(D, (avec[0]+step)*f(avec[1],y)))
chi_b = np.square(np.subtract(D, avec[0]*f((avec[1]+step),y)))
chisquared = np.sum(chi)
chisquared_a = np.sum(chi_a)
chisquared_b = np.sum(chi_b)
grad[0] = np. divide(np.subtract(chisquared_a, chisquared), step)
grad[1] = np.divide(np.subtract(chisquared_b, chisquared), step)
g= lambda alpha: np.sum(np.square(np.subtract(D, (avec[0]-alpha*grad)*f((avec[1]-alpha*grad),y)) ))
b= fmin(g,(0.0))
avec= np.subtract(avec, 1e5*grad )
最终我只需要知道函数 g 处于最小值时的 alpha 值,并在最后一行使用它而不是 1e5。
【问题讨论】:
-
请发布可重现的代码。见stackoverflow.com/help/mcve
-
什么是
D、avec[0]、alpha、grad、f((avec[1]-alpha*grad)、y? -
f((avec[1]-alpha*grad),y)使用两个参数调用您的lambda:(avec[1]-alpha*grad)和y。更重要的是,我不确定这个递归代码是否会达到你的预期。 -
可读性有助于我们对您的代码进行故障排除。尝试在发布之前重新组织并添加上下文,以便人们尽可能地理解它。
-
感谢cmets,代码已添加
标签: python error-handling