【问题标题】:Map a sentence to its vocabulary in sklearn将句子映射到 sklearn 中的词汇表
【发布时间】:2019-08-06 13:07:36
【问题描述】:

我正在使用CountVectorizer 来获取字符串列表中的单词列表

from sklearn.feature_extraction.text import CountVectorizer
raw_text = [
    'The dog hates the black cat',
    'The black dog is good'
]
raw_text = [x.lower() for x in raw_text]
vocabulary = vectorizer.vocabulary_ 
vocabulary = dict((v, k) for k, v in vocabulary.iteritems())
vocabulary

在词汇表中,我有以下数据,这些数据是正确的

{0: u'black', 1: u'cat', 2: u'dog', 3: u'good', 4: u'hates', 5: u'is', 6: u'the'}

我现在想要获得的是“映射”到这些新值的原始句子,例如:

expected_output = [
    [6, 2, 4, 6, 0, 1],
    [6, 0, 2, 5, 3]
]

我尝试探索 Sklearn 文档,但我真的找不到任何似乎可以做到这一点的东西,而且我什至不知道我正在尝试执行的操作的正确术语,所以我在 Google 中找不到任何结果。

有没有办法达到这个效果?

【问题讨论】:

    标签: python python-3.x python-2.7 machine-learning scikit-learn


    【解决方案1】:

    我认为您可以只适合文本来构建词汇表,然后使用词汇表使用build_analyzer() 创建所需的映射

    from sklearn.feature_extraction.text import CountVectorizer
    raw_text = [
        'The dog hates the black cat',
        'The black dog is good'
    ]
    vectorizer = CountVectorizer()
    vectorizer.fit(raw_text)
    
    analyzer = vectorizer.build_analyzer()
    [[vectorizer.vocabulary_[i]  for i in analyzer(doc)]  for doc in raw_text]
    

    输出:

    [[6, 2, 4, 6, 0, 1], [6, 0, 2, 5, 3]]

    【讨论】:

      【解决方案2】:

      像这样查找每个单词:

      from sklearn.feature_extraction.text import CountVectorizer
      raw_text = [
          'The dog hates the black cat',
          'The black dog is good'
      ]
      
      cv = CountVectorizer()
      cv.fit_transform(raw_text)
      
      
      vocab = cv.vocabulary_.copy()
      
      def lookup_key(string):
          s = string.lower()
          return [vocab[w] for w in s.split()]
      
      list(map(lookup_key, raw_text))
      

      输出:

      [[6, 2, 4, 6, 0, 1], [6, 0, 2, 5, 3]]
      

      【讨论】:

      • 与此处另一个答案中的解决方案相比,此解决方案对于大量文本通常应该具有更好的运行时间。
      • .split() 不考虑停用词或其他前置词,在构建词汇表时可能会使用 countVectorizer
      • @AI_Learning 好点。也许对任何被删除的停用词使用 -1 对 OP 的用例来说就足够了。
      【解决方案3】:

      您可以尝试以下方法吗:

      mydict = {0: u'black', 1: u'cat', 2: u'dog',
                3: u'good', 4: u'hates', 5: u'is', 6: u'the'}
      
      
      def get_val_key(val):
          return list(mydict.keys())[list(mydict.values()).index(val.lower())]
      
      
      raw_text = [
          'The dog hates the black cat',
          'The black dog is good'
      ]
      expected_output = [list(map(get_val_key, text.split())) for text in raw_text]
      print(expected_output)
      

      输出:

      [[6, 2, 4, 6, 0, 1], [6, 0, 2, 5, 3]]
      

      【讨论】:

      • 有效,但由于使用了值列表,因此具有二次时间复杂度。此处的另一个答案通过反转字典提供了更好的典型运行时间。
      猜你喜欢
      • 2018-09-28
      • 1970-01-01
      • 1970-01-01
      • 2019-08-29
      • 2020-09-09
      • 1970-01-01
      • 2020-11-15
      • 2018-10-17
      • 1970-01-01
      相关资源
      最近更新 更多