建立 n-gram 模型

Python 中文本特徵工程

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 中文本特徵工程

n-grams

  • 一段文件中連續的 n 個元素(或單字)。
  • n = 1 → bag-of-words
    'for you a thousand times over'
    
  • n = 2,n-grams:
    [
    'for you',
    'you a',
    'a thousand',
    'thousand times',
    'times over'
    ]
    
Python 中文本特徵工程

n-grams

'for you a thousand times over'
  • n = 3,n-grams:
    [
    'for you a',
    'you a thousand',
    'a thousand times',
    'thousand times over'
    ]
    
  • 可擷取更多脈絡。
Python 中文本特徵工程

應用

  • 句子補全
  • 拼字更正
  • 機器翻譯修正
Python 中文本特徵工程

使用 scikit-learn 建立 n-gram 模型

只產生 bigram。

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

產生 unigram、bigram 與 trigram。

ngrams = CountVectorizer(ngram_range=(1,3))
Python 中文本特徵工程

侷限

  • 維度詛咒
  • 高階 n-gram 罕見
  • 保持 n 小
Python 中文本特徵工程

一起來練習吧!

Python 中文本特徵工程

Preparing Video For Download...