【问题标题】:Obtain tf-idf weights of words with sklearn使用 sklearn 获取单词的 tf-idf 权重
【发布时间】:2017-12-27 05:03:50
【问题描述】:

我有一组维基百科的文本。
使用 tf-idf,我可以定义每个单词的权重。 下面是代码:

import pandas as pd                                             
from sklearn.feature_extraction.text import TfidfVectorizer

wiki = pd.read_csv('people_wiki.csv')

tfidf_vectorizer = TfidfVectorizer(max_features= 1000000)
tfidf = tfidf_vectorizer.fit_transform(wiki['text'])

目标是查看 tf-idf 列中显示的权重:

文件“people_wiki.csv”在这里:

https://ufile.io/udg1y

【问题讨论】:

    标签: python machine-learning scikit-learn nlp tf-idf


    【解决方案1】:

    TfidfVectorizer 有一个 vocabulary_ 属性,它对你想要的东西非常有用。该属性是以单词为键,以单词对应的列索引为值的字典。

    对于下面的例子,我想要那个字典的逆,因为我使用字典理解。

    tfidf_vec = TfidfVectorizer()
    transformed = tfidf_vec.fit_transform(raw_documents=['this is a quick example','just to show off'])
    index_value={i[1]:i[0] for i in tfidf_vec.vocabulary_.items()}
    

    index_value 将进一步用作查找表。

    fit_transform 返回压缩稀疏行格式矩阵。对您想要实现的目标有用的属性是indicesdataindices 返回所有实际包含数据的索引,data 返回这些索引中的所有数据。

    循环返回的transformed稀疏矩阵如下。

    fully_indexed = []
    for row in transformed:
        fully_indexed.append({index_value[column]:value for (column,value) in zip(row.indices,row.data)})
    

    返回包含以下内容的字典列表。

    [{'example': 0.5, 'is': 0.5, 'quick': 0.5, 'this': 0.5},
     {'just': 0.5, 'off': 0.5, 'show': 0.5, 'to': 0.5}]
    

    请注意,这样做只会返回特定文档的非零值的单词。查看我示例中的第一个文档,字典中没有 'just', 0.0 键值对。如果你想包括那些,你需要稍微调整一下最终的字典理解。

    像这样

    fully_indexed = []
    transformed = np.array(transformed.todense())
    for row in transformed:
        fully_indexed.append({index_value[column]:value for (column,value) in enumerate(row)})
    

    我们创建一个密集版本的矩阵作为一个 numpy 数组循环遍历 numpy 数组的每一行枚举内容,然后填充字典列表。 这样做会导致输出还包括文档中不存在的所有单词。

    [{'example': 0.5,'is': 0.5,'just': 0.0,'off': 0.0,'quick': 0.5,'show': 0.0,'this': 0.5,'to': 0.0},
     {'example': 0.0,'is': 0.0,'just': 0.5,'off': 0.5,'quick': 0.0,'show': 0.5,'this': 0.0,'to': 0.5}]
    

    然后,您可以将字典添加到您的数据框中。

    df['tf_idf'] = fully_indexed
    

    【讨论】:

      猜你喜欢
      • 2019-07-08
      • 2016-08-07
      • 2021-02-13
      • 2021-04-21
      • 2016-03-30
      • 1970-01-01
      • 2019-06-12
      • 1970-01-01
      • 2018-03-23
      相关资源
      最近更新 更多