超越 n-grams:詞向量

Python 中文本特徵工程

Rounak Banik

Data Scientist

BoW 與 tf-idf 的侷限

'I am happy'
'I am joyous'
'I am sad'
Python 中文本特徵工程

詞向量(Word embeddings)

  • 將詞彙映射到 n 維向量空間
  • 以深度學習與海量資料訓練產生
  • 判別兩個詞的相似程度
  • 用於偵測同義詞與反義詞
  • 捕捉複雜關係
    • King-QueenMan-Woman
    • France-ParisRussia-Moscow
  • 取決於 spaCy 模型,與你使用的資料集無關
Python 中文本特徵工程

使用 spaCy 的詞向量

import spacy

# Load model and create Doc object
nlp = spacy.load('en_core_web_lg')
doc = nlp('I am happy')
# Generate word vectors for each token
for token in doc:
  print(token.vector)
[-1.0747459e+00  4.8677087e-02  5.6630421e+00  1.6680446e+00
 -1.3194644e+00 -1.5142369e+00  1.1940931e+00 -3.0168812e+00
 ...
Python 中文本特徵工程

詞彙相似度

doc = nlp("happy joyous sad")
for token1 in doc:
  for token2 in doc:
    print(token1.text, token2.text, token1.similarity(token2))
happy happy 1.0
happy joyous 0.63244456
happy sad 0.37338886
joyous happy 0.63244456
joyous joyous 1.0
joyous sad 0.5340932
...
Python 中文本特徵工程

文件相似度

# Generate doc objects
sent1 = nlp("I am happy")
sent2 = nlp("I am sad")
sent3 = nlp("I am joyous")
# Compute similarity between sent1 and sent2
sent1.similarity(sent2)
0.9273363837282105
# Compute similarity between sent1 and sent3
sent1.similarity(sent3)
0.9403554938594568
Python 中文本特徵工程

一起來練習吧!

Python 中文本特徵工程

Preparing Video For Download...