日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

PyTorch基础(part4)

發(fā)布時間:2023/12/19 编程问答 24 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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表示圖像的尺寸.
len(train_loader) 938 labels tensor([9, 3, 8, 1, 1, 3, 0, 4, 7, 4, 8, 4, 6, 4, 8, 5, 0, 0, 2, 0, 1, 6, 8, 3,3, 6, 6, 5, 0, 6, 7, 0, 5, 3, 8, 3, 2, 5, 9, 9, 1, 5, 4, 3, 8, 3, 1, 3,1, 7, 8, 6, 5, 3, 9, 4, 2, 7, 0, 1, 9, 1, 0, 0])

定義網(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)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。