roudan
roudan

Reputation: 4210

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

Upvotes: 0

Views: 76

Answers (2)

Barmar
Barmar

Reputation: 780929

Since elipse() takes 3 arguments, but BallTree() only supplies 2 arguments, you can still use a lambda, but it's simpler because the long equation is in the function.

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

Upvotes: 2

quamrana
quamrana

Reputation: 39354

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)  

Upvotes: 1

Related Questions