最近遇到低版本的pytorch向0.4.0版本遷移,最終找到一個比較好的講解
轉自:https://blog.csdn.net/sunqiande88/article/details/80172391
2018年4月25號,官方發佈Pytorch0.4.0版本,此版本除了支持Windows外,與之前的Pytorch版本也有諸多不同,主要表現在編程方面。因此該指南主要用來介紹Pytorch0.4.0代碼方面需要注意的地方:
1. 棄用Variables並與Tensors合併
之前版本,最終的輸入數據必須轉化爲Variable的形式,而在Pytorch0.4.0版中,torch.Tensor包括了torch.autograd.Variable,已經不需要轉化爲Variable的形式。
type()的功能也變了,它不會再返回數據的類型,需要用x.type()代替。
>>>x = torch.DoubleTensor([1, 1, 1])
>>>print(type(x))
“<class ‘torch.Tensor’>” #不再返回數據類型
>>>print(x.type())
“<class ‘torch.DoubleTensor’>” #能返回數據類型
- 1
- 2
- 3
- 4
- 5
2. 支持零維Tensors
>>>torch.tensor(3.1416).size()
Torch.Size([]) #零維張量
- 1
- 2
3. 棄用volatile
之前版本的volatitle=True 相當於requires_grad=False,一般用於測試的時候不需要進行梯度計算,這樣做能減少內存使用。新版中使用torch.no_grad()代替。
4.新增dtypes、devices和numpy風格的Tensor
如:device = torch.device(“cuda” if torch.cuda.is_available() else “cpu”),會依據你的計算機配置自動選擇CPU還是GPU運算。
用一個例子來對比Pytorch 0.4.0代碼上需要注意的地方:
0.3.1(老版本):
model = CNN()
if use_cuda:
model = model.cuda()
# 訓練
total_loss = 0
for input, target in train_loader:
input, target = Variable(input), Variable(target) #需轉化爲Variable
hidden = Variable(torch.zeros(*h_shape))
# 定義是否使用GPU
if use_cuda:
input, target, hidden = input.cuda(), target.cuda(), hidden.cuda()
...
# 獲得loss的值
total_loss += loss.data[0]
# 測試
for input, target in test_loader:
input = Variable(input, volatile=True)
if use_cuda:
...
...
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
0.4.0(新版本):
# 定義device,是否使用GPU,依據計算機配置自動會選擇
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
#用.to(device)來決定模型使用GPU還是CPU
model = CNN().to(device)
# 訓練
total_loss = 0
for input, target in train_loader:
#不需要轉化爲Variable,直接用Tensors作爲輸入,用.to(device)來決定使用GPU還是CPU
input, target = input.to(device), target.to(device)
hidden = input.new_zeros(*h_shape)
... # 獲得loss值,也與老版本不同
total_loss += loss.item()
# 測試
with torch.no_grad(): # 測試時不會進行梯度計算,節約內存
for input, target in test_loader:
...