テキストデータのエンコード

PyTorch で学ぶテキストの Deep Learning

Shubham Jain

Data Scientist

テキストのエンコード

PyTorch の処理パイプライン

  • テキストを機械可読な数値へ変換
  • 分析とモデリングを可能にする

連続データから洞察を得るエンコーダー画像

PyTorch で学ぶテキストの Deep Learning

エンコード手法

  • One-hot encoding: 単語を一意の数値表現に変換
  • Bag-of-Words (BoW): 語の頻度を取得、順序は無視
  • TF-IDF: 珍しさと重要度のバランス
  • 埋め込み (Embedding): 単語をベクトル化し意味を表現(第2章)
PyTorch で学ぶテキストの Deep Learning

One-hot encoding

  • 各単語を固有のベクトルに対応付ける
  • バイナリベクトル:
    • 単語があれば 1
    • なければ 0
  • ['cat', 'dog', 'rabbit']
    • 'cat' [1, 0, 0]
    • 'dog' [0, 1, 0]
    • 'rabbit' [0, 0, 1]
PyTorch で学ぶテキストの Deep Learning

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.])}
PyTorch で学ぶテキストの Deep Learning

Bag-of-words

  • : "The cat sat on the mat"
  • Bag-of-words:
    • {'the': 2, 'cat': 1, 'sat': 1, 'on': 1, 'mat': 1}
  • 各文書を順不同の語集合として扱う
  • 頻度に注目し、順序は無視
PyTorch で学ぶテキストの Deep Learning

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']
PyTorch で学ぶテキストの Deep Learning

TF-IDF

  • Term Frequency-Inverse Document Frequency
    • 文書内での語の重要度をスコア化
    • まれな語は高スコア
    • よくある語は低スコア
    • 情報量の高い語を強調
PyTorch で学ぶテキストの Deep Learning

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']
PyTorch で学ぶテキストの Deep Learning

TfidfVectorizer

TF-IDF のコード

PyTorch で学ぶテキストの Deep Learning

エンコード手法

手法: One-hot encoding、Bag-of-words、TF-IDF

  • モデルがテキストを理解・処理できるようにする
  • 冗長回避のため手法は1つ選ぶ
  • 他にも手法あり
PyTorch で学ぶテキストの Deep Learning

Laten we oefenen!

PyTorch で学ぶテキストの Deep Learning

Preparing Video For Download...