python - 获取 scikit-learn tf-idf 矩阵中的文档名称

标签 python matrix machine-learning scikit-learn tf-idf

我已经创建了一个 tf-idf 矩阵,但现在我想检索每个文档的前 2 个词。我想传递文档 ID,它应该给我前 2 个词。

现在,我有这个示例数据:

from sklearn.feature_extraction.text import TfidfVectorizer

d = {'doc1':"this is the first document",'doc2':"it is a sunny day"} ### corpus

test_v = TfidfVectorizer(min_df=1)    ### applied the model
t = test_v.fit_transform(d.values())
feature_names = test_v.get_feature_names() ### list of words/terms

>>> feature_names
['day', 'document', 'first', 'is', 'it', 'sunny', 'the', 'this']

>>> t.toarray()
array([[ 0.        ,  0.47107781,  0.47107781,  0.33517574,  0.        ,
     0.        ,  0.47107781,  0.47107781],
   [ 0.53404633,  0.        ,  0.        ,  0.37997836,  0.53404633,
     0.53404633,  0.        ,  0.        ]])

我可以通过给出行号来访问矩阵,例如。

 >>> t[0,1]
   0.47107781233161794

有没有一种方法可以通过文档 ID 访问此矩阵?在我的例子中是“doc1”和“doc2”。

谢谢

最佳答案

通过做

t = test_v.fit_transform(d.values())

您丢失了所有指向文档 ID 的链接。字典没有排序,所以你不知道哪个值是按哪个顺序给出的。这意味着在将值传递给 fit_transform 函数之前,您需要记录哪个值对应于哪个 id。

例如你可以做的是:

counter = 0
values = []
key = {}


for k,v in d.items():
    values.append(v)
    key[k] = counter
    counter+=1

t = test_v.fit_transform(values)

从那里你可以构建一个函数来通过文档 ID 访问这个矩阵:

def get_doc_row(docid):
    rowid = key[docid]
    row = t[rowid,:]
    return row

关于python - 获取 scikit-learn tf-idf 矩阵中的文档名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26304191/

相关文章:

python - django-nose 与默认的 Django 测试运行器有何不同

matlab - 如何随机分配矩阵元素

r - 因子 MSZoning 具有新级别 NA(数据中有新因子,但线性回归模型中没有)

optimization - Hyperopt 在执行期间设置超时并修改空间

tensorflow - 当数据集不平衡时多类分类的最佳损失函数?

python - matplotlib scatter_hist 在直方图中具有 stepfilled histt​​ype

python - 在不丢失顺序的情况下消除冗余的 2D 点

python - “QuerySet”对象没有属性 'save'

python - 来自 numpy 数组的派生类不能很好地与矩阵和掩码数组一起使用

java - 将 3x3 OpenCV Mat 转换为 Android 矩阵