原文鏈接
PyTorch由于使用了強(qiáng)大的GPU加速的Tensor計(jì)算(類似numpy)和基于tape的autograd系統(tǒng)的深度神經(jīng)網(wǎng)絡(luò)。這使得今年一月份被開源的PyTorch成為了深度學(xué)習(xí)領(lǐng)域新流行框架,許多新的論文在發(fā)表過程中都加入了大多數(shù)人不理解的PyTorch代碼。這篇文章我們就來講述一下我對PyTorch代碼的理解,希望能幫助你閱讀PyTorch代碼。整個(gè)過程是基于賈斯汀·約翰遜的偉大教程。如果你想了解更多或者有超過10分鐘的時(shí)間,建議你去讀下整篇代碼。
PyTorch由4個(gè)主要包裝組成:
Torch:類似于Numpy的通用數(shù)組庫,可以在將張量類型轉(zhuǎn)換為(torch.cuda.TensorFloat)并在GPU上進(jìn)行計(jì)算。
torch.autograd:用于構(gòu)建計(jì)算圖形并自動獲取漸變的包
torch.nn:具有共同層和成本函數(shù)的神經(jīng)網(wǎng)絡(luò)庫
torch.optim:具有通用優(yōu)化算法(如SGD,Adam等)的優(yōu)化包
1.導(dǎo)入工具
你可以這樣導(dǎo)入PyTorch:
importtorch # arrays on GPUimporttorch.autogradasautograd #build a computational graphimporttorch.nnasnn # neural net libraryimporttorch.nn.functionalasF # most non-linearities are hereimporttorch.optimasoptim # optimizationpackage
2.torch數(shù)組取代了numpy ndarray - >在GPU支持下提供線性代數(shù)
第一個(gè)特色,PyTorch提供了一個(gè)像Numpy數(shù)組一樣的多維數(shù)組,當(dāng)數(shù)據(jù)類型被轉(zhuǎn)換為(torch.cuda.TensorFloat)時(shí),可以在GPU上進(jìn)行處理。這個(gè)數(shù)組和它的關(guān)聯(lián)函數(shù)是一般的科學(xué)計(jì)算工具。
從下面的代碼中,我們可以發(fā)現(xiàn),PyTorch提供的這個(gè)包的功能可以將我們常用的二維數(shù)組變成GPU可以處理的三維數(shù)組。這極大的提高了GPU的利用效率,提升了計(jì)算速度。
大家可以自己比較Torch和numpy,從而發(fā)現(xiàn)他們的優(yōu)缺點(diǎn)。
#2matricesofsize 2x3 into a 3d tensor 2x2x3d=[[[1.,2.,3.],[4.,5.,6.]],[[7.,8.,9.],[11.,12.,13.]]]d=torch.Tensor(d) # arrayfrompython listprint"shape of the tensor:",d.size()# the first index is the depthz=d[0]+d[1]print"adding up the two matrices of the 3d tensor:",zshapeofthe tensor: torch.Size([2,2,3])adding up the two matricesofthe 3d tensor:81012151719[torch.FloatTensorofsize 2x3]# a heavily used operation is reshapingoftensors using .view()print d.view(2,-1) #-1makes torch infer the second dim123456789111213[torch.FloatTensorofsize 2x6]
3.torch.autograd可以生成一個(gè)計(jì)算圖- >自動計(jì)算梯度
第二個(gè)特色是autograd包,其提供了定義計(jì)算圖的能力,以便我們可以自動計(jì)算漸變梯度。在計(jì)算圖中,一個(gè)節(jié)點(diǎn)是一個(gè)數(shù)組,邊(edge)是on數(shù)組的一個(gè)操作。要做一個(gè)計(jì)算圖,我們需要在(torch.aurograd.Variable())函數(shù)中通過包裝數(shù)組來創(chuàng)建一個(gè)節(jié)點(diǎn)。那么我們在這個(gè)節(jié)點(diǎn)上所做的所有操作都將被定義為邊,它們將是計(jì)算圖中新的節(jié)點(diǎn)。圖中的每個(gè)節(jié)點(diǎn)都有一個(gè)(node.data)屬性,它是一個(gè)多維數(shù)組和一個(gè)(node.grad)屬性,這是相對于一些標(biāo)量值的漸變(node.grad也是一個(gè).Variable())。在定義計(jì)算圖之后,我們可以使用單個(gè)命令(loss.backward())來計(jì)算圖中所有節(jié)點(diǎn)的損耗梯度。
使用torch.autograd.Variable()將張量轉(zhuǎn)換為計(jì)算圖中的節(jié)點(diǎn)。
使用x.data訪問其值。
使用x.grad訪問其漸變。
在.Variable()上執(zhí)行操作,繪制圖形的邊緣。
# d is a tensor not a node, to create a node based on it:x= autograd.Variable(d, requires_grad=True)print"the node's data is the tensor:", x.data.size()print"the node's gradient is empty at creation:", x.grad # the grad is empty right nowthe node's data is the tensor: torch.Size([2,2,3])the node's gradient is empty at creation: None#dooperation on the node to make a computational graphy= x+1z=x+ys=z.sum()print s.creator# calculate gradientss.backward()print"the variable now has gradients:",x.gradthe variable now has gradients: Variable containing:(0,.,.) =222222(1,.,.) =222222[torch.FloatTensorofsize 2x2x3]
4.torch.nn包含各種NN層(張量行的線性映射)+(非線性)-->
其作用是有助于構(gòu)建神經(jīng)網(wǎng)絡(luò)計(jì)算圖,而無需手動操縱張量和參數(shù),減少不必要的麻煩。
第三個(gè)特色是高級神經(jīng)網(wǎng)絡(luò)庫(torch.nn),其抽象出了神經(jīng)網(wǎng)絡(luò)層中的所有參數(shù)處理,以便于在通過幾個(gè)命令(例如torch.nn.conv)就很容易地定義NN。這個(gè)包也帶有流行的損失函數(shù)的功能(例如torch.nn.MSEloss)。我們首先定義一個(gè)模型容器,例如使用(torch.nn.Sequential)的層序列的模型,然后在序列中列出我們期望的層。這個(gè)高級神經(jīng)網(wǎng)絡(luò)庫也可以處理其他的事情,我們可以使用(model.parameters())訪問參數(shù)(Variable())
# linear transformationofa 2x5 matrix into a 2x3 matrixlinear_map=nn.Linear(5,3)print"using randomly initialized params:", linear_map.parametersusing randomly initialized params: 3)># data has2exampleswith5features and3targetdata=torch.randn(2,5) # trainingy=autograd.Variable(torch.randn(2,3)) # target# make a nodex=autograd.Variable(data, requires_grad=True)# apply transformation to a node creates a computational grapha=linear_map(x)z=F.relu(a)o=F.softmax(z)print"output of softmax as a probability distribution:", o.data.view(1,-1)# lossfunctionloss_func=nn.MSELoss() #instantiate lossfunctionL=loss_func(z,y) # calculateMSE loss between output and targetprint"Loss:", Loutputofsoftmaxasa probability distribution:0.20920.19790.59290.43430.30380.2619[torch.FloatTensorofsize 1x6]Loss: Variable containing:2.9838[torch.FloatTensorofsize1]
我們還可以通過子類(torch.nn.Module)定義自定義層,并實(shí)現(xiàn)接受(Variable())作為輸入的(forward())函數(shù),并產(chǎn)生(Variable())作為輸出。我們也可以通過定義一個(gè)時(shí)間變化的層來做一個(gè)動態(tài)網(wǎng)絡(luò)。
定義自定義層時(shí),需要實(shí)現(xiàn)2個(gè)功能:
_init_函數(shù)必須始終被繼承,然后層的所有參數(shù)必須在這里定義為類變量(self.x)
正向函數(shù)是我們通過層傳遞輸入的函數(shù),使用參數(shù)對輸入進(jìn)行操作并返回輸出。輸入需要是一個(gè)autograd.Variable(),以便pytorch可以構(gòu)建圖層的計(jì)算圖。
classLog_reg_classifier(nn.Module):? ? def__init__(self, in_size,out_size):super(Log_reg_classifier,self).__init__() #always call parent's init? ? ? ? self.linear=nn.Linear(in_size, out_size) #layer parameters? ? defforward(self,vect):returnF.log_softmax(self.linear(vect)) #
5.torch.optim也可以做優(yōu)化—>
我們使用torch.nn構(gòu)建一個(gè)nn計(jì)算圖,使用torch.autograd來計(jì)算梯度,然后將它們提供給torch.optim來更新網(wǎng)絡(luò)參數(shù)。
第四個(gè)特色是與NN庫一起工作的優(yōu)化軟件包(torch.optim)。該庫包含復(fù)雜的優(yōu)化器,如Adam,RMSprop等。我們定義一個(gè)優(yōu)化器并傳遞網(wǎng)絡(luò)參數(shù)和學(xué)習(xí)率(opt = torch.optim.Adam(model.parameters(),lr = learning_rate)),然后我們調(diào)用(opt.step())對我們的參數(shù)進(jìn)行近一步更新。
optimizer=optim.SGD(linear_map.parameters(),lr=1e-2) # instantiate optimizerwithmodel params + learning rate# epoch loop: we run following until convergenceoptimizer.zero_grad() # make gradients zeroL.backward(retain_variables=True)optimizer.step()print LVariable containing:2.9838[torch.FloatTensorofsize1]
建立神經(jīng)網(wǎng)絡(luò)很容易,但是如何協(xié)同工作并不容易。這是一個(gè)示例顯示如何協(xié)同工作:
# define modelmodel =Log_reg_classifier(10,2)# define lossfunctionloss_func=nn.MSELoss() # define optimizeroptimizer=optim.SGD(model.parameters(),lr=1e-1)# send data through modelinminibatchesfor10epochsforepochinrange(10):forminibatch, targetindata:? ? ? ? model.zero_grad() # pytorch accumulates gradients, making them zeroforeach minibatch? ? ? ? #forward pass? ? ? ? out=model(autograd.Variable(minibatch))? ? ? ? #backward pass? ? ? ? L=loss_func(out,target) #calculate loss? ? ? ? L.backward() # calculate gradients? ? ? ? optimizer.step() # make an update step
希望上述的介紹能夠幫你更好的閱讀PyTorch代碼。
本文由北郵@愛可可-愛生活老師推薦,阿里云云棲社區(qū)組織翻譯。
文章原標(biāo)題《Understand PyTorch code in 10 minutes》,
作者:Hamidreza Saghir,機(jī)器學(xué)習(xí)研究員-多倫多大學(xué)博士生 譯者:袁虎審閱:阿福
文章為簡譯,更為詳細(xì)的內(nèi)容,請查看原文