Pytorch 我遇到了一个问题,那就是;运行时错误:输入和隐藏张量不在同一设备上,在cuda处发现输入张量:0,在cpu处发现隐藏张量;
我猜隐藏张量是我需要在RNN开头初始化的基调。因此,我通过.cuda()设置了h0和c0,但这并不有用。下面是我的密码。请问,谁能帮我一下Pytorch 我遇到了一个问题,那就是;运行时错误:输入和隐藏张量不在同一设备上,在cuda处发现输入张量:0,在cpu处发现隐藏张量;,pytorch,lstm,recurrent-neural-network,Pytorch,Lstm,Recurrent Neural Network,我猜隐藏张量是我需要在RNN开头初始化的基调。因此,我通过.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.Embeddin
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
起初,我认为您在将.cuda()包装到变量中之前没有将其放入的错误如下所述: 但是,您在初始化时已正确地对其进行了转换,并将其包装到变量中。你的小错误在于你的循环。在您的if语句中,当您使用GPU时,不会激活cuda,而是在else循环中激活cuda。不管有没有GPU,它都会失败 与其纠正你的if-else,不如我建议你推荐的方法:
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
class LSTM_net(nn.Module):
...
...
def init_hidden(self, batch):
return (autograd.Variable(torch.zeros(1, batch, self.Hidden_dim).to(device)),
autograd.Variable(torch.zeros(1, batch, self.Hidden_dim).to(device)))
使用.to(设备)可以避免大多数设备错误。错误可能源于代码的执行方式。您可能会遇到这个问题,因为您在一台具有GPU的机器上运行此代码,该GPU强制隐藏的张量为
cuda
tensor。但是,在主代码中执行时,如果给cpu输入张量,pytorch将引发不匹配错误。为防止出现这种情况,请按以下所述进行更改
def转发(self,句子):
# 64 * 52
x=自嵌入(句子)
#x=64*52*32
x=x.permute(1,0,2).cuda()#您能否分享您正在定义LSTM_net对象并训练模型的代码部分?这是否回答了您的问题?你能解决这个问题吗?我也犯了同样的错误。