PyTorch手寫數(shù)字?jǐn)?shù)據(jù)集進(jìn)行多分類
一、實(shí)現(xiàn)過(guò)程
本文對(duì)經(jīng)典手寫數(shù)字?jǐn)?shù)據(jù)集進(jìn)行多分類,損失函數(shù)采用交叉熵,激活函數(shù)采用ReLU,優(yōu)化器采用帶有動(dòng)量的mini-batchSGD算法。
所有代碼如下:
0、導(dǎo)包
import torch from torchvision import transforms,datasets from torch.utils.data import DataLoader import torch.nn.functional as F import torch.optim as optim
1、準(zhǔn)備數(shù)據(jù)
batch_size = 64 transform = transforms.Compose([ ? ? transforms.ToTensor(), ? ? transforms.Normalize((0.1307,),(0.3081,)) ]) # 訓(xùn)練集 train_dataset = datasets.MNIST(root='G:/datasets/mnist',train=True,download=False,transform=transform) train_loader = DataLoader(train_dataset,shuffle=True,batch_size=batch_size) # 測(cè)試集 test_dataset = datasets.MNIST(root='G:/datasets/mnist',train=False,download=False,transform=transform) test_loader = DataLoader(test_dataset,shuffle=False,batch_size=batch_size)
2、設(shè)計(jì)模型
class Net(torch.nn.Module):
? ? def __init__(self):
? ? ? ? super(Net, self).__init__()
? ? ? ? self.l1 = torch.nn.Linear(784, 512)
? ? ? ? self.l2 = torch.nn.Linear(512, 256)
? ? ? ? self.l3 = torch.nn.Linear(256, 128)
? ? ? ? self.l4 = torch.nn.Linear(128, 64)
? ? ? ? self.l5 = torch.nn.Linear(64, 10)
? ? def forward(self, x):
? ? ? ? x = x.view(-1, 784)
? ? ? ? x = F.relu(self.l1(x))
? ? ? ? x = F.relu(self.l2(x))
? ? ? ? x = F.relu(self.l3(x))
? ? ? ? x = F.relu(self.l4(x))
? ? ? ? return self.l5(x)
model = Net()
# 模型加載到GPU上
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
model.to(device)3、構(gòu)造損失函數(shù)和優(yōu)化器
criterion = torch.nn.CrossEntropyLoss() optimizer = optim.SGD(model.parameters(),lr=0.01,momentum=0.5)
4、訓(xùn)練和測(cè)試
def train(epoch):
? ? running_loss = 0.0
? ? for batch_idx, data in enumerate(train_loader, 0):
? ? ? ? inputs, target = data
? ? ? ? optimizer.zero_grad()
? ? ? ? # forward+backward+update
? ? ? ? outputs = model(inputs.to(device))
? ? ? ? loss = criterion(outputs, target.to(device))
? ? ? ? loss.backward()
? ? ? ? optimizer.step()
? ? ? ? running_loss += loss.item()
? ? ? ? if batch_idx % 300 == 299:
? ? ? ? ? ? print('[%d,%d] loss: %.3f' % (epoch + 1, batch_idx + 1, running_loss / 300))
? ? ? ? ? ? running_loss = 0.0
def test():
? ? correct = 0
? ? total = 0
? ? with torch.no_grad():
? ? ? ? for data in test_loader:
? ? ? ? ? ? images, labels = data
? ? ? ? ? ? outputs = model(images.to(device))
? ? ? ? ? ? _, predicted = torch.max(outputs.data, dim=1)
? ? ? ? ? ? total += labels.size(0)
? ? ? ? ? ? correct += (predicted.cpu() == labels).sum().item()
? ? print('Accuracy on test set: %d %%' % (100 * correct / total))
for epoch in range(10):
? ? train(epoch)
? ? test()運(yùn)行結(jié)果如下:
[1,300] loss: 2.166
[1,600] loss: 0.797
[1,900] loss: 0.405
Accuracy on test set: 90 %
[2,300] loss: 0.303
[2,600] loss: 0.252
[2,900] loss: 0.218
Accuracy on test set: 94 %
[3,300] loss: 0.178
[3,600] loss: 0.168
[3,900] loss: 0.142
Accuracy on test set: 95 %
[4,300] loss: 0.129
[4,600] loss: 0.119
[4,900] loss: 0.110
Accuracy on test set: 96 %
[5,300] loss: 0.094
[5,600] loss: 0.092
[5,900] loss: 0.091
Accuracy on test set: 96 %
[6,300] loss: 0.077
[6,600] loss: 0.070
[6,900] loss: 0.075
Accuracy on test set: 97 %
[7,300] loss: 0.061
[7,600] loss: 0.058
[7,900] loss: 0.058
Accuracy on test set: 97 %
[8,300] loss: 0.043
[8,600] loss: 0.051
[8,900] loss: 0.050
Accuracy on test set: 97 %
[9,300] loss: 0.041
[9,600] loss: 0.038
[9,900] loss: 0.043
Accuracy on test set: 97 %
[10,300] loss: 0.030
[10,600] loss: 0.032
[10,900] loss: 0.033
Accuracy on test set: 97 %
二、參考文獻(xiàn)
到此這篇關(guān)于PyTorch手寫數(shù)字?jǐn)?shù)據(jù)集進(jìn)行多分類的文章就介紹到這了,更多相關(guān)python多分類內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- Pytorch搭建簡(jiǎn)單的卷積神經(jīng)網(wǎng)絡(luò)(CNN)實(shí)現(xiàn)MNIST數(shù)據(jù)集分類任務(wù)
- python神經(jīng)網(wǎng)絡(luò)AlexNet分類模型訓(xùn)練貓狗數(shù)據(jù)集
- Python機(jī)器學(xué)習(xí)應(yīng)用之基于天氣數(shù)據(jù)集的XGBoost分類篇解讀
- Python深度學(xué)習(xí)pytorch實(shí)現(xiàn)圖像分類數(shù)據(jù)集
- 總結(jié)近幾年P(guān)ytorch基于Imgagenet數(shù)據(jù)集圖像分類模型
- 詳解PyTorch預(yù)定義數(shù)據(jù)集類datasets.ImageFolder使用方法
相關(guān)文章
使用Python編寫電腦定時(shí)關(guān)機(jī)小程序
這篇文章主要為大家詳細(xì)介紹了如何使用Python編寫電腦定時(shí)關(guān)機(jī)小程序,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2024-01-01
Python協(xié)程異步爬取數(shù)據(jù)(asyncio+aiohttp)實(shí)例
這篇文章主要為大家介紹了Python協(xié)程異步爬取數(shù)據(jù)(asyncio+aiohttp)實(shí)現(xiàn)示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-08-08
Python使用multiprocessing創(chuàng)建進(jìn)程的方法
這篇文章主要介紹了Python使用multiprocessing創(chuàng)建進(jìn)程的方法,實(shí)例分析了multiprocessing模塊操作進(jìn)程的相關(guān)技巧,需要的朋友可以參考下2015-06-06
通過(guò)python下載FTP上的文件夾的實(shí)現(xiàn)代碼
使用python下載FTP上的文件夾的代碼,有需要的朋友不妨看看2013-02-02
中秋節(jié)老家要貼對(duì)聯(lián)之python無(wú)線對(duì)聯(lián)生成器
適逢中秋老家居然有在中秋貼對(duì)聯(lián)的習(xí)俗,于是自己開(kāi)機(jī)立馬寫了一個(gè)對(duì)聯(lián)生成器,文中給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有參考價(jià)值2021-09-09
Python實(shí)現(xiàn)Excel數(shù)據(jù)過(guò)濾
本文將以車牌數(shù)據(jù)為示例,為大家詳細(xì)介紹一下如何使用Python實(shí)現(xiàn)Excel數(shù)據(jù)過(guò)濾功能,感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2024-10-10
導(dǎo)入tensorflow:ImportError: libcublas.so.9.0 報(bào)錯(cuò)
這篇文章主要介紹了導(dǎo)入tensorflow:ImportError: libcublas.so.9.0 報(bào)錯(cuò),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-01-01

