只需对前 10 个节点的排序距离矩阵进行切片。像这样的东西:
from scipy.spatial import distance
# Find the query node
query_node = df.iloc[10] ## Not sure what you're looking for
# Find the distance between this node and everyone else
euclidean_distances = df.apply(lambda row: distance.euclidean(row, query_node), axis=1)
# Create a new dataframe with distances.
distance_frame = pandas.DataFrame(data={"dist": euclidean_distances, "idx": euclidean_distances.index})
distance_frame.sort("dist", inplace=True)
# nodes
smallest_dist_ixs = distance_frame.iloc[1:10]["idx"]
most_similar_nodes = df.iloc[int(smallest_dist_ixs)]
我的假设基于您在此处使用的“标题”一词以及 300 维向量的选择,这些是词或短语向量。
Gensim实际上有一种方法可以根据这个想法获得前N个相似词,速度相当快。
https://tedboy.github.io/nlps/generated/generated/gensim.models.Word2Vec.most_similar.html
>>> trained_model.most_similar(positive=['woman', 'king'], negative=['man'])
[('queen', 0.50882536), ...]
对于稍有不同的情况,如果您想获得所有点之间的最短路径,然后简单地切出前 10 个“城市” ,这也与旅行商问题 (TSP) 略有相似。
Google 在此处使用 OR-Tools 提供了一个非常简单快捷的 Python 实现:https ://developers.google.com/optimization/routing/tsp 。