用 n-grams 更細緻地拆解

Python 情感分析

Violeta Misheva

Data Scientist

脈絡很重要

I am happy, not sad.

I am sad, not happy.

  • 在詞前加上「not」(否定)說明了脈絡會影響意義。
Python 情感分析

用 BOW 擷取脈絡

  • Unigrams:單一詞元

  • Bigrams:兩詞元組

  • Trigrams:三詞元組

  • n-grams:連續 n 個詞元

Python 情感分析

用 BOW 擷取脈絡

The weather today is wonderful.

  • Unigrams:{ The, weather, today, is, wonderful }

  • Bigrams:{The weather, weather today, today is, is wonderful}

  • Trigrams:{The weather today, weather today is, today is wonderful}

Python 情感分析

在 CountVectorizer 使用 n-grams

from sklearn.feature_extraction.text import CountVectorizer
vect = CountVectorizer(ngram_range=(min_n, max_n))
# Only unigrams
ngram_range=(1, 1)
# Uni- and bigrams
ngram_range=(1, 2)
Python 情感分析

最佳的 n 是多少?

較長的詞元序列
  • 產生更多特徵
  • 模型精確度較高
  • 過度擬合風險提高
Python 情感分析

設定字彙表大小

CountVectorizer(max_features, max_df, min_df)
  • max_features:若指定,僅保留字彙表中最常見的前幾個詞
    • 若 max_features = None,則納入所有詞
  • max_df:忽略高於指定頻率的詞
    • 設為整數則為絕對次數;設為浮點數則為比例
    • 預設為 1.0,表示不忽略任何詞
  • min_df:忽略低於指定頻率的詞
    • 設為整數則為絕對次數;設為浮點數則為比例
    • 預設為 1.0,表示不忽略任何詞
Python 情感分析

一起來練習吧!

Python 情感分析

Preparing Video For Download...