简体   繁体   中英

how to convert lambda function into a separate function?

I am not sure how to pass argument after converting lambda function into separate function.

Here is the original codes which works.

from sklearn.neighbors import BallTree
X = np.array([[-1, -1], [-2, -1], [-3, -2], [1, 1], [2, 1], [3, 2]])
aspect=2
tree = BallTree(X,metric="pyfunc",func=lambda p0, p1: math.sqrt((p1[0] - p0[0]) * (p1[0] - p0[0]) + (p1[1] - p0[1]) * (p1[1] - p0[1]) * aspect)) 

since the above lambda function is too long, i'd like define a separate function fromthis lambda function.

def elipse(p0,p1,aspect):

   a=math.sqrt((p1[0] - p0[0]) * (p1[0] - p0[0]) + (p1[1] - p0[1]) * (p1[1] - p0[1]) * aspect)  
   return  a

tree = BallTree(X,metric="pyfunc",func=elipse(X.iloc[:,0],X.iloc[:,1],aspect)) 

then i got an error of TypeError: 'float' object is not callable

I am not sure how to pass p0 and p1 , could anyone help me? Thanks

由于elipse()接受 3 个参数,但BallTree()仅提供 2 个参数,您仍然可以使用lambda ,但它更简单,因为长方程在函数中。

tree = BallTree(X,metric="pyfunc",func=lambda p0, p1: elipse(p0, p1, aspect)) 

Since you now have a named function, you just need to tell BallTree what that name is:

tree = BallTree(X,metric="pyfunc",func=elipse) 

Also, you don't need to have aspect as a parameter:

def elipse(p0, p1):
    aspect = 2
    return math.sqrt((p1[0] - p0[0]) * (p1[0] - p0[0]) + (p1[1] - p0[1]) * (p1[1] - p0[1]) * aspect)  

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM