pytorch安装完后import不了_使用新版PyTorch运行《动手学深度学习》中的代码
更新中~PyTorch版《动手学深度学习》中提供的代码在最新版本pytorch上会报错。这里记录一下debug。第三章代码报错记录3.2节1、RuntimeError: Expected object of scalar type Double but got scalar type Float for argument #2 'mat2'解决:def linreg(X, w, b):# 本函..
更新中~
PyTorch版《动手学深度学习》中提供的代码在最新版本pytorch上会报错。这里记录一下debug。
第三章代码报错记录
3.2节
1、RuntimeError: Expected object of scalar type Double but got scalar type Float for argument #2 'mat2'
解决:
def linreg(X, w, b): # 本函数已保存在d2lzh_pytorch包中⽅便以后使用
X = torch.tensor(X, dtype=torch.float32)
return torch.mm(X, w) + b
2、UserWarning: To copy construct from a tensor, it is recommended to use sourceTensor.clone().detach() or sourceTensor.clone().detach().requires_grad_(True), rather than torch.tensor(sourceTensor).
解决:
#w = torch.tensor(np.random.normal(0, 0.01, (num_inputs, 1)), dtype=torch.float32)
w = torch.as_tensor(np.random.normal(0, 0.01, (num_inputs, 1)), dtype=torch.float32)
b = torch.zeros(1, dtype=torch.float32)
3.3节
3、RuntimeError: Expected object of scalar type Float but got scalar type Double for argument #2 'mat1' in call to _th_addmm
RuntimeError: Expected object of scalar type Float but got scalar type Double for argument #2 'target' in call to _thnn_mse_loss_forward
解决:修改训练模型部分的代码。
num_epochs = 3
for epoch in range(1, num_epochs + 1):
for X, y in data_iter:
#在代码前添加一行,将输入的数据转成是dtype=torch.float32的。
#X= torch.tensor(X, dtype=torch.float32)
X=X.clone().detach().float()
output = net(X)
y = torch.tensor(y, dtype=torch.float32)
l = loss(output, y.view(-1, 1))
optimizer.zero_grad() # 梯度清零,等价于net.zero_grad()
l.backward()
optimizer.step()
print('epoch %d, loss: %f' % (epoch, l.item()))
第四章代码报错记录
4.4节
4、NameError: name 'MyListDense' is not defined
解决:代码修改如下
net = nn.Sequential( MyDictDense(),MyDense(),)
#net = nn.Sequential( MyDictDense(),MyListDense(),)
print(net)
print(net(x))
第五章代码报错记录
5.8节
5、报错内容为:type object 'F' has no attribute 'avg_pool2d',或 name 'F' is not defined。
解决:
import torch.nn.functional as F
更多推荐
所有评论(0)