Pytorch使用过程错误与解决 -汇总~
生活随笔
收集整理的這篇文章主要介紹了
Pytorch使用过程错误与解决 -汇总~
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
Pytorch使用過程錯誤與解決
- error1:關鍵詞 copy tensor
- error2:關鍵詞 張量相加
- error3:關鍵詞 nn.Linear()的使用
- 報錯1:
- 報錯代碼:
- 錯誤原因:
- 報錯2:
- 報錯代碼:
- 錯誤原因:
- 解決辦法
- 錯誤原因:
- 正確代碼
error1:關鍵詞 copy tensor
報錯信息:
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:
*** 當轉換某個變量為tensor時,盡量使用torch.as_tensor()***
解決辦法2:
*** 當轉換某個變量x為tensor時,盡量使用x.clone().detach() or x.clone().detach().requires_grad_(True) ***
error2:關鍵詞 張量相加
參考鏈接:
報錯信息:
RuntimeError: The size of tensor a (3) must match the size of tensor b (4) at non-singleton dimension 1
解決辦法:
檢查張量維度!!!
error3:關鍵詞 nn.Linear()的使用
參考鏈接:
報錯1:
報錯:RuntimeError: expected scalar type Long but found Float
報錯代碼:
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)結果: Net((net): Sequential((0): Linear(in_features=9, out_features=5, bias=True)) ) torch.Size([9]) torch.Size([9])錯誤原因:
將一維張量轉換成二維張量后才能輸入
報錯2:
報錯:RuntimeError: expected scalar type Float but found Long
報錯代碼:
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) 結果: Net((net): Sequential((0): Linear(in_features=9, out_features=5, bias=True)) ) torch.Size([9]) torch.Size([1, 9])錯誤原因:
傳入的張量數據類型應該為float32
解決辦法
錯誤原因:
1、將張量轉為二維使用.view(1,shape)
2、指定張量數據類型 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)總結
以上是生活随笔為你收集整理的Pytorch使用过程错误与解决 -汇总~的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Pytorch学习:Task4 PyTo
- 下一篇: Pytorch学习-torch.max(