【问题标题】:Returning term position in a document with scikit-learn使用 scikit-learn 返回文档中的术语位置
【发布时间】:2015-11-17 11:59:59
【问题描述】:

我知道 scikit-learn 根据documentation 遵循词袋假设/模型。但是,有没有办法在计算 tf-idf 时提取词的位置?

例如,如果我有这些文件

document1 = "foo bar baz"
document2 = "bar bar baz"

我能以某种方式得到这个(term_id 的元组/列表)

document1_terms = (1, 2, 3)
document2_terms = (2, 2, 3)

或(术语字典,以位置元组为值)

document1_terms = {1: (1, ), 2: (2, ), 3: (3, )}
document2_terms = {2: (1, 2), 3: (3, )}

【问题讨论】:

    标签: python scikit-learn


    【解决方案1】:

    经过反复试验,我找到了解决此问题的方法。首先创建帖子

    vectorizer = CountVectorizer()
    
    term_doc_freq = vectorizer.fit_transform(collection['document'])
    

    然后用一个术语ID元组表示每个文档

    from functools import partial
    def document_get_position(row, vectorizer):
        result = tuple()
    
        for token in vectorizer.build_tokenizer()(row['document']):
            result = result + (vectorizer.vocabulary_.get(token),)
    
        return result
    
    positions = collection.apply(partial(document_get_position,
                                         vectorizer=vectorizer),
                                 axis=1)
    

    【讨论】:

      【解决方案2】:

      你是这个意思吗?

      In [13]: from sklearn.feature_extraction.text import CountVectorizer
      
      In [14]: vectorize = CountVectorizer(min_df=1)
      
      In [15]: document1 = "foo bar baz"
          ...: document2 = "bar bar baz dee"
          ...: 
      
      In [16]: documents = [document1, document2]
      
      In [17]: d = vectorize.fit_transform(documents)
      
      In [18]: vectorize.vocabulary_
      Out[18]: {u'bar': 0, u'baz': 1, u'dee': 2, u'foo': 3}
      
      In [19]: d.todense()
      Out[19]: 
      matrix([[1, 1, 0, 1],
              [2, 1, 1, 0]], dtype=int64)
      

      【讨论】:

      • 其实他不是在找这个。您正在为整个文档集创建一个词汇表。 OP 显然正在寻找“文档级”的字典。
      • 不,我不希望将稀疏矩阵转换为密集矩阵,@Radu Gheorghiu,在文档级别并不是真正的 dict,但更像是尝试以某种方式用术语 ID 表示每个文档,并且他们在文档中的各自位置
      猜你喜欢
      • 2016-07-15
      • 2016-08-09
      • 1970-01-01
      • 1970-01-01
      • 2018-10-11
      • 2018-01-29
      • 1970-01-01
      • 2017-01-11
      • 2014-10-02
      相关资源
      最近更新 更多