【发布时间】:2020-11-23 02:52:39
【问题描述】:
我将给出一组上下文无关的代码。该代码在添加“to(设备)”之前有效。
def get_input_layer(word_idx) :
x = torch.zeros(vocabulary_size).float().to(device)
x[word_idx] = 1.0
return x
embedding_dims = 5
device = torch.device("cuda:0")
W1 = Variable(torch.randn(embedding_dims, vocabulary_size).float(), requires_grad=True).to(device)
W2 = Variable(torch.randn(vocabulary_size, embedding_dims).float(), requires_grad=True).to(device)
num_epochs = 100
learning_rate = 0.001
x = Variable(get_input_layer(data)).float().to(device)
y_true = Variable(torch.from_numpy(np.array([target])).long()).to(device)
z1 = torch.matmul(W1, x).to(device)
z2 = torch.matmul(W2, z1).to(device)
log_softmax = F.log_softmax(z2, dim=0).to(device)
loss = F.nll_loss(log_softmax.view(1,-1), y_true).to(device)
loss_val += loss.data
loss.backward().to(device)
## Optimize values. This is done by hand rather than using the optimizer function
W1.data -= learning_rate * W1.grad.data
W2.data -= learning_rate * W2.grad.data
我明白了
Traceback (most recent call last):
File "<input>", line 1, in <module>
AttributeError: 'NoneType' object has no attribute 'data'
具体触发就行了
W1.data -= learning_rate * W1.grad.data
检查,这已确认,因为 W1.grad 出于某种原因是 None。
这会在清除渐变后循环。如果我删除所有 .to(device),这会很好。我试图在我的 GPU 上运行它时做错了什么?
感谢您的宝贵时间。
【问题讨论】:
标签: python neural-network pytorch gradient