如何從TensorFlow轉(zhuǎn)入PyTorch
當(dāng)我第一次嘗試學(xué)習(xí) PyTorch 時(shí),沒(méi)幾天就放棄了。和 TensorFlow 相比,我很難弄清 PyTorch 的核心要領(lǐng)。但是隨后不久,PyTorch 發(fā)布了一個(gè)新版本,我決定重新來(lái)過(guò)。在第二次的學(xué)習(xí)中,我開(kāi)始了解這個(gè)框架的易用性。在本文中,我會(huì)簡(jiǎn)要解釋 PyTorch 的核心概念,為你轉(zhuǎn)入這個(gè)框架提供一些必要的動(dòng)力。其中包含了一些基礎(chǔ)概念,以及先進(jìn)的功能如學(xué)習(xí)速率調(diào)整、自定義層等等。
PyTorch 的易用性如何?Andrej Karpathy 是這樣評(píng)價(jià)的
資源
- 首先要知道的是:PyTorch 的主目錄和教程是分開(kāi)的。而且因?yàn)殚_(kāi)發(fā)和版本更新的速度過(guò)快,有時(shí)候兩者之間并不匹配。所以你需要不時(shí)查看源代碼:http://pytorch.org/tutorials/。
- 當(dāng)然,目前網(wǎng)絡(luò)上已有了一些 PyTorch 論壇,你可以在其中詢問(wèn)相關(guān)的問(wèn)題,并很快得到回復(fù):https://discuss.pytorch.org/。
把 PyTorch 當(dāng)做 NumPy 用
讓我們先看看 PyTorch 本身,其主要構(gòu)件是張量——這和 NumPy 看起來(lái)差不多。這種性質(zhì)使得 PyTorch 可支持大量相同的 API,所以有時(shí)候你可以把它用作是 NumPy 的替代品。PyTorch 的開(kāi)發(fā)者們這么做的原因是希望這種框架可以完全獲得 GPU 加速帶來(lái)的便利,以便你可以快速進(jìn)行數(shù)據(jù)預(yù)處理,或其他任何機(jī)器學(xué)習(xí)任務(wù)。將張量從 NumPy 轉(zhuǎn)換至 PyTorch 非常容易,反之亦然。讓我們看看如下代碼:
- importtorch
- importnumpy asnp
- numpy_tensor =np.random.randn(10,20)
- # convert numpy array to pytorch array
- pytorch_tensor =torch.Tensor(numpy_tensor)
- # or another way
- pytorch_tensor =torch.from_numpy(numpy_tensor)
- # convert torch tensor to numpy representation
- pytorch_tensor.numpy()
- # if we want to use tensor on GPU provide another type
- dtype =torch.cuda.FloatTensor
- gpu_tensor =torch.randn(10,20).type(dtype)
- # or just call `cuda()` method
- gpu_tensor =pytorch_tensor.cuda()
- # call back to the CPU
- cpu_tensor =gpu_tensor.cpu()
- # define pytorch tensors
- x =torch.randn(10,20)
- y =torch.ones(20,5)
- # `@` mean matrix multiplication from python3.5, PEP-0465
- res =x @y
- # get the shape
- res.shape # torch.Size([10, 5])
從張量到變量
張量是 PyTorch 的一個(gè)完美組件,但是要想構(gòu)建神經(jīng)網(wǎng)絡(luò)這還遠(yuǎn)遠(yuǎn)不夠。反向傳播怎么辦?當(dāng)然,我們可以手動(dòng)實(shí)現(xiàn)它,但是真的需要這樣做嗎?幸好還有自動(dòng)微分。為了支持這個(gè)功能,PyTorch 提供了變量,它是張量之上的封裝。如此,我們可以構(gòu)建自己的計(jì)算圖,并自動(dòng)計(jì)算梯度。每個(gè)變量實(shí)例都有兩個(gè)屬性:包含初始張量本身的.data,以及包含相應(yīng)張量梯度的.grad
- importtorch
- fromtorch.autograd importVariable
- # define an inputs
- x_tensor =torch.randn(10,20)
- y_tensor =torch.randn(10,5)
- x =Variable(x_tensor,requires_grad=False)
- y =Variable(y_tensor,requires_grad=False)
- # define some weights
- w =Variable(torch.randn(20,5),requires_grad=True)
- # get variable tensor
- print(type(w.data))# torch.FloatTensor
- # get variable gradient
- print(w.grad)# None
- loss =torch.mean((y -x @w)**2)
- # calculate the gradients
- loss.backward()
- print(w.grad)# some gradients
- # manually apply gradients
- w.data -=0.01*w.grad.data
- # manually zero gradients after update
- w.grad.data.zero_()
你也許注意到我們手動(dòng)計(jì)算了自己的梯度,這樣看起來(lái)很麻煩,我們能使用優(yōu)化器嗎?當(dāng)然。
- importtorch
- fromtorch.autograd importVariable
- importtorch.nn.functional asF
- x =Variable(torch.randn(10,20),requires_grad=False)
- y =Variable(torch.randn(10,3),requires_grad=False)
- # define some weights
- w1 =Variable(torch.randn(20,5),requires_grad=True)
- w2 =Variable(torch.randn(5,3),requires_grad=True)
- learning_rate =0.1
- loss_fn =torch.nn.MSELoss()
- optimizer =torch.optim.SGD([w1,w2],lr=learning_rate)
- forstep inrange(5):
- pred =F.sigmoid(x @w1)
- pred =F.sigmoid(pred @w2)
- loss =loss_fn(pred,y)
- # manually zero all previous gradients
- optimizer.zero_grad()
- # calculate new gradients
- loss.backward()
- # apply new gradients
- optimizer.step()
并不是所有的變量都可以自動(dòng)更新。但是你應(yīng)該可以從最后一段代碼中看到重點(diǎn):我們?nèi)匀恍枰谟?jì)算新梯度之前將它手動(dòng)歸零。這是 PyTorch 的核心理念之一。有時(shí)我們會(huì)不太明白為什么要這么做,但另一方面,這樣可以讓我們充分控制自己的梯度。
靜態(tài)圖 vs 動(dòng)態(tài)圖
PyTorch 和 TensorFlow 的另一個(gè)主要區(qū)別在于其不同的計(jì)算圖表現(xiàn)形式。TensorFlow 使用靜態(tài)圖,這意味著我們是先定義,然后不斷使用它。在 PyTorch 中,每次正向傳播都會(huì)定義一個(gè)新計(jì)算圖。在開(kāi)始階段,兩者之間或許差別不是很大,但動(dòng)態(tài)圖會(huì)在你希望調(diào)試代碼,或定義一些條件語(yǔ)句時(shí)顯現(xiàn)出自己的優(yōu)勢(shì)。就像你可以使用自己最喜歡的 debugger 一樣!
你可以比較一下 while 循環(huán)語(yǔ)句的下兩種定義——第一個(gè)是 TensorFlow 中,第二個(gè)是 PyTorch 中:
- importtensorflow astf
- first_counter =tf.constant(0)
- second_counter =tf.constant(10)
- some_value =tf.Variable(15)
- # condition should handle all args:
- defcond(first_counter,second_counter,*args):
- returnfirst_counter <second_counter
- defbody(first_counter,second_counter,some_value):
- first_counter =tf.add(first_counter,2)
- second_counter =tf.add(second_counter,1)
- returnfirst_counter,second_counter,some_value
- c1,c2,val =tf.while_loop(
- cond,body,[first_counter,second_counter,some_value])
- withtf.Session()assess:
- sess.run(tf.global_variables_initializer())
- counter_1_res,counter_2_res =sess.run([c1,c2])
- importtorch
- first_counter =torch.Tensor([0])
- second_counter =torch.Tensor([10])
- some_value =torch.Tensor(15)
- while(first_counter <second_counter)[0]:
- first_counter +=2
- second_counter +=1
看起來(lái)第二種方法比第一個(gè)簡(jiǎn)單多了,你覺(jué)得呢?
模型定義
現(xiàn)在我們看到,想在 PyTorch 中創(chuàng)建 if/else/while 復(fù)雜語(yǔ)句非常容易。不過(guò)讓我們先回到常見(jiàn)模型中,PyTorch 提供了非常類似于 Keras 的、即開(kāi)即用的層構(gòu)造函數(shù):
神經(jīng)網(wǎng)絡(luò)包(nn)定義了一系列的模塊,它可以粗略地等價(jià)于神經(jīng)網(wǎng)絡(luò)的層。模塊接收輸入變量并計(jì)算輸出變量,但也可以保存內(nèi)部狀態(tài),例如包含可學(xué)習(xí)參數(shù)的變量。nn 包還定義了一組在訓(xùn)練神經(jīng)網(wǎng)絡(luò)時(shí)常用的損失函數(shù)。
- fromcollections importOrderedDict
- importtorch.nn asnn
- # Example of using Sequential
- model =nn.Sequential(
- nn.Conv2d(1,20,5),
- nn.ReLU(),
- nn.Conv2d(20,64,5),
- nn.ReLU()
- )
- # Example of using Sequential with OrderedDict
- model =nn.Sequential(OrderedDict([
- ('conv1',nn.Conv2d(1,20,5)),
- ('relu1',nn.ReLU()),
- ('conv2',nn.Conv2d(20,64,5)),
- ('relu2',nn.ReLU())
- ]))
- output =model(some_input)
如果你想要構(gòu)建復(fù)雜的模型,我們可以將 nn.Module 類子類化。當(dāng)然,這兩種方式也可以互相結(jié)合。
- fromtorch importnn
- classModel(nn.Module):
- def__init__(self):
- super().__init__()
- self.feature_extractor =nn.Sequential(
- nn.Conv2d(3,12,kernel_size=3,padding=1,stride=1),
- nn.Conv2d(12,24,kernel_size=3,padding=1,stride=1),
- )
- self.second_extractor =nn.Conv2d(
- 24,36,kernel_size=3,padding=1,stride=1)
- defforward(self,x):
- x =self.feature_extractor(x)
- x =self.second_extractor(x)
- # note that we may call same layer twice or mode
- x =self.second_extractor(x)
- returnx
在__init__方法中,我們需要定義之后需要使用的所有層。在正向方法中,我們需要提出如何使用已經(jīng)定義的層的步驟。而在反向傳播上,和往常一樣,計(jì)算是自動(dòng)進(jìn)行的。
自定義層
如果我們想要定義一些非標(biāo)準(zhǔn)反向傳播模型要怎么辦?這里有一個(gè)例子——XNOR 網(wǎng)絡(luò):
在這里我們不會(huì)深入細(xì)節(jié),如果你對(duì)它感興趣,可以參考一下原始論文:
https://arxiv.org/abs/1603.05279
與我們問(wèn)題相關(guān)的是反向傳播需要權(quán)重必須介于-1 到 1 之間。在 PyTorch 中,這可以很容易實(shí)現(xiàn):
- importtorch
- classMyFunction(torch.autograd.Function):
- @staticmethod
- defforward(ctx,input):
- ctx.save_for_backward(input)
- output =torch.sign(input)
- returnoutput
- @staticmethod
- defbackward(ctx,grad_output):
- # saved tensors - tuple of tensors, so we need get first
- input,=ctx.saved_variables
- grad_output[input.ge(1)]=0
- grad_output[input.le(-1)]=0
- returngrad_output
- # usage
- x =torch.randn(10,20)
- y =MyFunction.apply(x)
- # or
- my_func =MyFunction.apply
- y =my_func(x)
- # and if we want to use inside nn.Module
- classMyFunctionModule(torch.nn.Module):
- defforward(self,x):
- returnMyFunction.apply(x)
正如你所見(jiàn),我們應(yīng)該只定義兩種方法:一個(gè)為正向傳播,一個(gè)為反向傳播。如果我們需要從正向通道訪問(wèn)一些變量,我們可以將它們存儲(chǔ)在 ctx 變量中。注意:在此前的 API 正向/反向傳播不是靜態(tài)的,我們存儲(chǔ)變量需要以 self.save_for_backward(input) 的形式,并以 input, _ = self.saved_tensors 的方式接入。
在 CUDA 上訓(xùn)練模型
我們?cè)?jīng)討論過(guò)傳遞一個(gè)張量到 CUDA 上。但如果希望傳遞整個(gè)模型,我們可以通過(guò)調(diào)用.cuda() 來(lái)完成,并將每個(gè)輸入變量傳遞到.cuda() 中。在所有計(jì)算后,我們需要用返回.cpu() 的方法來(lái)獲得結(jié)果。
同時(shí),PyTorch 也支持在源代碼中直接分配設(shè)備:
- importtorch
- ### tensor example
- x_cpu =torch.randn(10,20)
- w_cpu =torch.randn(20,10)
- # direct transfer to the GPU
- x_gpu =x_cpu.cuda()
- w_gpu =w_cpu.cuda()
- result_gpu =x_gpu @w_gpu
- # get back from GPU to CPU
- result_cpu =result_gpu.cpu()
- ### model example
- modelmodel =model.cuda()
- # train step
- inputs =Variable(inputs.cuda())
- outputs =model(inputs)
- # get back from GPU to CPU
- outputsoutputs =outputs.cpu()
因?yàn)橛行r(shí)候我們想在 CPU 和 GPU 中運(yùn)行相同的模型,而無(wú)需改動(dòng)代碼,我們會(huì)需要一種封裝:
- classTrainer:
- def__init__(self,model,use_cuda=False,gpu_idx=0):
- self.use_cuda =use_cuda
- self.gpu_idx =gpu_idx
- selfself.model =self.to_gpu(model)
- defto_gpu(self,tensor):
- ifself.use_cuda:
- returntensor.cuda(self.gpu_idx)
- else:
- returntensor
- deffrom_gpu(self,tensor):
- ifself.use_cuda:
- returntensor.cpu()
- else:
- returntensor
- deftrain(self,inputs):
- inputs =self.to_gpu(inputs)
- outputs =self.model(inputs)
- outputs =self.from_gpu(outputs)
權(quán)重初始化
在 TesnorFlow 中權(quán)重初始化主要是在張量聲明中進(jìn)行的。PyTorch 則提供了另一種方法:首先聲明張量,隨后在下一步里改變張量的權(quán)重。權(quán)重可以用調(diào)用 torch.nn.init 包中的多種方法初始化為直接訪問(wèn)張量的屬性。這個(gè)決定或許并不直接了當(dāng),但當(dāng)你希望初始化具有某些相同初始化類型的層時(shí),它就會(huì)變得有用。
- importtorch
- fromtorch.autograd importVariable
- # new way with `init` module
- w =torch.Tensor(3,5)
- torch.nn.init.normal(w)
- # work for Variables also
- w2 =Variable(w)
- torch.nn.init.normal(w2)
- # old styled direct access to tensors data attribute
- w2.data.normal_()
- # example for some module
- defweights_init(m):
- classname =m.__class__.__name__
- ifclassname.find('Conv')!=-1:
- m.weight.data.normal_(0.0,0.02)
- elifclassname.find('BatchNorm')!=-1:
- m.weight.data.normal_(1.0,0.02)
- m.bias.data.fill_(0)
- # for loop approach with direct access
- classMyModel(nn.Module):
- def__init__(self):
- form inself.modules():
- ifisinstance(m,nn.Conv2d):
- n =m.kernel_size[0]*m.kernel_size[1]*m.out_channels
- m.weight.data.normal_(0,math.sqrt(2./n))
- elifisinstance(m,nn.BatchNorm2d):
- m.weight.data.fill_(1)
- m.bias.data.zero_()
- elifisinstance(m,nn.Linear):
- m.bias.data.zero_()
反向排除子圖
有時(shí),當(dāng)你希望保留模型中的某些層或者為生產(chǎn)環(huán)境做準(zhǔn)備的時(shí)候,禁用某些層的自動(dòng)梯度機(jī)制非常有用。在這種思路下,PyTorch 設(shè)計(jì)了兩個(gè) flag:requires_grad 和 volatile。第一個(gè)可以禁用當(dāng)前層的梯度,但子節(jié)點(diǎn)仍然可以計(jì)算。第二個(gè)可以禁用自動(dòng)梯度,同時(shí)效果沿用至所有子節(jié)點(diǎn)。
- importtorch
- fromtorch.autograd importVariable
- # requires grad
- # If there’s a single input to an operation that requires gradient,
- # its output will also require gradient.
- x =Variable(torch.randn(5,5))
- y =Variable(torch.randn(5,5))
- z =Variable(torch.randn(5,5),requires_grad=True)
- a =x +y
- a.requires_grad # False
- b =a +z
- b.requires_grad # True
- # Volatile differs from requires_grad in how the flag propagates.
- # If there’s even a single volatile input to an operation,
- # its output is also going to be volatile.
- x =Variable(torch.randn(5,5),requires_grad=True)
- y =Variable(torch.randn(5,5),volatile=True)
- a =x +y
- a.requires_grad # False
訓(xùn)練過(guò)程
當(dāng)然,PyTorch 還有一些其他賣點(diǎn)。例如你可以設(shè)定學(xué)習(xí)速率,讓它以特定規(guī)則進(jìn)行變化?;蛘吣憧梢酝ㄟ^(guò)簡(jiǎn)單的訓(xùn)練標(biāo)記允許/禁止批規(guī)范層和 dropout。如果你想要做的話,讓 CPU 和 GPU 的隨機(jī)算子不同也是可以的。
- # scheduler example
- fromtorch.optim importlr_scheduler
- optimizer =torch.optim.SGD(model.parameters(),lr=0.01)
- scheduler =lr_scheduler.StepLR(optimizer,step_size=30,gamma=0.1)
- forepoch inrange(100):
- scheduler.step()
- train()
- validate()
- # Train flag can be updated with boolean
- # to disable dropout and batch norm learning
- model.train(True)
- # execute train step
- model.train(False)
- # run inference step
- # CPU seed
- torch.manual_seed(42)
- # GPU seed
- torch.cuda.manual_seed_all(42)
同時(shí),你也可以添加模型信息,或存儲(chǔ)/加載一小段代碼。如果你的模型是由 OrderedDict 或基于類的模型字符串,它的表示會(huì)包含層名。
- fromcollections importOrderedDict
- importtorch.nn asnn
- model =nn.Sequential(OrderedDict([
- ('conv1',nn.Conv2d(1,20,5)),
- ('relu1',nn.ReLU()),
- ('conv2',nn.Conv2d(20,64,5)),
- ('relu2',nn.ReLU())
- ]))
- print(model)
- # Sequential (
- # (conv1): Conv2d(1, 20, kernel_size=(5, 5), stride=(1, 1))
- # (relu1): ReLU ()
- # (conv2): Conv2d(20, 64, kernel_size=(5, 5), stride=(1, 1))
- # (relu2): ReLU ()
- # )
- # save/load only the model parameters(prefered solution)
- torch.save(model.state_dict(),save_path)
- model.load_state_dict(torch.load(save_path))
- # save whole model
- torch.save(model,save_path)
- model =torch.load(save_path)
根據(jù) PyTorch 文檔,用 state_dict() 的方式存儲(chǔ)文檔更好。
記錄
訓(xùn)練過(guò)程的記錄是一個(gè)非常重要的部分。不幸的是,PyTorch 目前還沒(méi)有像 Tensorboard 這樣的東西。所以你只能使用普通文本記錄 Python 了,你也可以試試一些第三方庫(kù):
- logger:https://github.com/oval-group/logger
- Crayon:https://github.com/torrvision/crayon
- tensorboard_logger:https://github.com/TeamHG-Memex/tensorboard_logger
- tensorboard-pytorch:https://github.com/lanpa/tensorboard-pytorch
- Visdom:https://github.com/facebookresearch/visdom
掌控?cái)?shù)據(jù)
你可能會(huì)記得 TensorFlow 中的數(shù)據(jù)加載器,甚至想要實(shí)現(xiàn)它的一些功能。對(duì)于我來(lái)說(shuō),我花了四個(gè)小時(shí)來(lái)掌握其中所有管道的執(zhí)行原理。
首先,我想在這里添加一些代碼,但我認(rèn)為上圖足以解釋它的基礎(chǔ)理念了。
PyTorch 開(kāi)發(fā)者不希望重新發(fā)明輪子,他們只是想要借鑒多重處理。為了構(gòu)建自己的數(shù)據(jù)加載器,你可以從 torch.utils.data.Dataset 繼承類,并更改一些方法:
- importtorch
- importtorchvision astv
- classImagesDataset(torch.utils.data.Dataset):
- def__init__(self,df,transform=None,
- loader=tv.datasets.folder.default_loader):
- self.df =df
- self.transform =transform
- self.loader =loader
- def__getitem__(self,index):
- row =self.df.iloc[index]
- target =row['class_']
- path =row['path']
- img =self.loader(path)
- ifself.transform isnotNone:
- img =self.transform(img)
- returnimg,target
- def__len__(self):
- n,_ =self.df.shape
- returnn
- # what transformations should be done with our images
- data_transforms =tv.transforms.Compose([
- tv.transforms.RandomCrop((64,64),padding=4),
- tv.transforms.RandomHorizontalFlip(),
- tv.transforms.ToTensor(),
- ])
- train_df =pd.read_csv('path/to/some.csv')
- # initialize our dataset at first
- train_dataset =ImagesDataset(
- df=train_df,
- transform=data_transforms
- )
- # initialize data loader with required number of workers and other params
- train_loader =torch.utils.data.DataLoader(train_dataset,
- batch_size=10,
- shuffle=True,
- num_workers=16)
- # fetch the batch(call to `__getitem__` method)
- forimg,target intrain_loader:
- pass
有兩件事你需要事先知道:
1. PyTorch 的圖維度和 TensorFlow 的不同。前者的是 [Batch_size × channels × height × width] 的形式。但如果你沒(méi)有通過(guò)預(yù)處理步驟 torchvision.transforms.ToTensor() 進(jìn)行交互,則可以進(jìn)行轉(zhuǎn)換。在 transforms 包中還有很多有用小工具。
2. 你很可能會(huì)使用固定內(nèi)存的 GPU,對(duì)此,你只需要對(duì) cuda() 調(diào)用額外的標(biāo)志 async = True,并從標(biāo)記為 pin_memory = True 的 DataLoader 中獲取固定批次。
最終架構(gòu)
現(xiàn)在我們了解了模型、優(yōu)化器和很多其他細(xì)節(jié)。是時(shí)候來(lái)個(gè)總結(jié)了:
這里有一段用于解讀的偽代碼:
- classImagesDataset(torch.utils.data.Dataset):
- pass
- classNet(nn.Module):
- pass
- model =Net()
- optimizer =torch.optim.SGD(model.parameters(),lr=0.01)
- scheduler =lr_scheduler.StepLR(optimizer,step_size=30,gamma=0.1)
- criterion =torch.nn.MSELoss()
- dataset =ImagesDataset(path_to_images)
- data_loader =torch.utils.data.DataLoader(dataset,batch_size=10)
- train =True
- forepoch inrange(epochs):
- iftrain:
- lr_scheduler.step()
- forinputs,labels indata_loader:
- inputs =Variable(to_gpu(inputs))
- labels =Variable(to_gpu(labels))
- outputs =model(inputs)
- loss =criterion(outputs,labels)
- iftrain:
- optimizer.zero_grad()
- loss.backward()
- optimizer.step()
- ifnottrain:
- save_best_model(epoch_validation_accuracy)
結(jié)論
希望本文可以讓你了解 PyTorch 的如下特點(diǎn):
- 它可以用來(lái)代替 Numpy
- 它的原型設(shè)計(jì)非常快
- 調(diào)試和使用條件流非常簡(jiǎn)單
- 有很多方便且開(kāi)箱即用的工具
PyTorch 是一個(gè)正在快速發(fā)展的框架,背靠一個(gè)富有活力的社區(qū)?,F(xiàn)在是嘗試 PyTorch 的好時(shí)機(jī)。
【本文是51CTO專欄機(jī)構(gòu)“機(jī)器之心”的原創(chuàng)譯文,微信公眾號(hào)“機(jī)器之心( id: almosthuman2014)”】