文字資料編碼

Deep Learning for Text with PyTorch

Shubham Jain

Data Scientist

文字編碼

Pytorch 處理流程

  • 將文字轉成機器可讀的數值
  • 便於分析與建模

從序列資料找洞見的示意圖

Deep Learning for Text with PyTorch

編碼技術

  • One-hot encoding: 將單字轉為唯一的數值表示
  • Bag-of-Words(BoW): 擷取詞頻,不考慮順序
  • TF-IDF: 兼顧稀有度與重要性
  • Embedding: 將單字轉成向量,捕捉語意(第 2 章)
Deep Learning for Text with PyTorch

One-hot encoding

  • 將每個單字對應到獨立向量
  • 二元向量
    • 出現為 1
    • 未出現為 0
  • ['cat', 'dog', 'rabbit']
    • 'cat' [1, 0, 0]
    • 'dog' [0, 1, 0]
    • 'rabbit' [0, 0, 1]
Deep Learning for Text with PyTorch

用 PyTorch 做 One-hot encoding

import torch
vocab = ['cat', 'dog', 'rabbit']

vocab_size = len(vocab)
one_hot_vectors = torch.eye(vocab_size)
one_hot_dict = {word: one_hot_vectors[i] for i, word in enumerate(vocab)}
print(one_hot_dict)
{'cat': tensor([1., 0., 0.]),
  'dog': tensor([0., 1., 0.]),
  'rabbit': tensor([0., 0., 1.])}
Deep Learning for Text with PyTorch

Bag-of-words

  • 範例:「The cat sat on the mat」
  • Bag-of-words
    • {'the': 2, 'cat': 1, 'sat': 1, 'on': 1, 'mat': 1}
  • 將每份文件視為無序的詞彙集合
  • 著重於「頻率」,不看順序
Deep Learning for Text with PyTorch

CountVectorizer

from sklearn.feature_extraction.text import CountVectorizer

vectorizer = CountVectorizer()
corpus = ['This is the first document.', 'This document is the second document.', 'And this is the third one.', 'Is this the first document?']
X = vectorizer.fit_transform(corpus)
print(X.toarray())
print(vectorizer.get_feature_names_out())
[[0 1 1 1 0 0 1 0 1]
 [0 2 0 1 0 1 1 0 1]
 [1 0 0 1 1 0 1 1 1]
 [0 1 1 1 0 0 1 0 1]]

['and' 'document' 'first' 'is' 'one' 'second' 'the' 'third' 'this']
Deep Learning for Text with PyTorch

TF-IDF

  • Term Frequency-Inverse Document Frequency
    • 衡量單字在文件中的重要性
    • 罕見詞得分較高
    • 常見詞得分較低
    • 強調具資訊性的詞
Deep Learning for Text with PyTorch

TfidfVectorizer

from sklearn.feature_extraction.text import TfidfVectorizer
vectorizer = TfidfVectorizer()

corpus = ['This is the first document.','This document is the second document.', 'And this is the third one.','Is this the first document?']
X = vectorizer.fit_transform(corpus)
print(X.toarray())
print(vectorizer.get_feature_names_out())
[[0.         0.         0.68091856 0.51785612 0.51785612 0.        ]
 [0.         0.         0.          0.51785612 0.51785612 0.68091856]
 [0.85151335 0.42575668 0.         0.32274454 0.32274454 0.        ]
 [0.         0.         0.68091856 0.51785612 0.51785612 0.        ]]

['and' 'document' 'first' 'is' 'one' 'second']
Deep Learning for Text with PyTorch

TfidfVectorizer

TFIDF 程式碼

Deep Learning for Text with PyTorch

編碼技術

技術:One-hot encoding、bag-of-words、TF-IDF

  • 讓模型能理解並處理文字
  • 選用一種技術以避免重複
  • 還有更多方法可用
Deep Learning for Text with PyTorch

一起來練習吧!

Deep Learning for Text with PyTorch

Preparing Video For Download...