您好,登錄后才能下訂單哦!
這篇文章主要講解了“Pytorch多層感知機的實現方法”,文中的講解內容簡單清晰,易于學習與理解,下面請大家跟著小編的思路慢慢深入,一起來研究和學習“Pytorch多層感知機的實現方法”吧!
import torch from torch import nn from torch.nn import init import numpy as np import sys import torchvision from torchvision import transforms num_inputs=784 num_outputs=10 num_hiddens=256 mnist_train = torchvision.datasets.FashionMNIST(root='~/Datasets/FashionMNIST', train=True, download=True, transform=transforms.ToTensor()) mnist_test = torchvision.datasets.FashionMNIST(root='~/Datasets/FashionMNIST', train=False, download=True, transform=transforms.ToTensor()) batch_size = 256 train_iter = torch.utils.data.DataLoader(mnist_train, batch_size=batch_size, shuffle=True) test_iter = torch.utils.data.DataLoader(mnist_test, batch_size=batch_size, shuffle=False) def evalute_accuracy(data_iter,net): acc_sum,n=0.0,0 for X,y in data_iter: acc_sum+=(net(X).argmax(dim=1)==y).float().sum().item() n+=y.shape[0] return acc_sum/n def train(net,train_iter,test_iter,loss,num_epochs,batch_size,params=None,lr=None,optimizer=None): for epoch in range(num_epochs): train_l_sum,train_acc_sum,n=0.0,0.0,0 for X,y in train_iter: y_hat=net(X) l=loss(y_hat,y).sum() if optimizer is not None: optimizer.zero_grad() elif params is not None and params[0].grad is not None: for param in params: param.grad.data.zero_() l.backward() optimizer.step() # “softmax回歸的簡潔實現”一節將用到 train_l_sum+=l.item() train_acc_sum+=(y_hat.argmax(dim=1)==y).sum().item() n+=y.shape[0] test_acc=evalute_accuracy(test_iter,net); print('epoch %d, loss %.4f, train acc %.3f, test acc %.3f' % (epoch + 1, train_l_sum / n, train_acc_sum / n, test_acc)) class Faltten(nn.Module): def __init__(self): super(Faltten, self).__init__() def forward(self,x): return x.view(x.shape[0],-1) net =nn.Sequential( Faltten(), nn.Linear(num_inputs,num_hiddens), nn.ReLU(), nn.Linear(num_hiddens,num_outputs) ) for params in net.parameters(): init.normal_(params,mean=0,std=0.01) batch_size=256 loss=torch.nn.CrossEntropyLoss() optimizer=torch.optim.SGD(net.parameters(),lr=0.5) num_epochs=5 train(net,train_iter,test_iter,loss,num_epochs,batch_size,None,None,optimizer)
感謝各位的閱讀,以上就是“Pytorch多層感知機的實現方法”的內容了,經過本文的學習后,相信大家對Pytorch多層感知機的實現方法這一問題有了更深刻的體會,具體使用情況還需要大家實踐驗證。這里是億速云,小編將為大家推送更多相關知識點的文章,歡迎關注!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。