Mạng nơ-ron tích chập cho phân loại văn bản

Deep Learning cho Văn bản với PyTorch

Shubham Jain

Instructor

CNN cho phân loại văn bản

  • Phân loại tweet thành
    • Tích cực
    • Tiêu cực
    • Trung tính
Deep Learning cho Văn bản với PyTorch

Phép tích chập

Phép tích chập

  • Phép tích chập
    • Trượt bộ lọc (kernel) trên dữ liệu đầu vào
    • Ở mỗi vị trí, tính theo phần tử

 

  • Với văn bản: học cấu trúc và nghĩa của từ
1 Hoạt ảnh từ Vincent Dumoulin, Francesco Visin
Deep Learning cho Văn bản với PyTorch

Bộ lọc và bước trượt trong CNN

  • Bộ lọc:
    • Ma trận nhỏ trượt trên đầu vào

 

  • Bước trượt (stride):
    • Số vị trí bộ lọc di chuyển

Bộ lọc và bước trượt

1 Hoạt ảnh từ Vincent Dumoulin, Francesco Visin
Deep Learning cho Văn bản với PyTorch

Kiến trúc CNN cho văn bản

  • Lớp tích chập: áp dụng bộ lọc lên dữ liệu đầu vào
  • Lớp gộp: giảm kích thước, giữ thông tin chính
  • Lớp kết nối đầy đủ: dự đoán cuối dựa trên đầu ra trước đó
Deep Learning cho Văn bản với PyTorch

Xây dựng mô hình phân loại văn bản bằng CNN

class SentimentAnalysisCNN(nn.Module):

def __init__(self, vocab_size, embed_dim):
super().__init__()
self.embedding = nn.Embedding(vocab_size, embed_dim)
self.conv = nn.Conv1d(embed_dim, embed_dim, kernel_size=3, stride=1, padding=1)
self.fc = nn.Linear(embed_dim, 2) ...
  • Phương thức __init__ cấu hình kiến trúc
  • super() khởi tạo lớp cơ sở nn.Module
  • nn.Embedding tạo vector từ dày
  • nn.Conv1d cho dữ liệu một chiều
Deep Learning cho Văn bản với PyTorch

Xây dựng mô hình phân loại văn bản bằng CNN

    ...
    def forward(self, text):
        embedded = self.embedding(text).permute(0, 2, 1)

conved = F.relu(self.conv(embedded))
conved = conved.mean(dim=2)
return self.fc(conved)
  • Lớp embedding chuyển văn bản thành embedding
  • Căn chỉnh tensor với đầu vào mong đợi của tích chập
  • Trích đặc trưng bằng ReLU
  • Loại bỏ chiều dư thừa
Deep Learning cho Văn bản với PyTorch

Chuẩn bị dữ liệu cho mô hình phân tích cảm xúc

vocab = ["i", "love", "this", "book", "do", "not", "like"]
word_to_idx = {word: i for i, word in enumerate(vocab)}

vocab_size = len(word_to_ix)
embed_dim = 10
book_samples = [ ("The story was captivating and kept me hooked until the end.".split(),1), ("I found the characters shallow and the plot predictable.".split(),0) ]
model = SentimentAnalysisCNN(vocab_size, embed_dim) criterion = nn.CrossEntropyLoss() optimizer = optim.SGD(model.parameters(), lr=0.1)
Deep Learning cho Văn bản với PyTorch

Huấn luyện mô hình

for epoch in range(10):  
    for sentence, label in data:

model.zero_grad()
sentence = torch.LongTensor([word_to_idx.get(w, 0) for w in sentence]).unsqueeze(0)
outputs = model(sentence) label = torch.LongTensor([int(label)])
loss = criterion(outputs, label) loss.backward()
optimizer.step()
Deep Learning cho Văn bản với PyTorch

Chạy mô hình phân tích cảm xúc

for sample in book_samples:

input_tensor = torch.tensor([word_to_idx[w] for w in sample], dtype=torch.long).unsqueeze(0)
outputs = model(input_tensor)
_, predicted_label = torch.max(outputs.data, 1)
sentiment = "Positive" if predicted_label.item() == 1 else "Negative"
print(f"Book Review: {' '.join(sample)}") print(f"Sentiment: {sentiment}\n")
Book Review: The story was captivating and kept me hooked until the end
Sentiment: Positive
Book Review: I found the characters shallow and the plot predictable
Sentiment: Negative
Deep Learning cho Văn bản với PyTorch

Ayo berlatih!

Deep Learning cho Văn bản với PyTorch

Preparing Video For Download...