Pytorch使用过程错误与解决 -汇总~
Pytorch使用過(guò)程錯(cuò)誤與解決
- error1:關(guān)鍵詞 copy tensor
- error2:關(guān)鍵詞 張量相加
- error3:關(guān)鍵詞 nn.Linear()的使用
- 報(bào)錯(cuò)1:
- 報(bào)錯(cuò)代碼:
- 錯(cuò)誤原因:
- 報(bào)錯(cuò)2:
- 報(bào)錯(cuò)代碼:
- 錯(cuò)誤原因:
- 解決辦法
- 錯(cuò)誤原因:
- 正確代碼
error1:關(guān)鍵詞 copy tensor
報(bào)錯(cuò)信息:
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).解決辦法1:
*** 當(dāng)轉(zhuǎn)換某個(gè)變量為tensor時(shí),盡量使用torch.as_tensor()***
解決辦法2:
*** 當(dāng)轉(zhuǎn)換某個(gè)變量x為tensor時(shí),盡量使用x.clone().detach() or x.clone().detach().requires_grad_(True) ***
error2:關(guān)鍵詞 張量相加
參考鏈接:
報(bào)錯(cuò)信息:
RuntimeError: The size of tensor a (3) must match the size of tensor b (4) at non-singleton dimension 1
解決辦法:
檢查張量維度!!!
error3:關(guān)鍵詞 nn.Linear()的使用
參考鏈接:
報(bào)錯(cuò)1:
報(bào)錯(cuò):RuntimeError: expected scalar type Long but found Float
報(bào)錯(cuò)代碼:
import torch import torch.nn as nn class Net(nn.Module):def __init__(self,state_dim,mid_dim,action_dim):super().__init__()self.net = nn.Sequential(nn.Linear(state_dim, mid_dim))def forward(self,state):res = self.net(state)return res net = Net(9,5,4) print(net) current_state = torch.tensor([0,0,0,0,0,0,0,0,0]) print(current_state.shape) action = net(current_state) print(action)結(jié)果: Net((net): Sequential((0): Linear(in_features=9, out_features=5, bias=True)) ) torch.Size([9]) torch.Size([9])錯(cuò)誤原因:
將一維張量轉(zhuǎn)換成二維張量后才能輸入
報(bào)錯(cuò)2:
報(bào)錯(cuò):RuntimeError: expected scalar type Float but found Long
報(bào)錯(cuò)代碼:
import torch import torch.nn as nn class Net(nn.Module):def __init__(self,state_dim,mid_dim,action_dim):super().__init__()self.net = nn.Sequential(nn.Linear(state_dim, mid_dim))def forward(self,state):res = self.net(state)return res net = Net(9,5,4) print(net) current_state = torch.tensor([0,0,0,0,0,0,0,0,0]) print(current_state.shape) current_state = current_state.view(1,9) print(current_state.shape) action = net(current_state) print(action) 結(jié)果: Net((net): Sequential((0): Linear(in_features=9, out_features=5, bias=True)) ) torch.Size([9]) torch.Size([1, 9])錯(cuò)誤原因:
傳入的張量數(shù)據(jù)類(lèi)型應(yīng)該為float32
解決辦法
錯(cuò)誤原因:
1、將張量轉(zhuǎn)為二維使用.view(1,shape)
2、指定張量數(shù)據(jù)類(lèi)型 dtype=torch.float32
正確代碼
import torch import torch.nn as nn class Net(nn.Module):def __init__(self,state_dim,mid_dim,action_dim):super().__init__()self.net = nn.Sequential(nn.Linear(state_dim, mid_dim))def forward(self,state):res = self.net(state)return res net = Net(9,5,4) print(net) current_state = torch.tensor([0,0,0,0,0,0,0,0,0],**dtype=torch.float32**) print(current_state.shape) **current_state = current_state.view(1,9)** print(current_state.shape) action = net(current_state) print(action)總結(jié)
以上是生活随笔為你收集整理的Pytorch使用过程错误与解决 -汇总~的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: Pytorch学习:Task4 PyTo
- 下一篇: Pytorch学习-torch.max(