Name errors with lambda functions in Python

这一生的挚爱 提交于 2019-12-13 03:14:20

问题


I am working with the following example. I wanted to run my code with mu>=0.9 in the last line of the following snippet.

alpha,beta,loc,scale = stats.beta.fit(value)  

error=(scale/(1.96))**2

gpdf = lambda B0, mu, sigma2: 1/np.sqrt(2*pi*sigma2)*np.exp(-1/2*((B0-mu)**2)/sigma2)
approx_sigma2 = lambda scale: (scale/(1.96))**2
ggpdf_v  = lambda B0, D0, error: gpdf(B0, mu=0.8, sigma2=error) * (D0 < 3) + (D0 >= 3) * gpdf(B0, mu=0.5, sigma2=error)
ggpdf_r  = lambda B0, D0, error: gpdf(B0, mu=0.5, sigma2=error)
ggpdf_c  = lambda B0, D0, error: gpdf(B0, mu=0.7, sigma2=error)
ggpdf_v  = lambda B0, D0, error: gpdf(B0, mu>=0.9, sigma2=error)

However, I am getting this error NameError: name 'mu' is not defined. It is already defined but I don't see the problem. How can I fix this error?


回答1:


This

gpdf(B0, mu=0.7, sigma2=error)

is actually syntax for a function, assigning 0.7 to the argument called mu in that function, and the value of error to the argument called sigma2 in that function.

mu>=0.9 is not valid Python syntax for assigning to a keyword argument in a function call, but it is a valid ordinary Python expression. But for that expression to evaluate, the variable mu must be defined, which it isn't. But even if it was defined, I doubt it would do what you want: it would pass True as an argument to that function.




回答2:


As mentioned elsewhere, this comes from your typo in keyword assignment >= instead of =. It is confusing because you don't hit it when f2 is defined, only when it f2 is evaluated (since it is hidden inside a lambda).

Here is a minimal example that shows the issue.

>>> f1 = lambda a: None
>>> f2 = lambda: f1(a >= 0)
>>> f2()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 1, in <lambda>
NameError: name 'a' is not defined


来源:https://stackoverflow.com/questions/55171597/name-errors-with-lambda-functions-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!