【发布时间】:2020-05-01 22:37:24
【问题描述】:
我猜隐藏张量是我需要在 RNN 开始时初始化的 Tenor。所以我通过 .cuda() 设置了 h0 和 c0,但这没有用。以下是我的代码。请问谁能帮帮我?
class LSTM_net(nn.Module):
def __init__(self, Embedding, vocab, label, batch):
super(LSTM_net, self).__init__()
self.Hidden_dim = Embedding
self.Embedding = nn.Embedding(vocab, Embedding)
self.lstm = nn.LSTM(Embedding, self.Hidden_dim) # 32 * 32
self.hidden2label = nn.Linear(Embedding, label)
self.hidden = self.init_hidden(batch)
def init_hidden(self, batch):
# the first is the hidden h
# the second is the cell c
if torch.cuda.is_available():
return (autograd.Variable(torch.zeros(1, batch, self.Hidden_dim)),
autograd.Variable(torch.zeros(1, batch, self.Hidden_dim)))
else:
return (autograd.Variable(torch.zeros(1, batch, self.Hidden_dim).cuda()),
autograd.Variable(torch.zeros(1, batch, self.Hidden_dim).cuda()))
def forward(self, sentence):
# 64 * 52
x = self.Embedding(sentence)
# x = 64 * 52 * 32
x = x.permute(1, 0, 2)
# x = 52 * 64 * 32
lstm_y, lstm_hidden = self.lstm(x, self.hidden)
# lstm_y = batch * 52 * 32
# input: lstm_y[-1] = batch * 32
y = self.hidden2label(lstm_y[-1])
# y = batch * 5
log_probs = F.log_softmax(y)
return log_probs
【问题讨论】:
-
你能分享一下你定义
LSTM_net对象和训练模型的代码部分吗? -
你能解决这个问题吗?我遇到了同样的错误。
标签: pytorch lstm recurrent-neural-network