用于文本分类的卷积神经网络

使用 PyTorch 的文本深度学习

Shubham Jain

Instructor

用于文本分类的 CNN

  • 将推文分类为
    • 积极
    • 消极
    • 中性
使用 PyTorch 的文本深度学习

卷积操作

卷积操作

  • 卷积操作
    • 在输入上滑动滤波器(核)
    • 每个位置执行逐元素计算

 

  • 针对文本:学习词的结构与含义
1 动画来自 Vincent Dumoulin、Francesco Visin
使用 PyTorch 的文本深度学习

CNN 中的滤波器与步幅

  • 滤波器:
    • 在输入上滑动的小矩阵

 

  • 步幅:
    • 滤波器每次移动的格数

滤波器与步幅

1 动画来自 Vincent Dumoulin、Francesco Visin
使用 PyTorch 的文本深度学习

文本的 CNN 架构

  • 卷积层:对输入应用滤波器
  • 池化层:在保留关键信息的同时降采样
  • 全连接层:基于上一层输出做最终预测
使用 PyTorch 的文本深度学习

用 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) ...
  • __init__ 方法配置模型结构
  • super() 初始化基类 nn.Module
  • nn.Embedding 生成稠密词向量
  • nn.Conv1d 处理一维数据
使用 PyTorch 的文本深度学习

用 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)
  • 嵌入层将文本转为向量
  • 调整张量以匹配卷积层输入
  • 用 ReLU 提取重要特征
  • 去除多余层级与维度
使用 PyTorch 的文本深度学习

为情感分析模型准备数据

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)
使用 PyTorch 的文本深度学习

训练模型

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()
使用 PyTorch 的文本深度学习

运行情感分析模型

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

Passons à la pratique !

使用 PyTorch 的文本深度学习

Preparing Video For Download...