【发布时间】:2012-01-16 17:39:15
【问题描述】:
我正在尝试用 Python 编写一个函数(仍然是一个菜鸟!),它返回按 tfidf 分数的内积排序的文档的索引和分数。程序是:
- 计算 doc
idx与所有其他文档之间的内积向量 - 降序排列
- 将“分数”和索引从第二个返回到末尾(即不是自身)
我现在的代码是:
import h5py
import numpy as np
def get_related(tfidf, idx) :
''' return the top documents '''
# calculate inner product
v = np.inner(tfidf, tfidf[idx].transpose())
# sort
vs = np.sort(v.toarray(), axis=0)[::-1]
scores = vs[1:,]
# sort indices
vi = np.argsort(v.toarray(), axis=0)[::-1]
idxs = vi[1:,]
return (scores, idxs)
其中tfidf 是sparse matrix of type '<type 'numpy.float64'>'。
这似乎效率低下,因为排序执行了两次(sort() 然后argsort()),然后必须反转结果。
- 这可以更有效地完成吗?
- 是否可以在不使用
toarray()转换稀疏矩阵的情况下做到这一点?
【问题讨论】:
标签: python numpy scipy information-retrieval sparse-matrix