您要查找的内容称为相似性度量。快速的 google/SO 搜索将揭示获得两个向量之间相似性的各种方法。以下是python2中余弦相似度的一些示例代码:
from math import *
def square_rooted(x):
return round(sqrt(sum([a*a for a in x])),3)
def cosine_similarity(x,y):
numerator = sum(a*b for a,b in zip(x,y))
denominator = square_rooted(x)*square_rooted(y)
return round(numerator/float(denominator),3)
print cosine_similarity([3, 45, 7, 2], [2, 54, 13, 15])
取自:http://dataaspirant.com/2015/04/11/five-most-popular-similarity-measures-implementation-in-python/
我注意到您希望每个项目的前 k 个相似项目。最好的方法是使用 k 最近邻实现。您可以做的是创建一个 knn 图并从图中返回前 k 个相似项以进行查询。
nmslib 是一个很好的库。这是具有余弦相似度的 HNSW 方法的 knn 查询from the library 的一些示例代码(您可以使用几种可用方法之一。HNSW 对于您的高维数据特别有效):
import nmslib
import numpy
# create a random matrix to index
data = numpy.random.randn(10000, 100).astype(numpy.float32)
# initialize a new index, using a HNSW index on Cosine Similarity
index = nmslib.init(method='hnsw', space='cosinesimil')
index.addDataPointBatch(data)
index.createIndex({'post': 2}, print_progress=True)
# query for the nearest neighbours of the first datapoint
ids, distances = index.knnQuery(data[0], k=10)
# get all nearest neighbours for all the datapoint
# using a pool of 4 threads to compute
neighbours = index.knnQueryBatch(data, k=10, num_threads=4)
在代码的最后,每个数据点的 k 个顶部邻居将存储在 neighbours 变量中。您可以将其用于您的目的。