PyTorch基础(part4)
生活随笔
收集整理的這篇文章主要介紹了
PyTorch基础(part4)
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
學(xué)習(xí)筆記,僅供參考,有錯必糾
文章目錄
- PyTorch 基礎(chǔ)
- MNIST數(shù)據(jù)識別
- 常用代碼
- 導(dǎo)包
- 載入數(shù)據(jù)
- 定義網(wǎng)絡(luò)結(jié)構(gòu)
PyTorch 基礎(chǔ)
MNIST數(shù)據(jù)識別
常用代碼
# 支持多行輸出 from IPython.core.interactiveshell import InteractiveShell InteractiveShell.ast_node_interactivity = 'all' #默認(rèn)為'last'導(dǎo)包
# 導(dǎo)入常用的包 import torch from torch import nn,optim import numpy as np import matplotlib.pyplot as plt from torch.autograd import Variable from torchvision import datasets, transforms from torch.utils.data import DataLoader載入數(shù)據(jù)
# 載入數(shù)據(jù) train_dataset = datasets.MNIST(root = './data/', # 載入的數(shù)據(jù)存放的位置train = True, # 載入訓(xùn)練集數(shù)據(jù)transform = transforms.ToTensor(), # 將載入進(jìn)來的數(shù)據(jù)變成Tensordownload = True) # 是否下載數(shù)據(jù) test_dataset = datasets.MNIST(root = './data/', # 載入的數(shù)據(jù)存放的位置train = False, # 載入測試集數(shù)據(jù)transform = transforms.ToTensor(), # 將載入進(jìn)來的數(shù)據(jù)變成Tensordownload = True) # 是否下載數(shù)據(jù) Downloading http://yann.lecun.com/exdb/mnist/train-images-idx3-ubyte.gz Downloading http://yann.lecun.com/exdb/mnist/train-images-idx3-ubyte.gz to ./data/MNIST\raw\train-images-idx3-ubyte.gz31.0%IOPub message rate exceeded. The notebook server will temporarily stop sending output to the client in order to avoid crashing it. To change this limit, set the config variable `--NotebookApp.iopub_msg_rate_limit`. 89.6%IOPub message rate exceeded. The notebook server will temporarily stop sending output to the client in order to avoid crashing it. To change this limit, set the config variable `--NotebookApp.iopub_msg_rate_limit`. 100.0%Extracting ./data/MNIST\raw\t10k-images-idx3-ubyte.gz to ./data/MNIST\rawDownloading http://yann.lecun.com/exdb/mnist/t10k-labels-idx1-ubyte.gz Downloading http://yann.lecun.com/exdb/mnist/t10k-labels-idx1-ubyte.gz to ./data/MNIST\raw\t10k-labels-idx1-ubyte.gz112.7%Extracting ./data/MNIST\raw\t10k-labels-idx1-ubyte.gz to ./data/MNIST\raw?
?
# 設(shè)置每次訓(xùn)練的批次大小 batch_size = 64 # 數(shù)據(jù)生成器(打亂數(shù)據(jù)集, 并每次迭代返回一個批次的數(shù)據(jù)) train_loader = DataLoader(dataset = train_dataset,batch_size = batch_size,shuffle = True) test_loader = DataLoader(dataset = test_dataset,batch_size = batch_size,shuffle = True) # 查看數(shù)據(jù)生成器的內(nèi)部結(jié)構(gòu) for i, data in enumerate(train_loader):inputs, labels = dataprint("批次:", i)print("輸入數(shù)據(jù)的形狀:", inputs.shape)print("標(biāo)簽的形狀:", labels.shape)break 批次: 0 輸入數(shù)據(jù)的形狀: torch.Size([64, 1, 28, 28]) 標(biāo)簽的形狀: torch.Size([64])torch.Size([64, 1, 28, 28]) 中:
- 64代表包含的樣本數(shù);
- 1代表通道數(shù),如果圖像為黑白圖像,那么通道數(shù)為1,如果圖像為彩色圖像,那么通道數(shù)為3;
- 最后兩個數(shù)值28, 28表示圖像的尺寸.
定義網(wǎng)絡(luò)結(jié)構(gòu)
class MyNet(nn.Module):def __init__(self):super(MyNet, self).__init__()self.fc1 = nn.Linear(784, 10)self.softmax = nn.Softmax(dim = 1) # 輸出的維度為(64, 10), 對維度dim = 1進(jìn)行概率轉(zhuǎn)換,使其和為1def forward(self, x):x = x.view(x.size()[0], -1)x = self.fc1(x)out = self.softmax(x)return out LR = 0.5 # 定義模型 model = MyNet() # 定義代價函數(shù) mse_loss = nn.MSELoss() # 定義優(yōu)化器 optimizer = optim.SGD(model.parameters(), lr = LR) # 定義訓(xùn)練 def train():for i, data in enumerate(train_loader):# 或者某個批次的數(shù)據(jù)和標(biāo)簽inputs, labels = data# 獲取預(yù)測結(jié)果out = model(inputs)# 把數(shù)據(jù)標(biāo)簽標(biāo)稱獨(dú)熱編碼labels = labels.reshape(-1, 1)one_hot = torch.zeros(inputs.shape[0], 10).scatter(1, labels, 1)# tensor.scatter(dim, index, src) # dim:對哪個維度進(jìn)行獨(dú)熱編碼# index:要將src中對應(yīng)的值放到tensor的哪個位置。# src:插入index的數(shù)值 # 計算 lossloss = mse_loss(out, one_hot)# 梯度清0optimizer.zero_grad()# 計算梯度loss.backward()# 修改權(quán)值optimizer.step() # 定義測試 def test():correct = 0for i, data in enumerate(test_loader):inputs, labels = dataout = model(inputs)# 獲得最大值,以及最大值所在的位置_, predicted = torch.max(out, 1)# 預(yù)測正確的數(shù)量correct += (predicted == labels).sum()print("Test Acc:{0}".format(correct.item()/len(test_dataset))) for epoch in range(10):print("epoch:", epoch)train()test() epoch: 0 Test Acc:0.8882 epoch: 1 Test Acc:0.9 epoch: 2 Test Acc:0.9078 epoch: 3 Test Acc:0.911 epoch: 4 Test Acc:0.9145 epoch: 5 Test Acc:0.9159 epoch: 6 Test Acc:0.9168 epoch: 7 Test Acc:0.9179 epoch: 8 Test Acc:0.9184 epoch: 9 Test Acc:0.9195總結(jié)
以上是生活随笔為你收集整理的PyTorch基础(part4)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: PyTorch基础(part3)
- 下一篇: en_core_web_sm下载