建立用於文字的 CNN 模型
PyBooks 已成功建立書籍推薦引擎。下一步是實作情緒分析模型,用來理解使用者評論,並深入掌握書籍偏好。
你將使用 卷積神經網路(CNN)模型,根據情緒將文字資料(書評)做分類。
torch、torch.nn 為 nn,以及 torch.nn.functional 為 F 已為你載入。
本練習屬於課程
Deep Learning for Text with PyTorch
練習說明
- 在
__init__()方法中初始化嵌入層(embedding layer)。 - 在
forward()方法內,將卷積層self.conv套用到embedded文字上。 - 在
forward()方法內,對這一層套用 ReLU 啟用函式。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
class TextClassificationCNN(nn.Module):
def __init__(self, vocab_size, embed_dim):
super(TextClassificationCNN, self).__init__()
# Initialize the embedding layer
self.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)
def forward(self, text):
embedded = self.embedding(text).permute(0, 2, 1)
# Pass the embedded text through the convolutional layer and apply a ReLU
conved = ____.____(self.conv(____))
conved = conved.mean(dim=2)
return self.fc(conved)