构建 n-gram 模型

Python 中的 NLP 特征工程

Rounak Banik

Data Scientist

BoW 的局限

review label
'The movie was good and not boring' positive
'The movie was not good and boring' negative

 

  • BoW 表示完全相同!
  • 上下文丢失。
  • 情感取决于"not"的位置。
Python 中的 NLP 特征工程

n-grams

  • 文档中连续的 n 个元素(或词)。
  • n = 1 → bag-of-words
    'for you a thousand times over'
    
  • n = 2,n-gram:
    [
    'for you',
    'you a',
    'a thousand',
    'thousand times',
    'times over'
    ]
    
Python 中的 NLP 特征工程

n-grams

'for you a thousand times over'
  • n = 3,n-gram:
    [
    'for you a',
    'you a thousand',
    'a thousand times',
    'thousand times over'
    ]
    
  • 捕获更多上下文。
Python 中的 NLP 特征工程

应用

  • 句子补全
  • 拼写纠错
  • 机器翻译纠错
Python 中的 NLP 特征工程

用 scikit-learn 构建 n-gram 模型

仅生成二元组。

bigrams = CountVectorizer(ngram_range=(2,2))

生成一元组、二元组和三元组。

ngrams = CountVectorizer(ngram_range=(1,3))
Python 中的 NLP 特征工程

局限性

  • 维度灾难
  • 高阶 n-gram 罕见
  • 保持 n 较小
Python 中的 NLP 特征工程

Vamos praticar!

Python 中的 NLP 特征工程

Preparing Video For Download...