如何在 RNN 模块中添加多个层以进行情感分析?火炬

青葱年少 pytorch 190

原文标题How to add multiple layers to an RNN module for sentiment analysis? Pytorch

我正在尝试使用 Pytorch(新手)创建情绪分析模型

import torch.nn as nn

class RNN(nn.Module):
 def __init__(self, input_dim, embedding_dim, hidden_dim, output_dim, dropout):
    super().__init__() #to call the functions in the superclass
    self.embedding = nn.Embedding(input_dim, embedding_dim) #Embedding layer to create dense vector instead of sparse matrix
    self.rnn = nn.RNN(embedding_dim, hidden_dim) 
    self.fc = nn.Linear(hidden_dim, output_dim)
    self.dropout = nn.Dropout(dropout)
    
def forward(self, text):
    embedded = self.embedding(text)
    output, hidden = self.rnn(embedded)   
    hidden = self.dropout(hidden[-1,:,:])
    nn.Sigmoid()
    return self.fc(hidden)

但是,准确度低于 50%,我想添加一个额外的层,也许是另一个线性,然后再将其馈送到最后一个线性以获得预测。我可以在 RNN 之后和最后一个 Linear 之前添加什么样的层?还有我应该用什么喂它?我试过简单地添加另一个

output, hidden= self.fc(hidden)

但我明白了

ValueError:要解包的值太多(预期为 2)

我相信这是因为前一层的激活和辍学的输出是不同的。非常感谢您的帮助。

谢谢

原文链接:https://stackoverflow.com//questions/71916899/how-to-add-multiple-layers-to-an-rnn-module-for-sentiment-analysis-pytorch

回复

我来回复
  • jhso的头像
    jhso 评论

    您非常接近,只需将您的转发呼叫更改为:

    import torch.nn.functional as F
    class model_RNN(nn.Module):
     def __init__(self, input_dim, embedding_dim, hidden_dim, output_dim, dropout):
        super().__init__() #to call the functions in the superclass
        self.embedding = nn.Embedding(input_dim, embedding_dim) #Embedding layer to create dense vector instead of sparse matrix
        self.rnn = nn.RNN(embedding_dim, hidden_dim) 
        self.hidden_fc = nn.Linear(hidden_dim,hidden_dim)
        self.out_fc = nn.Linear(hidden_dim, output_dim)
        self.dropout = nn.Dropout(dropout)
        
    def forward(self, text):
        embedded = self.embedding(text)
        output, hidden = self.rnn(embedded)   
        hidden = self.dropout(hidden[-1,:,:])
        hidden = F.relu(torch.self.hidden_fc(hidden))
        return self.out_fc(hidden)
    

    请注意,调用 nn.Sigmoid() 不会对您的模型输出做任何事情,因为它只会创建一个 sigmoid 层但不会在您的数据上调用它。你想要的可能是torch.sigmoid(self.fc(hidden))。虽然我会说它不是建议使用输出激活,因为一些常见的损失函数需要原始 logits。确保在 eval 模式下调用模型后应用 sigmoid!

    2年前 0条评论