文本数据编码

使用 PyTorch 的文本深度学习

Shubham Jain

Data Scientist

文本编码

Pytorch 处理流程

  • 将文本转为机器可读的数字
  • 支持分析与建模

顺序数据图以获取洞见

使用 PyTorch 的文本深度学习

编码技术

  • 独热编码:将词转换为唯一数值表示
  • 词袋(BoW):统计词频,忽略顺序
  • TF‑IDF:兼顾稀有度与重要性
  • 嵌入:将词映射为向量,捕捉语义(第2章)
使用 PyTorch 的文本深度学习

独热编码(One‑hot)

  • 将每个词映射到唯一向量
  • 二进制向量:
    • 出现为 1
    • 未出现为 0
  • ['cat', 'dog', 'rabbit']
    • 'cat' [1, 0, 0]
    • 'dog' [0, 1, 0]
    • 'rabbit' [0, 0, 1]
使用 PyTorch 的文本深度学习

用 PyTorch 实现独热编码

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 的文本深度学习

词袋模型

  • 示例: "The cat sat on the mat"
  • 词袋模型(Bag-of-Words):
    • {'the': 2, 'cat': 1, 'sat': 1, 'on': 1, 'mat': 1}
  • 将每个文档视为无序的词集合
  • 关注词频,不考虑顺序
使用 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']
使用 PyTorch 的文本深度学习

TF‑IDF

  • 词频-逆文档频率(TF‑IDF)
    • 评估词在文档中的重要性
    • 罕见词得分更高
    • 常见词得分更低
    • 强调信息量高的词
使用 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']
使用 PyTorch 的文本深度学习

TfidfVectorizer

TFIDF 代码

使用 PyTorch 的文本深度学习

编码技术

技术:独热编码、词袋、TF‑IDF

  • 使模型能够理解并处理文本
  • 仅选一种技术以避免冗余
  • 还有更多方法
使用 PyTorch 的文本深度学习

开始练习吧!

使用 PyTorch 的文本深度学习

Preparing Video For Download...