使用Pytorch訓(xùn)練two-head網(wǎng)絡(luò)的操作
之前有寫過一篇如何使用Pytorch實(shí)現(xiàn)two-head(多輸出)模型
在那篇文章里,基本把two-head網(wǎng)絡(luò)以及構(gòu)建講清楚了(如果不清楚請先移步至那一篇博文)。
但是我后來發(fā)現(xiàn)之前的訓(xùn)練方法貌似有些問題。
以前的訓(xùn)練方法:
之前是把兩個(gè)head分開進(jìn)行訓(xùn)練的,因此每一輪訓(xùn)練先要對一個(gè)batch的數(shù)據(jù)進(jìn)行劃分,然后再分別訓(xùn)練兩個(gè)頭。代碼如下:
f_out_y0, _ = net(x0)
_, f_out_y1 = net(x1)
#實(shí)例化損失函數(shù)
criterion0 = Loss()
criterion1 = Loss()
loss0 = criterion0(f_y0, f_out_y0, w0)
loss1 = criterion1(f_y1, f_out_y1, w1)
print(loss0.item(), loss1.item())
#對網(wǎng)絡(luò)參數(shù)進(jìn)行初始化
optimizer.zero_grad()
loss0.backward()
loss1.backward()
#對網(wǎng)絡(luò)的參數(shù)進(jìn)行更新
optimizer.step()
但是在實(shí)際操作中想到那這樣的話豈不是每次都先使用t=0的數(shù)據(jù)訓(xùn)練公共的表示層,再使用t=1的數(shù)據(jù)去訓(xùn)練。這樣會不會使表示層產(chǎn)生bias呢?且這樣兩步訓(xùn)練也很麻煩。
修改后的方法
使用之前訓(xùn)練方法其實(shí)還是對神經(jīng)網(wǎng)絡(luò)的訓(xùn)練的機(jī)理不清楚。事實(shí)上,在計(jì)算loss的時(shí)候每個(gè)數(shù)據(jù)點(diǎn)的梯度都是單獨(dú)計(jì)算的。
因此完全可以把網(wǎng)絡(luò)前向傳播得到結(jié)果按之前的順序拼接起來后再進(jìn)行梯度的反向傳播,這樣就可以只進(jìn)行一步訓(xùn)練,且不會出現(xiàn)訓(xùn)練先后的偏差。
代碼如下:
f_out_y0, cf_out_y0 = net(x0)
cf_out_y1, f_out_y1 = net(x1)
#按照t=0和t=1的索引拼接向量
y_pred = torch.zeros([len(x), 1])
y_pred[index0] = f_out_y0
y_pred[index1] = f_out_y1
criterion = Loss()
loss = criterion(f_y, y_pred, w) + 0.01 * (l2_regularization0 + l2_regularization1)
#print(loss.item())
viz.line([float(loss)], [epoch], win='train_loss', update='append')
optimizer.zero_grad()
loss.backward()
#對網(wǎng)絡(luò)的參數(shù)進(jìn)行更新
optimizer.step()
總結(jié)
two-head網(wǎng)絡(luò)前向傳播得到結(jié)果的時(shí)候是分開得到的,訓(xùn)練的時(shí)候通過拼接預(yù)測結(jié)果可以實(shí)現(xiàn)一次訓(xùn)練。
補(bǔ)充:Pytorch訓(xùn)練網(wǎng)絡(luò)的一般步驟
如下所示:
import torch print(torch.tensor([1,2,3],dtype=torch.float))#將一個(gè)列表強(qiáng)制轉(zhuǎn)換為torch.Tensor類型 print(torch.randn(5,3))#生成torch.Tensor類型的5X3的隨機(jī)數(shù)
1、構(gòu)建模型
2、定義一個(gè)損失函數(shù)
3、定義一個(gè)優(yōu)化器
4、將訓(xùn)練數(shù)據(jù)帶入模型得到預(yù)測值
5、將梯度清零
6、獲得損失
7、進(jìn)行優(yōu)化
import torch
from torch.autograd import Variable
#初步認(rèn)識構(gòu)建Tensor數(shù)據(jù)
def one():
print(torch.tensor([1,2,3],dtype=torch.float))#將一個(gè)列表強(qiáng)制轉(zhuǎn)換為torch.Tensor類型
print(torch.randn(5,3))#生成torch.Tensor類型的5X3的隨機(jī)數(shù)
print(torch.zeros((2,3)))#生成一個(gè)2X3的全零矩陣
print(torch.ones((2,3)))#生成一個(gè)2X3的全一矩陣
a = torch.randn((2,3))
b = a.numpy()#將一個(gè)torch.Tensor轉(zhuǎn)換為numpy
c = torch.from_numpy(b)#將numpy轉(zhuǎn)換為Tensor
print(a)
print(b)
print(c)
#使用Variable自動求導(dǎo)
def two():
# 構(gòu)建Variable
x = Variable(torch.Tensor([1, 2, 3]), requires_grad=True)
w = Variable(torch.Tensor([4, 5, 6]), requires_grad=True)
b = Variable(torch.Tensor([7, 8, 9]), requires_grad=True)
# 函數(shù)等式
y = w * x ** 2 + b
# 使用梯度下降計(jì)算各變量的偏導(dǎo)數(shù)
y.backward(torch.Tensor([1, 1, 1]))
print(x.grad)
print(w.grad)
print(b.grad)
線性回歸例子:
import torch
from torch.autograd import Variable
import numpy as np
import matplotlib.pyplot as plt
from torch import nn
x = torch.unsqueeze(torch.linspace(-1,1,100),dim=1)
y = 3*x+10+torch.rand(x.size())
class LinearRegression(nn.Module):
def __init__(self):
super(LinearRegression,self).__init__()
self.Linear = nn.Linear(1,1)
def forward(self,x):
return self.Linear(x)
model = LinearRegression()
Loss = nn.MSELoss()
Opt = torch.optim.SGD(model.parameters(),lr=0.01)
for i in range(1000):
inputs = Variable(x)
targets = Variable(y)
outputs = model(inputs)
loss = Loss(outputs,targets)
Opt.zero_grad()
loss.backward()
Opt.step()
model.eval()
predict = model(Variable(x))
plt.plot(x.numpy(),y.numpy(),'ro')
plt.plot(x.numpy(),predict.data.numpy())
plt.show()
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
Python向Excel中插入圖片的簡單實(shí)現(xiàn)方法
這篇文章主要介紹了Python向Excel中插入圖片的簡單實(shí)現(xiàn)方法,結(jié)合實(shí)例形式分析了Python使用XlsxWriter模塊操作Excel單元格插入jpg格式圖片的相關(guān)操作技巧,非常簡單實(shí)用,需要的朋友可以參考下2018-04-04
python 用Matplotlib作圖中有多個(gè)Y軸
這篇文章主要介紹了python 如何用Matplotlib作圖中有多個(gè)Y軸,幫助大家更好的利用python繪圖,感興趣的朋友可以了解下2020-11-11
python結(jié)合opencv實(shí)現(xiàn)人臉檢測與跟蹤
在Python下用起來OpenCV很爽,代碼很簡潔,很清晰易懂。使用的是Haar特征的分類器,訓(xùn)練之后得到的數(shù)據(jù)存在一個(gè)xml中。下面我們就來詳細(xì)談?wù)劇?/div> 2015-06-06
Python實(shí)戰(zhàn)使用Selenium爬取網(wǎng)頁數(shù)據(jù)
這篇文章主要為大家介紹了Python實(shí)戰(zhàn)使用Selenium爬取網(wǎng)頁數(shù)據(jù)示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步早日升職加薪2023-05-05
簡單了解python gevent 協(xié)程使用及作用
這篇文章主要介紹了簡單了解python gevent 協(xié)程,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-07-07最新評論

