- 特性
pytorch的第一大特性是其能與numpy無縫對(duì)接轉(zhuǎn)換
np_data = np.arange(6).reshape((2, 3)) #創(chuàng)建一個(gè)numpy數(shù)組
torch_data = torch.from_numpy(np_data) #將numpy轉(zhuǎn)換為torch tensor
tensor2array = torch_data.numpy() #將torch tensor 轉(zhuǎn)換為numpy
Variable 存放變化的值
import torch
from torch.autograd import Variable
tensor = torch.FloatTensor([[1,2],[3,4]])
variable = Variable(tensor, requires_grad=True) #requires_grad是參不參與誤差反向傳播, 要不要計(jì)算梯度
variable.data # 將Variable轉(zhuǎn)成tensor 形式
variable.data.numpy() # 將Variable轉(zhuǎn)成numpy形式
- 常用函數(shù)
torch.Tensor.view() 作用同numpy中的reshape辱揭,用來改變數(shù)組的結(jié)構(gòu)
x = torch.randn(4, 4)
# torch.Size([4, 4])
z = x.view(-1, 8) # the size -1 is inferred from other dimensions
z.size()
# torch.Size([2, 8])
- 示例
這個(gè)是簡(jiǎn)單的網(wǎng)絡(luò)分類的代碼,下面的博文對(duì)其進(jìn)行了解析
https://github.com/MorvanZhou/PyTorch-Tutorial/blob/master/tutorial-contents/302_classification.py
net = Net(n_feature=2, n_hidden=10, n_output=2)調(diào)試的時(shí)候看到是在這步自動(dòng)完成權(quán)重初始化的
在調(diào)用交叉熵?fù)p失函數(shù)時(shí)箱沦,CrossEntropyLoss的默認(rèn)輸入時(shí)logit,out是沒有被softmax激活output
loss_func = torch.nn.CrossEntropyLoss()
loss = loss_func(out, y)
未完待續(xù)抚岗。。鱼鼓。
參考資料
- 關(guān)于pytorchGPU使用的討論帖
- BCEWithLogitsLoss解釋
https://blog.csdn.net/qq_22210253/article/details/85222093 - pytorch官網(wǎng) https://pytorch.org/tutorials/