user4720834
user4720834

Reputation:

How to use user defined metric in KernelDensity from scikit-learn (python)

I'm using scikit-learn (0.14) and trying to implement a user defined metric for my KernelDensity estimation.

Following code is an example how my code is structured:

def myDistance(x,y):
    return np.sqrt(sum((x - y)**2))

dt=DistanceMetric.get_metric("pyfunc",func=myDistance)

kernelModel=KernelDensity(algorithm='ball_tree',metric='pyfunc')
kernelModel.fit(X)

According to the documentation, the BallTree algorithm should accept user defined metrics. If I run this code the way given here, I get following error:

TypeError: __init__() takes exactly 1 positional argument (0 given) 

The error seems to come from:

sklearn.neighbors.dist_metrics.PyFuncDistance.__init__

I don't understand this. If i check what 'dt' in the code above gives me, I get what I expect. dt.pairwise(X) returns the correct values. What am I doing wrong?

Thanks in advance.

Upvotes: 3

Views: 822

Answers (1)

user4720834
user4720834

Reputation:

Solution is

kernelModel=KernelDensity(...,metric='pyfunc',metric_params={"func":myDistance})

The call to Distancemetric.get_metric is not necessary. M

Upvotes: 6

Related Questions