Currently I'm doing a project which may require using a kNN algorithm to find the top k nearest neighbors for a given point, say P. im using python, sklearn package to do the job, but our predefined metric is not one of those default metrics. so I have to use the user defined metric, from the documents of sklearn, which can be find here and here.
It seems that the latest version of sklearn kNN support the user defined metric, but i cant find how to use it:
import sklearn
from sklearn.neighbors import NearestNeighbors
import numpy as np
from sklearn.neighbors import DistanceMetric
from sklearn.neighbors.ball_tree import BallTree
BallTree.valid_metrics
say i have defined a metric called mydist=max(x-y), then use DistanceMetric.get_metric to make it a DistanceMetric object:
dt=DistanceMetric.get_metric('pyfunc',func=mydist)
from the document, the line should looks like this
nbrs = NearestNeighbors(n_neighbors=4, algorithm='auto',metric='pyfunc').fit(A)
distances, indices = nbrs.kneighbors(A)
but where can i put the dt
in? Thanks
nbrs = NearestNeighbors(n_neighbors=4, algorithm='auto',metric='pyfunc').fit(A) distances, indices = nbrs.kneighbors(A)
not working even i putfunc=mydist
in there is because the parameteralgorithm=auto
not accepting user defined metrics, neitheralgorithm=kd_tree
oralgorithm=brute
. Only thealgorithm=ball_tree
accepts – Fragonard