【问题标题】:Python: how to turn list of word counts into format suitable for CountVectorizerPython:如何将字数列表转换为适合 CountVectorizer 的格式
【发布时间】:2017-09-16 10:20:03
【问题描述】:

我有大约 100,000 个形式的字符串列表:
['the: 652', 'of: 216', 'in: 168', 'to: 159', 'is: 145'] 等。
这基本上构成了我的语料库。每个列表都包含文档中的单词及其字数。

我怎样才能把这个语料库变成我可以输入到 CountVectorizer 的形式?

有没有比将每个列表转换为包含 'the' 652 次、'of' 216 次等的字符串更快的方法?

【问题讨论】:

    标签: python python-2.7 nlp nltk countvectorizer


    【解决方案1】:

    假设您要实现的是稀疏矩阵格式的矢量化语料库,以及经过训练的矢量化器,您可以在不重复数据的情况下模拟矢量化过程:

    from scipy.sparse.lil import lil_matrix
    from sklearn.feature_extraction.text import CountVectorizer
    
    corpus = [['the: 652', 'of: 216', 'in: 168', 'to: 159', 'is: 145'],
              ['king: 20', 'of: 16', 'the: 400', 'jungle: 110']]
    
    
    # Prepare a vocabulary for the vectorizer
    vocabulary = {item.split(':')[0] for document in corpus for item in document}
    indexed_vocabulary = {term: index for index, term in enumerate(vocabulary)}
    vectorizer = CountVectorizer(vocabulary=indexed_vocabulary)
    
    # Vectorize the corpus using the coordinates known to the vectorizer
    X = lil_matrix((len(corpus), len(vocabulary)))
    X.data = [[int(item.split(':')[1]) for item in document] for document in corpus]
    X.rows = [[vectorizer.vocabulary[(item.split(':')[0])] for item in document]
              for document in corpus]
    
    # Convert the matrix to csr format to be compatible with vectorizer.transform output
    X = X.tocsr()
    

    在本例中,输出将是:

    [[ 168.  216.    0.  159.  652.  145.    0.]
     [   0.   16.  110.    0.  400.    0.   20.]]
    

    这可以允许进一步的文档矢量化:

    vectorizer.transform(['jungle kid is programming', 'the jungle machine learning jungle'])
    

    产量:

    [[0 0 1 0 0 1 0]
     [0 0 2 0 1 0 0]]
    

    【讨论】:

    • 如果我想在这个过程中删除停用词,最好是在构建词汇表之前还是之后?
    • 这里有点棘手,因为语料库的矢量化不是在矢量化器中完成的。我能想到的一种简单方法是将stop_words 提供给矢量化构造函数。稍后在构建 data 和 rows 时,将过滤器添加到矢量化器停用词 (vectorizer.get_stop_words())。该方法保持了快速的向量化过程,并支持未来的文档转换。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-25
    • 2015-01-10
    • 1970-01-01
    • 2017-06-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多