Python深度學(xué)習(xí)pyTorch權(quán)重衰減與L2范數(shù)正則化解析

下面進行一個高維線性實驗
假設(shè)我們的真實方程是:

假設(shè)feature數(shù)200,訓(xùn)練樣本和測試樣本各20個
模擬數(shù)據(jù)集
num_train,num_test = 10,10 num_features = 200 true_w = torch.ones((num_features,1),dtype=torch.float32) * 0.01 true_b = torch.tensor(0.5) samples = torch.normal(0,1,(num_train+num_test,num_features)) noise = torch.normal(0,0.01,(num_train+num_test,1)) labels = samples.matmul(true_w) + true_b + noise train_samples, train_labels= samples[:num_train],labels[:num_train] test_samples, test_labels = samples[num_train:],labels[num_train:]
定義帶正則項的loss function
def loss_function(predict,label,w,lambd):
loss = (predict - label) ** 2
loss = loss.mean() + lambd * (w**2).mean()
return loss
畫圖的方法
def semilogy(x_val,y_val,x_label,y_label,x2_val,y2_val,legend):
plt.figure(figsize=(3,3))
plt.xlabel(x_label)
plt.ylabel(y_label)
plt.semilogy(x_val,y_val)
if x2_val and y2_val:
plt.semilogy(x2_val,y2_val)
plt.legend(legend)
plt.show()
擬合和畫圖
def fit_and_plot(train_samples,train_labels,test_samples,test_labels,num_epoch,lambd):
w = torch.normal(0,1,(train_samples.shape[-1],1),requires_grad=True)
b = torch.tensor(0.,requires_grad=True)
optimizer = torch.optim.Adam([w,b],lr=0.05)
train_loss = []
test_loss = []
for epoch in range(num_epoch):
predict = train_samples.matmul(w) + b
epoch_train_loss = loss_function(predict,train_labels,w,lambd)
optimizer.zero_grad()
epoch_train_loss.backward()
optimizer.step()
test_predict = test_sapmles.matmul(w) + b
epoch_test_loss = loss_function(test_predict,test_labels,w,lambd)
train_loss.append(epoch_train_loss.item())
test_loss.append(epoch_test_loss.item())
semilogy(range(1,num_epoch+1),train_loss,'epoch','loss',range(1,num_epoch+1),test_loss,['train','test'])

可以發(fā)現(xiàn)加了正則項的模型,在測試集上的loss確實下降了
以上就是Python深度學(xué)習(xí)pyTorch權(quán)重衰減與L2范數(shù)正則化解析的詳細內(nèi)容,更多關(guān)于Python pyTorch權(quán)重與L2范數(shù)正則化的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Python實現(xiàn)將羅馬數(shù)字轉(zhuǎn)換成普通阿拉伯數(shù)字的方法
這篇文章主要介紹了Python實現(xiàn)將羅馬數(shù)字轉(zhuǎn)換成普通阿拉伯數(shù)字的方法,簡單分析了羅馬數(shù)字的構(gòu)成并結(jié)合實例形式給出了Python轉(zhuǎn)換羅馬數(shù)字為阿拉伯數(shù)字的實現(xiàn)方法,需要的朋友可以參考下2017-04-04
python-xpath獲取html文檔的部分內(nèi)容
這篇文章主要介紹了python-xpath獲取html文檔的部分內(nèi)容,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-03-03
Python?matplotlib的spines模塊實例詳解
作為程序員,經(jīng)常需要進行繪圖,下面這篇文章主要給大家介紹了關(guān)于Python?matplotlib的spines模塊的相關(guān)資料,文中通過實例代碼介紹的非常詳細,需要的朋友可以參考下2022-08-08
python3之模塊psutil系統(tǒng)性能信息使用
psutil是個跨平臺庫,能夠輕松實現(xiàn)獲取系統(tǒng)運行的進程和系統(tǒng)利用率,這篇文章主要介紹了python3之模塊psutil系統(tǒng)性能信息使用,感興趣的小伙伴們可以參考一下2018-05-05
Python使用Bokeh庫實現(xiàn)炫目的交互可視化
Bokeh是一個用于創(chuàng)建交互式可視化圖形的強大Python庫,它不僅易于使用,而且功能強大,適用于各種數(shù)據(jù)可視化需求,本文將介紹Bokeh庫的繪圖可視化基礎(chǔ)入門,需要的可以了解下2024-03-03

