文本分类概览

使用 PyTorch 的文本深度学习

Shubham Jain

Instructor

文本分类定义

  • 为文本分配标签
  • 赋予词与句子以含义

 

 

机器学习中的分类类型

  • 为非结构化数据提供组织与结构
  • 应用:

    • 分析评价中的客户情感
    • 检测邮件垃圾
    • 给新闻打上相关主题标签
  • 类型:二分类、多分类、多标签

使用 PyTorch 的文本深度学习

二分类

  • 划分为两类
  • 例:邮件垃圾检测
  • 邮件可分为"垃圾"或"非垃圾"

二分类

1 https://storage.googleapis.com/gweb-cloudblog-publish/images/image4_v2LFcq0.max-1200x1200.png
使用 PyTorch 的文本深度学习

多分类

新闻分类

  • 划分为多个类别
  • 例:新闻可归入多种类别,如
    1. 政治
    2. 体育
    3. 科技
使用 PyTorch 的文本深度学习

多标签分类

  • 每个文本可分配多个标签
  • 例:图书可属多种体裁
    • 动作
    • 冒险
    • 奇幻
使用 PyTorch 的文本深度学习

什么是词向量

词向量管道

词向量示例

  • 之前的编码方法是良好起点
    • 往往特征过多,且难以识别相似词
  • 词向量将词映射为数值向量
  • 语义关系示例:
    • 国王 与 王后
    • 男性 与 女性
使用 PyTorch 的文本深度学习

词到索引映射

  • 示例:
    • "King" -> 1
    • "Queen" -> 2
  • 紧凑且计算高效
  • 在流水线中紧随分词之后
使用 PyTorch 的文本深度学习

PyTorch 中的词向量

  • torch.nn.Embedding
    • 由索引生成词向量

 

  • 输入:['The', 'cat', 'sat', 'on', 'the', 'mat'] 的索引
Embedding for 'the': tensor([-0.4689,  0.3164, -0.2971, -0.1291,  0.4064])
Embedding for 'cat': tensor([-0.0978, -0.4764,  0.0476,  0.1044, -0.3976])
Embedding for 'sat': tensor([ 0.2731,  0.4431,  0.1275,  0.1434, -0.4721])
使用 PyTorch 的文本深度学习

使用 torch.nn.Embedding

import torch
from torch import nn

words = ["The", "cat", "sat", "on", "the", "mat"] word_to_idx = {word: i for i, word in enumerate(words)}
inputs = torch.LongTensor([word_to_idx[w] for w in words])
embedding = nn.Embedding(num_embeddings=len(words), embedding_dim=10)
output = embedding(inputs)
print(output)
tensor([[ 1.0624,  0.6792,  0.0459,  ... -1.0828, -0.4475,  0.4868],
         ...
         [1.5766,  0.0106,  0.1161,  ...,,  -0.0859, 1.3160,  1.3621])
使用 PyTorch 的文本深度学习

在流水线中使用嵌入

def preprocess_sentences(text):
  # Tokenization
  # Stemming
  ...

# Word to index mapping
class TextDataset(Dataset): def __init__(self, encoded_sentences): self.data = encoded_sentences def __len__(self): return len(self.data) def __getitem__(self, index): return self.data[index]
def text_processing_pipeline(text):
    tokens = preprocess_sentences(text)
    dataset = TextDataset(tokens)
    dataloader = DataLoader(dataset, batch_size=2, 
                            shuffle=True)
    return dataloader, vectorizer

text = "Your sample text here." dataloader, vectorizer = text_processing_pipeline(text)
embedding = nn.Embedding(num_embeddings=10, embedding_dim=50) for batch in dataloader: output = embedding(batch) print(output)
使用 PyTorch 的文本深度学习

Passons à la pratique !

使用 PyTorch 的文本深度学习

Preparing Video For Download...