Python深度學(xué)習(xí)pytorch神經(jīng)網(wǎng)絡(luò)多層感知機(jī)簡(jiǎn)潔實(shí)現(xiàn)
我們可以通過(guò)高級(jí)API更簡(jiǎn)潔地實(shí)現(xiàn)多層感知機(jī)。
import torch from torch import nn from d2l import torch as d2l
模型
與softmax回歸的簡(jiǎn)潔實(shí)現(xiàn)相比,唯一的區(qū)別是我們添加了2個(gè)全連接層。第一層是隱藏層,它包含256個(gè)隱藏單元,并使用了ReLU激活函數(shù)。第二層是輸出層。
net = nn.Sequential(nn.Flatten(), nn.Linear(784, 256), nn.ReLU(), nn.Linear(256, 10)) def init_weights(m): if type(m) == nn.Linear: nn.init.normal_(m.weight, std=0.01) net.apply(init_weights)
訓(xùn)練過(guò)程的實(shí)現(xiàn)與我們實(shí)現(xiàn)softmax回歸時(shí)完全相同,這種模塊化設(shè)計(jì)使我們能夠?qū)⑴c和模型架構(gòu)有關(guān)的內(nèi)容獨(dú)立出來(lái)。
batch_size, lr, num_epochs = 256, 0.1, 10 # 批量大小為256,學(xué)習(xí)率為0.1,類型為10 loss = nn.CrossEntropyLoss() # 使用交叉熵?fù)p失函數(shù) trainer = torch.optim.SGD(net.parameters(), lr=lr) # 開(kāi)始訓(xùn)練
train_iter, test_iter = d2l.load_data_fashion_mnist(batch_size) d2l.train_ch3(net, train_iter, test_iter, loss, num_epochs, trainer)

以上就是Python深度學(xué)習(xí)pytorch神經(jīng)網(wǎng)絡(luò)多層感知機(jī)簡(jiǎn)潔實(shí)現(xiàn)的詳細(xì)內(nèi)容,更多關(guān)于pytorch神經(jīng)網(wǎng)絡(luò)的資料請(qǐng)關(guān)注本站其它相關(guān)文章!
版權(quán)聲明:本站文章來(lái)源標(biāo)注為YINGSOO的內(nèi)容版權(quán)均為本站所有,歡迎引用、轉(zhuǎn)載,請(qǐng)保持原文完整并注明來(lái)源及原文鏈接。禁止復(fù)制或仿造本網(wǎng)站,禁止在非maisonbaluchon.cn所屬的服務(wù)器上建立鏡像,否則將依法追究法律責(zé)任。本站部分內(nèi)容來(lái)源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來(lái),僅供學(xué)習(xí)參考,不代表本站立場(chǎng),如有內(nèi)容涉嫌侵權(quán),請(qǐng)聯(lián)系alex-e#qq.com處理。
關(guān)注官方微信