【问题标题】:From featurers to words python ("reverse" bag of words)从特征到词 python(“反向”词袋)
【发布时间】:2019-03-15 20:23:00
【问题描述】:

我使用 sklearn 在 Python 中创建了一个包含 200 个特征的 BOW,这些特征很容易提取。但是,我怎样才能扭转它呢?也就是说,从一个包含 200 个 0 或 1 的向量到对应的单词?由于词汇表是字典,因此没有排序,我不确定特征列表中的每个元素对应于哪个单词。另外,如果我的 200 维向量中的第一个元素对应字典中的第一个词,那么我如何通过索引从字典中提取一个词?

弓是这样创建的

vec = CountVectorizer(stop_words = sw, strip_accents="unicode", analyzer = "word", max_features = 200)
features = vec.fit_transform(data.loc[:,"description"]).todense()

因此“特征”是一个矩阵 (n,200) 矩阵(n 是句子的数量)。

【问题讨论】:

    标签: python scikit-learn feature-extraction


    【解决方案1】:

    我不完全确定您要做什么,但您似乎只是想弄清楚哪一列代表哪个单词。为此,有方便的get_feature_names 参数。

    让我们看一下docs中提供的示例语料库:

    corpus = [
         'This is the first document.',
         'This document is the second document.',
         'And this is the third one.',
         'Is this the first document?' ]
    
    # Put into a dataframe
    data = pd.DataFrame(corpus,columns=['description'])
    # Take a look:
    >>> data
                                 description
    0            This is the first document.
    1  This document is the second document.
    2             And this is the third one.
    3            Is this the first document?
    
    # Initialize CountVectorizer (you can put in your arguments, but for the sake of example, I'm keeping it simple):
    vec = CountVectorizer()
    
    # Fit it as you had before:
    features = vec.fit_transform(data.loc[:,"description"]).todense()
    
    >>> features
    matrix([[0, 1, 1, 1, 0, 0, 1, 0, 1],
            [0, 2, 0, 1, 0, 1, 1, 0, 1],
            [1, 0, 0, 1, 1, 0, 1, 1, 1],
            [0, 1, 1, 1, 0, 0, 1, 0, 1]], dtype=int64)
    

    要查看哪一列代表哪个单词,请使用get_feature_names

    >>> vec.get_feature_names()
    ['and', 'document', 'first', 'is', 'one', 'second', 'the', 'third', 'this']
    

    所以您的第一列是and,第二列是document,依此类推。为了便于阅读,您可以将其粘贴在数据框中:

    >>> pd.DataFrame(features, columns = vec.get_feature_names())
       and  document  first  is  one  second  the  third  this
    0    0         1      1   1    0       0    1      0     1
    1    0         2      0   1    0       1    1      0     1
    2    1         0      0   1    1       0    1      1     1
    3    0         1      1   1    0       0    1      0     1
    

    【讨论】:

    • 这就是我要找的!我搜索了文档和大量示例,但我不知道我是如何错过的。谢谢! :D
    猜你喜欢
    • 2016-09-27
    • 1970-01-01
    • 2017-06-17
    • 2012-06-24
    • 2019-09-16
    • 2016-02-16
    • 2015-12-27
    • 1970-01-01
    相关资源
    最近更新 更多