开始使用免费开始使用

构建用于文本的 CNN 模型

PyBooks 已成功构建了一套图书推荐引擎。下一步任务是实现情感分析模型,以理解用户评论并洞察图书偏好。

您将使用卷积神经网络(CNN)对文本数据(图书评论)按情感进行分类。

torchtorch.nn(简称 nn)以及 torch.nn.functional(简称 F)已为您加载。

本练习是课程的一部分

使用 PyTorch 的文本深度学习

查看课程

练习说明

  • __init__() 方法中初始化嵌入层。
  • 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)
编辑并运行代码