Python實(shí)戰(zhàn)小項(xiàng)目之Mnist手寫數(shù)字識(shí)別
程序流程分析圖:
傳播過程:
代碼展示:
創(chuàng)建環(huán)境
使用<pip install+包名>來下載torch,torchvision包
準(zhǔn)備數(shù)據(jù)集
設(shè)置一次訓(xùn)練所選取的樣本數(shù)Batch_Sized的值為512,訓(xùn)練此時(shí)Epochs的值為8
BATCH_SIZE = 512 EPOCHS = 8 device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
下載數(shù)據(jù)集
Normalize()數(shù)字歸一化,轉(zhuǎn)換使用的值0.1307和0.3081是MNIST數(shù)據(jù)集的全局平均值和標(biāo)準(zhǔn)偏差,這里我們將它們作為給定值。model
train_loader = torch.utils.data.DataLoader( datasets.MNIST('data', train=True, download=True, transform=transforms.Compose([. transforms.ToTensor(), transforms.Normalize((0.1307,), (0.3081,)) ])), batch_size=BATCH_SIZE, shuffle=True)
下載測(cè)試集
test_loader = torch.utils.data.DataLoader( datasets.MNIST('data', train=False, transform=transforms.Compose([ transforms.ToTensor(), transforms.Normalize((0.1307,), (0.3081,)) ])), batch_size=BATCH_SIZE, shuffle=True)
繪制圖像
我們可以使用matplotlib來繪制其中的一些圖像
examples = enumerate(test_loader) batch_idx, (example_data, example_targets) = next(examples) print(example_targets) print(example_data.shape) print(example_data) import matplotlib.pyplot as plt fig = plt.figure() for i in range(6): plt.subplot(2,3,i+1) plt.tight_layout() plt.imshow(example_data[i][0], cmap='gray', interpolation='none') plt.title("Ground Truth: {}".format(example_targets[i])) plt.xticks([]) plt.yticks([]) plt.show()
搭建神經(jīng)網(wǎng)絡(luò)
這里我們構(gòu)建全連接神經(jīng)網(wǎng)絡(luò),我們使用三個(gè)全連接(或線性)層進(jìn)行前向傳播。
class linearNet(nn.Module): def __init__(self): super().__init__() self.fc1 = nn.Linear(784, 128) self.fc2 = nn.Linear(128, 64) self.fc3 = nn.Linear(64, 10) def forward(self, x): x = x.view(-1, 784) x = self.fc1(x) x = F.relu(x) x = self.fc2(x) x = F.relu(x) x = self.fc3(x) x = F.log_softmax(x, dim=1) return x
訓(xùn)練模型
首先,我們需要使用optimizer.zero_grad()手動(dòng)將梯度設(shè)置為零,因?yàn)镻yTorch在默認(rèn)情況下會(huì)累積梯度。然后,我們生成網(wǎng)絡(luò)的輸出(前向傳遞),并計(jì)算輸出與真值標(biāo)簽之間的負(fù)對(duì)數(shù)概率損失?,F(xiàn)在,我們收集一組新的梯度,并使用optimizer.step()將其傳播回每個(gè)網(wǎng)絡(luò)參數(shù)。
def train(model, device, train_loader, optimizer, epoch): model.train() for batch_idx, (data, target) in enumerate(train_loader): data, target = data.to(device), target.to(device) optimizer.zero_grad() output = model(data) loss = F.nll_loss(output, target) loss.backward() optimizer.step() if (batch_idx) % 30 == 0: print('Train Epoch: {} [{}/{} ({:.0f}%)]\tLoss: {:.6f}'.format( epoch, batch_idx * len(data), len(train_loader.dataset), 100. * batch_idx / len(train_loader), loss.item()))
測(cè)試模型
def test(model, device, test_loader): model.eval() test_loss = 0 correct = 0 with torch.no_grad(): for data, target in test_loader: data, target = data.to(device), target.to(device) output = model(data) test_loss += F.nll_loss(output, target, reduction='sum').item() # 將一批的損失相加 pred = output.max(1, keepdim=True)[1] # 找到概率最大的下標(biāo) correct += pred.eq(target.view_as(pred)).sum().item() test_loss /= len(test_loader.dataset) print('\nTest set: Average loss: {:.4f}, Accuracy: {}/{} ({:.0f}%)\n'.format( test_loss, correct, len(test_loader.dataset), 100. * correct / len(test_loader.dataset)))
將訓(xùn)練次數(shù)進(jìn)行循環(huán)
if __name__ == '__main__': model = linearNet() optimizer = optim.Adam(model.parameters()) for epoch in range(1, EPOCHS + 1): train(model, device, train_loader, optimizer, epoch) test(model, device, test_loader)
保存訓(xùn)練模型
torch.save(model, 'MNIST.pth')
運(yùn)行結(jié)果展示:
分享人:蘇云云
到此這篇關(guān)于Python實(shí)戰(zhàn)小項(xiàng)目之Mnist手寫數(shù)字識(shí)別的文章就介紹到這了,更多相關(guān)Python Mnist手寫數(shù)字識(shí)別內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- python ndarray數(shù)組對(duì)象特點(diǎn)及實(shí)例分享
- python計(jì)算數(shù)字或者數(shù)組的階乘的實(shí)現(xiàn)
- Python多進(jìn)程共享numpy 數(shù)組的方法
- Python基礎(chǔ)學(xué)習(xí)之基本數(shù)據(jù)結(jié)構(gòu)詳解【數(shù)字、字符串、列表、元組、集合、字典】
- Python 數(shù)字轉(zhuǎn)化成列表詳情
- Python神經(jīng)網(wǎng)絡(luò)TensorFlow基于CNN卷積識(shí)別手寫數(shù)字
- Python劃分?jǐn)?shù)組為連續(xù)數(shù)字集合的練習(xí)
相關(guān)文章
Python如何使用內(nèi)置庫matplotlib繪制折線圖
這篇文章主要介紹了Python如何使用內(nèi)置庫matplotlib繪制折線圖,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-02-02Python超簡單分析評(píng)論提取關(guān)鍵詞制作精美詞云流程
這篇文章主要介紹了使用Python來分析評(píng)論并且提取其中的關(guān)鍵詞,用于制作精美詞云的方法,感興趣的朋友來看看吧2022-03-03PyTorch的Optimizer訓(xùn)練工具的實(shí)現(xiàn)
這篇文章主要介紹了PyTorch的Optimizer訓(xùn)練工具的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-08-08Python實(shí)現(xiàn)插入排序和選擇排序的方法
這篇文章主要介紹了Python實(shí)現(xiàn)插入排序和選擇排序的方法,非常不錯(cuò),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2019-05-05解決python的空格和tab混淆而報(bào)錯(cuò)的問題
這篇文章主要介紹了解決python的空格和tab混淆而報(bào)錯(cuò)的問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2021-02-02python:HDF和CSV存儲(chǔ)優(yōu)劣對(duì)比分析
這篇文章主要介紹了python:HDF和CSV存儲(chǔ)優(yōu)劣對(duì)比分析,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2020-06-06Python面向?qū)ο罂偨Y(jié)及類與正則表達(dá)式詳解
Python中的類提供了面向?qū)ο缶幊痰乃谢竟δ埽侯惖睦^承機(jī)制允許多個(gè)基類,派生類可以覆蓋基類中的任何方法,方法中可以調(diào)用基類中的同名方法。這篇文章主要介紹了Python面向?qū)ο罂偨Y(jié)及類與正則表達(dá)式 ,需要的朋友可以參考下2019-04-04Python cv2 圖像自適應(yīng)灰度直方圖均衡化處理方法
今天小編就為大家分享一篇Python cv2 圖像自適應(yīng)灰度直方圖均衡化處理方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2018-12-12