目前我正在做一个可能需要使用kNN算法来找到给定点的前k个最近邻居的项目,比如P. im使用python,sklearn包来完成这项工作,但是我们的预定义度量不是那些默认值指标.所以我必须使用用户定义的度量标准,来自sklearn的文档,可以在这里和这里找到.
似乎最新版本的sklearn kNN支持用户定义的度量标准,但我无法找到如何使用它:
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
Run Code Online (Sandbox Code Playgroud)
我已经定义了一个名为mydist = max(xy)的度量,然后使用DistanceMetric.get_metric使其成为DistanceMetric对象:
dt=DistanceMetric.get_metric('pyfunc',func=mydist)
Run Code Online (Sandbox Code Playgroud)
从文档中,该行应该如下所示
nbrs = NearestNeighbors(n_neighbors=4, algorithm='auto',metric='pyfunc').fit(A)
distances, indices = nbrs.kneighbors(A)
Run Code Online (Sandbox Code Playgroud)
但我dt在哪里可以放入?谢谢
我正在尝试为聚类实现自定义距离度量。代码片段如下所示:
import numpy as np
from sklearn.cluster import KMeans, DBSCAN, MeanShift
def distance(x, y):
# print(x, y) -> This x and y aren't one-hot vectors and is the source of this question
match_count = 0.
for xi, yi in zip(x, y):
if float(xi) == 1. and xi == yi:
match_count += 1
return match_count
def custom_metric(x, y):
# x, y are two vectors
# distance(.,.) calculates count of elements when both xi and yi are True
return distance(x, y)
vectorized_text …Run Code Online (Sandbox Code Playgroud)