【问题标题】:"takes 1 positional argument but 2 were given" while finding minimum of function“接受 1 个位置参数,但给出了 2 个”,同时找到函数的最小值
【发布时间】: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
  • 什么是Davec[0]alphagradf((avec[1]-alpha*grad)y
  • f((avec[1]-alpha*grad),y) 使用两个参数调用您的 lambda(avec[1]-alpha*grad)y。更重要的是,我不确定这个递归代码是否会达到你的预期。
  • 可读性有助于我们对您的代码进行故障排除。尝试在发布之前重新组织并添加上下文,以便人们尽可能地理解它。
  • 感谢cmets,代码已添加

标签: python error-handling


【解决方案1】:

你的代码不是很清楚,有些方法和变量是模棱两可的。

从您给出的内容来看,似乎 lambda 函数 f() 应该采用 1 个参数,但在 f() 内部您再次递归调用 f(),但内部 f() 采用 2 个参数,我认为这是一个错字.

尝试将您的 lambda 方法重命名为另一个没有冲突的名称,例如 g

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)

【讨论】:

  • 谢谢,我重命名了函数,但还是有错误
  • 如果还是一样的错误,那就是你的内部f()的问题,应该是1个参数,但是这里给了2个参数,你最好检查一下定义F()。如果您有新的错误,请告诉我们。
  • avec[2] 和 avec[3] 是什么? avec 是一个 2 值列表。 g = lambda alpha: np.sum(np.square(np.subtract(D, (avec[0]-alphagrad)*f((avec[1]-alphagrad),y) )))
  • 不要介意这些值,我已经从函数中删除了它们.. avec 有 2 个元素。我不小心把它从另一个代码复制到了这里
猜你喜欢
  • 2016-10-13
  • 2016-11-25
  • 2019-04-20
  • 2018-11-15
  • 2014-07-19
  • 2016-08-09
  • 2020-01-30
  • 2019-08-02
  • 1970-01-01
相关资源
最近更新 更多