溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

PyTorch怎么設(shè)置隨機(jī)種子

發(fā)布時(shí)間:2021-12-16 09:51:19 來源:億速云 閱讀:292 作者:iii 欄目:大數(shù)據(jù)

本篇內(nèi)容介紹了“PyTorch怎么設(shè)置隨機(jī)種子”的有關(guān)知識(shí),在實(shí)際案例的操作過程中,不少人都會(huì)遇到這樣的困境,接下來就讓小編帶領(lǐng)大家學(xué)習(xí)一下如何處理這些情況吧!希望大家仔細(xì)閱讀,能夠?qū)W有所成!

import torch
import torch.nn as nn
import matplotlib.pyplot as plt
from tools import set_seed
from torch.utils.tensorboard import SummaryWriter

set_seed(1)  # 設(shè)置隨機(jī)種子
n_hidden = 200
max_iter = 2000
disp_interval = 200
lr_init = 0.01


def gen_data(num_data=10, x_range=(-1, 1)):
    w = 1.5
    train_x = torch.linspace(*x_range, num_data).unsqueeze_(1)
    train_y = w*train_x + torch.normal(0, 0.5, size=train_x.size())
    test_x = torch.linspace(*x_range, num_data).unsqueeze_(1)
    test_y = w*test_x + torch.normal(0, 0.3, size=test_x.size())
    return train_x, train_y, test_x, test_y
train_x, train_y, test_x, test_y = gen_data(num_data=10, x_range=(-1, 1))

class MLP(nn.Module):
    def __init__(self, neural_num):
        super(MLP, self).__init__()
        self.linears = nn.Sequential(
            nn.Linear(1, neural_num),
            nn.ReLU(inplace=True),
            nn.Linear(neural_num, neural_num),
            nn.ReLU(inplace=True),
            nn.Linear(neural_num, neural_num),
            nn.ReLU(inplace=True),
            nn.Linear(neural_num, 1),
        )

    def forward(self, x):
        return self.linears(x)

net_n = MLP(neural_num=n_hidden)
net_weight_decay = MLP(neural_num=n_hidden)

optim_n = torch.optim.SGD(net_n.parameters(), lr=lr_init, momentum=0.9)
optim_wdecay = torch.optim.SGD(net_weight_decay.parameters(), lr=lr_init, momentum=0.9, weight_decay=1e-2)
loss_fun = torch.nn.MSELoss() #均方損失
writer = SummaryWriter(comment='test', filename_suffix='test')
for epoch in range(max_iter):
    pred_normal, pred_wdecay = net_n(train_x), net_weight_decay(train_x)
    loss_n, loss_wdecay = loss_fun(pred_normal, train_y), loss_fun(pred_wdecay, train_y)
    optim_n.zero_grad()
    optim_wdecay.zero_grad()
    loss_n.backward()
    loss_wdecay.backward()
    optim_n.step() #參數(shù)更新
    optim_wdecay.step()
    if (epoch + 1) % disp_interval == 0:
        for name, layer in net_n.named_parameters(): ##
            writer.add_histogram(name + '_grad_normal', layer.grad, epoch)
            writer.add_histogram(name + '_data_normal', layer, epoch)
        for name, layer in net_weight_decay.named_parameters():
            writer.add_histogram(name + '_grad_weight_decay', layer.grad, epoch)
            writer.add_histogram(name + '_data_weight_decay', layer, epoch)
        test_pred_normal, test_pred_wdecay = net_n(test_x), net_weight_decay(test_x)
        plt.scatter(train_x.data.numpy(), train_y.data.numpy(), c='blue', s=50, alpha=0.3, label='trainc')
        plt.scatter(test_x.data.numpy(), test_y.data.numpy(), c='red', s=50, alpha=0.3, label='test')
        plt.plot(test_x.data.numpy(), test_pred_normal.data.numpy(), 'r-', lw=3, label='no weight decay')
        plt.plot(test_x.data.numpy(), test_pred_wdecay.data.numpy(), 'b--', lw=3, label='weight decay')
        plt.text(-0.25, -1.5, 'no weight decay loss={:.6f}'.format(loss_n.item()),
                 fontdict={'size': 15, 'color': 'red'})
        plt.text(-0.25, -2, 'weight decay loss={:.6f}'.format(loss_wdecay.item()),
                 fontdict={'size': 15, 'color': 'red'})
        plt.ylim(-2.5, 2.5)
        plt.legend()
        plt.title('Epoch: {}'.format(epoch +  1))
        plt.show()
        plt.close()

作業(yè)

1.   weight decay在pytorch的SGD中實(shí)現(xiàn)代碼是哪一行?它對(duì)應(yīng)的數(shù)學(xué)公式為?

2.   PyTorch中,Dropout在訓(xùn)練的時(shí)候權(quán)值尺度會(huì)進(jìn)行什么操作?

1. weight decay

optim_wdecay = torch.optim.SGD(net_weight_decay.parameters(), lr=lr_init,
										 momentum=0.9, weight_decay=1e-2)
optim_wdecay.step()	

2. dropout期望

Dropout隨機(jī)失活,隱藏單元以一定概率被丟棄,以1-p的概率除以1-p做拉伸,即輸出單元的計(jì)算不依賴于丟棄的隱藏層單元

“PyTorch怎么設(shè)置隨機(jī)種子”的內(nèi)容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業(yè)相關(guān)的知識(shí)可以關(guān)注億速云網(wǎng)站,小編將為大家輸出更多高質(zhì)量的實(shí)用文章!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI