Pytorch框架實(shí)現(xiàn)mnist手寫庫識別(與tensorflow對比)
前言最近在學(xué)習(xí)過程中需要用到pytorch框架,簡單學(xué)習(xí)了一下,寫了一個簡單的案例,記錄一下pytorch中搭建一個識別網(wǎng)絡(luò)基礎(chǔ)的東西。對應(yīng)一位博主寫的tensorflow的識別mnist數(shù)據(jù)集,將其改為pytorch框架,也可以詳細(xì)看到兩個框架大體的區(qū)別。
Tensorflow版本轉(zhuǎn)載來源(CSDN博主「兔八哥1024」):http://www.fzitv.net/article/191157.htm
Pytorch實(shí)戰(zhàn)mnist手寫數(shù)字識別
#需要導(dǎo)入的包
import torch
import torch.nn as nn#用于構(gòu)建網(wǎng)絡(luò)層
import torch.optim as optim#導(dǎo)入優(yōu)化器
from torch.utils.data import DataLoader#加載數(shù)據(jù)集的迭代器
from torchvision import datasets, transforms#用于加載mnsit數(shù)據(jù)集
#下載數(shù)據(jù)集
train_set = datasets.MNIST('./data', train=True, download=True,transform = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.1037,), (0.3081,))
]))
test_set = datasets.MNIST('./data', train=False, download=True,transform = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.1037,), (0.3081,))
]))
#構(gòu)建網(wǎng)絡(luò)(網(wǎng)絡(luò)結(jié)構(gòu)對應(yīng)tensorflow的那一篇文章)
class Net(nn.Module):
def __init__(self, num_classes=10):
super(Net, self).__init__()
self.features = nn.Sequential(
nn.Conv2d(1, 32, kernel_size=5, stride=1, padding=2),
nn.MaxPool2d(kernel_size=2,stride=2),
nn.Conv2d(32, 64, kernel_size=5, stride=1, padding=2),
nn.MaxPool2d(kernel_size=2,stride=2),
)
self.classifier = nn.Sequential(
nn.Linear(3136, 7*7*64),
nn.Linear(3136, num_classes),
)
def forward(self,x):
x = self.features(x)
x = torch.flatten(x, 1)
x = self.classifier(x)
return x
net=Net()
net.cuda()#用GPU運(yùn)行
#計(jì)算誤差,使用adam優(yōu)化器優(yōu)化誤差
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(net.parameters(), 1e-2)
train_data = DataLoader(train_set, batch_size=128, shuffle=True)
test_data = DataLoader(test_set, batch_size=128, shuffle=False)
#訓(xùn)練過程
for epoch in range(1):
net.train() ##在進(jìn)行訓(xùn)練時加上train(),測試時加上eval()
batch = 0
for batch_images, batch_labels in train_data:
average_loss = 0
train_acc = 0
##在pytorch0.4之后將Variable 與tensor進(jìn)行合并,所以這里不需要進(jìn)行Variable封裝
if torch.cuda.is_available():
batch_images, batch_labels = batch_images.cuda(),batch_labels.cuda()
#前向傳播
out = net(batch_images)
loss = criterion(out,batch_labels)
average_loss = loss
prediction = torch.max(out,1)[1]
# print(prediction)
train_correct = (prediction == batch_labels).sum()
##這里得到的train_correct是一個longtensor型,需要轉(zhuǎn)換為float
train_acc = (train_correct.float()) / 128
optimizer.zero_grad() #清空梯度信息,否則在每次進(jìn)行反向傳播時都會累加
loss.backward() #loss反向傳播
optimizer.step() ##梯度更新
batch+=1
print("Epoch: %d/%d || batch:%d/%d average_loss: %.3f || train_acc: %.2f"
%(epoch, 20, batch, float(int(50000/128)), average_loss, train_acc))
# 在測試集上檢驗(yàn)效果
net.eval() # 將模型改為預(yù)測模式
for idx,(im1, label1) in enumerate(test_data):
if torch.cuda.is_available():
im, label = im1.cuda(),label1.cuda()
out = net(im)
loss = criterion(out, label)
eval_loss = loss
pred = torch.max(out,1)[1]
num_correct = (pred == label).sum()
acc = (num_correct.float())/ 128
eval_acc = acc
print('EVA_Batch:{}, Eval Loss: {:.6f}, Eval Acc: {:.6f}'
.format(idx,eval_loss , eval_acc))
運(yùn)行結(jié)果:

到此這篇關(guān)于Pytorch框架實(shí)現(xiàn)mnist手寫庫識別(與tensorflow對比)的文章就介紹到這了,更多相關(guān)Pytorch框架實(shí)現(xiàn)mnist手寫庫識別(與tensorflow對比)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python利用watchdog模塊監(jiān)控文件變化
這篇文章主要為大家介紹一個Python中的模塊:watchdog模塊,它可以實(shí)現(xiàn)監(jiān)控文件的變化。文中通過示例詳細(xì)介紹了watchdog模塊的使用,需要的可以參考一下2022-06-06
使用python實(shí)現(xiàn)unix2dos和dos2unix命令的例子
今天小編就為大家分享一篇使用python實(shí)現(xiàn)unix2dos和dos2unix命令的例子,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-08-08
Python使用K-means實(shí)現(xiàn)文本聚類功能
最近遇到了這樣一個需求,將N個文本內(nèi)容聚類成若干個主題詞團(tuán),減少人工分析文本和分類文本的工作量,實(shí)現(xiàn)思路是使用?K-means算法通過高頻詞對文本內(nèi)容進(jìn)行聚類,K-means算法實(shí)現(xiàn)原理簡單易于理解,本文給大家介紹了Python使用K-means實(shí)現(xiàn)文本聚類功能,需要的朋友可以參考下2024-11-11
Python?一篇文章看懂Python集合與字典數(shù)據(jù)類型
集合并不是一種數(shù)據(jù)處理類型,而是一種中間類型。集合(set)是一個無序、不重復(fù)的元素序列,經(jīng)常被用來處理兩個列表進(jìn)行交并差的處理性。本文將詳細(xì)講解集合的一些常用方法,感興趣的可以了解一下2022-03-03

