10 万個のベクトルのセットがあり、コサイン類似度に基づいて上位 25 個の最も近いベクトルを取得する必要があります。
Scipy と Sklearn には、コサイン距離/類似度 2 ベクトルを計算するための実装がありますが、100k X 100k サイズのコサイン Sim を計算してから、トップ 25 を取り出す必要があります。Python計算に高速な実装はありますか?
@Silmathoronの提案によると、これが私がやっていることです-
#vectors is a list of vectors of size : 100K x 400 i.e. 100K vectors each of dimenions 400
vectors = numpy.array(vectors)
similarity = numpy.dot(vectors, vectors.T)
# squared magnitude of preference vectors (number of occurrences)
square_mag = numpy.diag(similarity)
# inverse squared magnitude
inv_square_mag = 1 / square_mag
# if it doesn't occur, set it's inverse magnitude to zero (instead of inf)
inv_square_mag[numpy.isinf(inv_square_mag)] = 0
# inverse of the magnitude
inv_mag = numpy.sqrt(inv_square_mag)
# cosine similarity (elementwise multiply by inverse magnitudes)
cosine = similarity * inv_mag
cosine = cosine.T * inv_mag
k = 26
box_plot_file = file("box_data.csv","w+")
for sim,query in itertools.izip(cosine,queries):
k_largest = heapq.nlargest(k, sim)
k_largest = map(str,k_largest)
result = query + "," + ",".join(k_largest) + "\n"
box_plot_file.write(result)
box_plot_file.close()