pytorch實(shí)現(xiàn)手寫數(shù)字圖片識(shí)別
本文實(shí)例為大家分享了pytorch實(shí)現(xiàn)手寫數(shù)字圖片識(shí)別的具體代碼,供大家參考,具體內(nèi)容如下
數(shù)據(jù)集:MNIST數(shù)據(jù)集,代碼中會(huì)自動(dòng)下載,不用自己手動(dòng)下載。數(shù)據(jù)集很小,不需要GPU設(shè)備,可以很好的體會(huì)到pytorch的魅力。
模型+訓(xùn)練+預(yù)測(cè)程序:
import torch from torch import nn from torch.nn import functional as F from torch import optim import torchvision from matplotlib import pyplot as plt from utils import plot_image, plot_curve, one_hot # step1 load dataset batch_size = 512 train_loader = torch.utils.data.DataLoader( torchvision.datasets.MNIST('mnist_data', train=True, download=True, transform=torchvision.transforms.Compose([ torchvision.transforms.ToTensor(), torchvision.transforms.Normalize( (0.1307,), (0.3081,) ) ])), batch_size=batch_size, shuffle=True) test_loader = torch.utils.data.DataLoader( torchvision.datasets.MNIST('mnist_data/', train=False, download=True, transform=torchvision.transforms.Compose([ torchvision.transforms.ToTensor(), torchvision.transforms.Normalize( (0.1307,), (0.3081,) ) ])), batch_size=batch_size, shuffle=False) x , y = next(iter(train_loader)) print(x.shape, y.shape, x.min(), x.max()) plot_image(x, y, "image_sample") class Net(nn.Module): def __init__(self): super(Net, self).__init__() self.fc1 = nn.Linear(28*28, 256) self.fc2 = nn.Linear(256, 64) self.fc3 = nn.Linear(64, 10) def forward(self, x): # x: [b, 1, 28, 28] # h1 = relu(xw1 + b1) x = F.relu(self.fc1(x)) # h2 = relu(h1w2 + b2) x = F.relu(self.fc2(x)) # h3 = h2w3 + b3 x = self.fc3(x) return x net = Net() optimizer = optim.SGD(net.parameters(), lr=0.01, momentum=0.9) train_loss = [] for epoch in range(3): for batch_idx, (x, y) in enumerate(train_loader): #加載進(jìn)來的圖片是一個(gè)四維的tensor,x: [b, 1, 28, 28], y:[512] #但是我們網(wǎng)絡(luò)的輸入要是一個(gè)一維向量(也就是二維tensor),所以要進(jìn)行展平操作 x = x.view(x.size(0), 28*28) # [b, 10] out = net(x) y_onehot = one_hot(y) # loss = mse(out, y_onehot) loss = F.mse_loss(out, y_onehot) optimizer.zero_grad() loss.backward() # w' = w - lr*grad optimizer.step() train_loss.append(loss.item()) if batch_idx % 10 == 0: print(epoch, batch_idx, loss.item()) plot_curve(train_loss) # we get optimal [w1, b1, w2, b2, w3, b3] total_correct = 0 for x,y in test_loader: x = x.view(x.size(0), 28*28) out = net(x) # out: [b, 10] pred = out.argmax(dim=1) correct = pred.eq(y).sum().float().item() total_correct += correct total_num = len(test_loader.dataset) acc = total_correct/total_num print("acc:", acc) x, y = next(iter(test_loader)) out = net(x.view(x.size(0), 28*28)) pred = out.argmax(dim=1) plot_image(x, pred, "test")
主程序中調(diào)用的函數(shù)(注意命名為utils):
import torch from matplotlib import pyplot as plt def plot_curve(data): fig = plt.figure() plt.plot(range(len(data)), data, color='blue') plt.legend(['value'], loc='upper right') plt.xlabel('step') plt.ylabel('value') plt.show() def plot_image(img, label, name): fig = plt.figure() for i in range(6): plt.subplot(2, 3, i + 1) plt.tight_layout() plt.imshow(img[i][0]*0.3081+0.1307, cmap='gray', interpolation='none') plt.title("{}: {}".format(name, label[i].item())) plt.xticks([]) plt.yticks([]) plt.show() def one_hot(label, depth=10): out = torch.zeros(label.size(0), depth) idx = torch.LongTensor(label).view(-1, 1) out.scatter_(dim=1, index=idx, value=1) return out
打印出損失下降的曲線圖:
訓(xùn)練3個(gè)epoch之后,在測(cè)試集上的精度就可以89%左右,可見模型的準(zhǔn)確度還是很不錯(cuò)的。
輸出六張測(cè)試集的圖片以及預(yù)測(cè)結(jié)果:
六張圖片的預(yù)測(cè)全部正確。
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Python?自動(dòng)控制原理?control的詳細(xì)解說
這篇文章主要介紹了Python自動(dòng)控制原理control的詳細(xì)解說,文章圍繞主題展開對(duì)Python?control的介紹,具有一定的參考價(jià)值,需要的朋友可以參考一下2022-07-07Python?Pandas學(xué)習(xí)之series的二元運(yùn)算詳解
二元運(yùn)算是指由兩個(gè)元素形成第三個(gè)元素的一種規(guī)則,例如數(shù)的加法及乘法;更一般地,由兩個(gè)集合形成第三個(gè)集合的產(chǎn)生方法或構(gòu)成規(guī)則稱為二次運(yùn)算。本文將詳細(xì)講講Pandas中series的二元運(yùn)算,感興趣的可以了解一下2022-09-09一起用Python做個(gè)上課點(diǎn)名器的制作過程
今天給大家分享一個(gè)讀者粉絲投稿的,關(guān)于上課點(diǎn)名的實(shí)戰(zhàn)案例,對(duì)Python上課點(diǎn)名器實(shí)現(xiàn)過程感興趣的朋友,一起來看看是如何實(shí)現(xiàn)的吧2021-09-09賺瘋了!轉(zhuǎn)手立賺800+?大佬的python「搶茅臺(tái)腳本」使用教程
這篇文章主要介紹了如果利用python搶購(gòu)京東茅臺(tái),幫助大家更好的理解和使用python,感興趣的朋友可以了解下2021-01-01python實(shí)現(xiàn)微信小程序的多種支付方式
這篇文章主要為大家介紹了python實(shí)現(xiàn)微信小程序的多種支付方式的實(shí)現(xiàn)示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步早日升職加薪2022-04-04django queryset 去重 .distinct()說明
這篇文章主要介紹了django queryset 去重 .distinct()說明,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2020-05-05Python計(jì)算不規(guī)則圖形面積算法實(shí)現(xiàn)解析
這篇文章主要介紹了Python計(jì)算不規(guī)則圖形面積算法實(shí)現(xiàn)解析,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-11-11