Python實(shí)戰(zhàn)小項(xiàng)目之Mnist手寫(xiě)數(shù)字識(shí)別
程序流程分析圖:

傳播過(guò)程:


代碼展示:
創(chuàng)建環(huán)境
使用<pip install+包名>來(lái)下載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來(lái)繪制其中的一些圖像
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手寫(xiě)數(shù)字識(shí)別的文章就介紹到這了,更多相關(guān)Python Mnist手寫(xiě)數(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í)別手寫(xiě)數(shù)字
- Python劃分?jǐn)?shù)組為連續(xù)數(shù)字集合的練習(xí)
相關(guān)文章
Python如何使用內(nèi)置庫(kù)matplotlib繪制折線圖
這篇文章主要介紹了Python如何使用內(nèi)置庫(kù)matplotlib繪制折線圖,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-02-02
Python超簡(jiǎn)單分析評(píng)論提取關(guān)鍵詞制作精美詞云流程
這篇文章主要介紹了使用Python來(lái)分析評(píng)論并且提取其中的關(guān)鍵詞,用于制作精美詞云的方法,感興趣的朋友來(lái)看看吧2022-03-03
Python標(biāo)準(zhǔn)庫(kù)之os模塊詳解
Python的os模塊是用于與操作系統(tǒng)進(jìn)行交互的模塊,它提供了許多函數(shù)和方法來(lái)執(zhí)行文件和目錄操作、進(jìn)程管理、環(huán)境變量訪問(wèn)等,本文詳細(xì)介紹了Python標(biāo)準(zhǔn)庫(kù)中os模塊,感興趣的同學(xué)跟著小編一起來(lái)看看吧2023-08-08
PyTorch的Optimizer訓(xùn)練工具的實(shí)現(xiàn)
這篇文章主要介紹了PyTorch的Optimizer訓(xùn)練工具的實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-08-08
Python實(shí)現(xiàn)插入排序和選擇排序的方法
這篇文章主要介紹了Python實(shí)現(xiàn)插入排序和選擇排序的方法,非常不錯(cuò),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2019-05-05
解決python的空格和tab混淆而報(bào)錯(cuò)的問(wèn)題
這篇文章主要介紹了解決python的空格和tab混淆而報(bào)錯(cuò)的問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2021-02-02
python:HDF和CSV存儲(chǔ)優(yōu)劣對(duì)比分析
這篇文章主要介紹了python:HDF和CSV存儲(chǔ)優(yōu)劣對(duì)比分析,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-06-06
Python面向?qū)ο罂偨Y(jié)及類(lèi)與正則表達(dá)式詳解
Python中的類(lèi)提供了面向?qū)ο缶幊痰乃谢竟δ埽侯?lèi)的繼承機(jī)制允許多個(gè)基類(lèi),派生類(lèi)可以覆蓋基類(lèi)中的任何方法,方法中可以調(diào)用基類(lèi)中的同名方法。這篇文章主要介紹了Python面向?qū)ο罂偨Y(jié)及類(lèi)與正則表達(dá)式 ,需要的朋友可以參考下2019-04-04
Python cv2 圖像自適應(yīng)灰度直方圖均衡化處理方法
今天小編就為大家分享一篇Python cv2 圖像自適應(yīng)灰度直方圖均衡化處理方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-12-12

