文字分類概觀

Deep Learning for Text with PyTorch

Shubham Jain

Instructor

文字分類定義

  • 為文字指派標籤
  • 賦予詞句意義

 

 

機器學習中的分類類型

  • 為非結構化資料建立結構
  • 應用:

    • 解析評論中的顧客情緒
    • 偵測電子郵件垃圾信
    • 為新聞加上主題標籤
  • 類型:二元、多類別、多標籤

Deep Learning for Text with PyTorch

二元分類

  • 分成兩類
  • 範例:電子郵件垃圾信偵測
  • 電子郵件可分為「spam」或「not spam

二元分類

1 https://storage.googleapis.com/gweb-cloudblog-publish/images/image4_v2LFcq0.max-1200x1200.png
Deep Learning for Text with PyTorch

多類別分類

新聞分類

  • 分成多個類別
  • 範例:新聞文章 可分類為
    1. Politics
    2. Sports
    3. Technology
Deep Learning for Text with PyTorch

多標籤分類

  • 每段文字可有多個標籤
  • 範例:書籍 可同時屬於多種體裁
    • 動作
    • 冒險
    • 奇幻
Deep Learning for Text with PyTorch

什麼是詞向量

詞向量流程

詞向量範例

  • 先前編碼法是良好起點
    • 但特徵過多,且難以辨識相似詞
  • 詞向量將單詞映射到數值向量
  • 語意關係範例:
    • King 與 queen
    • Man 與 woman
Deep Learning for Text with PyTorch

字詞到索引映射

  • 範例:
    • "King" -> 1
    • "Queen" -> 2
  • 精簡且計算有效率
  • 在流程中接在分詞之後
Deep Learning for Text with 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])
Deep Learning for Text with 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])
Deep Learning for Text with 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)
Deep Learning for Text with PyTorch

一起來練習吧!

Deep Learning for Text with PyTorch

Preparing Video For Download...