用Pytorch訓(xùn)練CNN(數(shù)據(jù)集MNIST,使用GPU的方法)
聽(tīng)說(shuō)pytorch使用比TensorFlow簡(jiǎn)單,加之pytorch現(xiàn)已支持windows,所以今天裝了pytorch玩玩,第一件事還是寫了個(gè)簡(jiǎn)單的CNN在MNIST上實(shí)驗(yàn),初步體驗(yàn)的確比TensorFlow方便。
參考代碼(在莫煩python的教程代碼基礎(chǔ)上修改)如下:
import torch import torch.nn as nn from torch.autograd import Variable import torch.utils.data as Data import torchvision import time #import matplotlib.pyplot as plt torch.manual_seed(1) EPOCH = 1 BATCH_SIZE = 50 LR = 0.001 DOWNLOAD_MNIST = False if_use_gpu = 1 # 獲取訓(xùn)練集dataset training_data = torchvision.datasets.MNIST( root='./mnist/', # dataset存儲(chǔ)路徑 train=True, # True表示是train訓(xùn)練集,F(xiàn)alse表示test測(cè)試集 transform=torchvision.transforms.ToTensor(), # 將原數(shù)據(jù)規(guī)范化到(0,1)區(qū)間 download=DOWNLOAD_MNIST, ) # 打印MNIST數(shù)據(jù)集的訓(xùn)練集及測(cè)試集的尺寸 print(training_data.train_data.size()) print(training_data.train_labels.size()) # torch.Size([60000, 28, 28]) # torch.Size([60000]) #plt.imshow(training_data.train_data[0].numpy(), cmap='gray') #plt.title('%i' % training_data.train_labels[0]) #plt.show() # 通過(guò)torchvision.datasets獲取的dataset格式可直接可置于DataLoader train_loader = Data.DataLoader(dataset=training_data, batch_size=BATCH_SIZE, shuffle=True) # 獲取測(cè)試集dataset test_data = torchvision.datasets.MNIST( root='./mnist/', # dataset存儲(chǔ)路徑 train=False, # True表示是train訓(xùn)練集,F(xiàn)alse表示test測(cè)試集 transform=torchvision.transforms.ToTensor(), # 將原數(shù)據(jù)規(guī)范化到(0,1)區(qū)間 download=DOWNLOAD_MNIST, ) # 取前全部10000個(gè)測(cè)試集樣本 test_x = Variable(torch.unsqueeze(test_data.test_data, dim=1).float(), requires_grad=False) #test_x = test_x.cuda() ## (~, 28, 28) to (~, 1, 28, 28), in range(0,1) test_y = test_data.test_labels #test_y = test_y.cuda() class CNN(nn.Module): def __init__(self): super(CNN, self).__init__() self.conv1 = nn.Sequential( # (1,28,28) nn.Conv2d(in_channels=1, out_channels=16, kernel_size=5, stride=1, padding=2), # (16,28,28) # 想要con2d卷積出來(lái)的圖片尺寸沒(méi)有變化, padding=(kernel_size-1)/2 nn.ReLU(), nn.MaxPool2d(kernel_size=2) # (16,14,14) ) self.conv2 = nn.Sequential( # (16,14,14) nn.Conv2d(16, 32, 5, 1, 2), # (32,14,14) nn.ReLU(), nn.MaxPool2d(2) # (32,7,7) ) self.out = nn.Linear(32*7*7, 10) def forward(self, x): x = self.conv1(x) x = self.conv2(x) x = x.view(x.size(0), -1) # 將(batch,32,7,7)展平為(batch,32*7*7) output = self.out(x) return output cnn = CNN() if if_use_gpu: cnn = cnn.cuda() optimizer = torch.optim.Adam(cnn.parameters(), lr=LR) loss_function = nn.CrossEntropyLoss() for epoch in range(EPOCH): start = time.time() for step, (x, y) in enumerate(train_loader): b_x = Variable(x, requires_grad=False) b_y = Variable(y, requires_grad=False) if if_use_gpu: b_x = b_x.cuda() b_y = b_y.cuda() output = cnn(b_x) loss = loss_function(output, b_y) optimizer.zero_grad() loss.backward() optimizer.step() if step % 100 == 0: print('Epoch:', epoch, '|Step:', step, '|train loss:%.4f'%loss.data[0]) duration = time.time() - start print('Training duation: %.4f'%duration) cnn = cnn.cpu() test_output = cnn(test_x) pred_y = torch.max(test_output, 1)[1].data.squeeze() accuracy = sum(pred_y == test_y) / test_y.size(0) print('Test Acc: %.4f'%accuracy)
以上這篇用Pytorch訓(xùn)練CNN(數(shù)據(jù)集MNIST,使用GPU的方法)就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
- pytorch實(shí)現(xiàn)mnist數(shù)據(jù)集的圖像可視化及保存
- 關(guān)于Pytorch的MNIST數(shù)據(jù)集的預(yù)處理詳解
- pytorch:實(shí)現(xiàn)簡(jiǎn)單的GAN示例(MNIST數(shù)據(jù)集)
- 使用 PyTorch 實(shí)現(xiàn) MLP 并在 MNIST 數(shù)據(jù)集上驗(yàn)證方式
- 詳解PyTorch手寫數(shù)字識(shí)別(MNIST數(shù)據(jù)集)
- pytorch 把MNIST數(shù)據(jù)集轉(zhuǎn)換成圖片和txt的方法
- Python PyTorch 如何獲取 MNIST 數(shù)據(jù)
相關(guān)文章
Python中使用pprint函數(shù)進(jìn)行格式化輸出的教程
這篇文章主要介紹了Python中使用pprint函數(shù)進(jìn)行格式化輸出的教程,包括能夠控制輸出寬度等非常有用的特性,需要的朋友可以參考下2015-04-04深入解析python中的實(shí)例方法、類方法和靜態(tài)方法
這篇文章主要介紹了python中的實(shí)例方法、類方法和靜態(tài)方法,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-03-03Django利用AJAX技術(shù)實(shí)現(xiàn)博文實(shí)時(shí)搜索
這篇文章主要介紹了Django如何利用AJAX技術(shù)實(shí)現(xiàn)博文實(shí)時(shí)搜索,幫助大家更好的理解和學(xué)習(xí)使用Django框架,感興趣的朋友可以了解下2021-05-05tensorflow通過(guò)模型文件,使用tensorboard查看其模型圖Graph方式
今天小編就為大家分享一篇tensorflow通過(guò)模型文件,使用tensorboard查看其模型圖Graph方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-01-01Python之Scrapy爬蟲框架安裝及簡(jiǎn)單使用詳解
這篇文章主要介紹了Python之Scrapy爬蟲框架安裝及簡(jiǎn)單使用詳解,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2017-12-12keras 兩種訓(xùn)練模型方式詳解fit和fit_generator(節(jié)省內(nèi)存)
這篇文章主要介紹了keras 兩種訓(xùn)練模型方式詳解fit和fit_generator(節(jié)省內(nèi)存),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-07-07python實(shí)現(xiàn)word/excel/ppt批量轉(zhuǎn)pdf的示例代碼
這篇文章主要為大家詳細(xì)介紹了如何利用python實(shí)現(xiàn)word、excel、ppt批量轉(zhuǎn)pdf文件,文中的示例代碼講解詳細(xì),有需要的小伙伴可以參考下2023-09-09