最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

pytorch如何利用ResNet18進(jìn)行手寫數(shù)字識別

 更新時間:2023年02月02日 16:21:51   作者:愛聽許嵩歌  
這篇文章主要介紹了pytorch如何利用ResNet18進(jìn)行手寫數(shù)字識別問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教

利用ResNet18進(jìn)行手寫數(shù)字識別

先寫resnet18.py

代碼如下:

import torch
from torch import nn
from torch.nn import functional as F


class ResBlk(nn.Module):
? ? """
? ? resnet block
? ? """

? ? def __init__(self, ch_in, ch_out, stride=1):
? ? ? ? """

? ? ? ? :param ch_in:
? ? ? ? :param ch_out:
? ? ? ? """
? ? ? ? super(ResBlk, self).__init__()

? ? ? ? self.conv1 = nn.Conv2d(ch_in, ch_out, kernel_size=3, stride=stride, padding=1)
? ? ? ? self.bn1 = nn.BatchNorm2d(ch_out)
? ? ? ? self.conv2 = nn.Conv2d(ch_out, ch_out, kernel_size=3, stride=1, padding=1)
? ? ? ? self.bn2 = nn.BatchNorm2d(ch_out)

? ? ? ? self.extra = nn.Sequential()

? ? ? ? if ch_out != ch_in:
? ? ? ? ? ? # [b, ch_in, h, w] => [b, ch_out, h, w]
? ? ? ? ? ? self.extra = nn.Sequential(
? ? ? ? ? ? ? ? nn.Conv2d(ch_in, ch_out, kernel_size=1, stride=stride),
? ? ? ? ? ? ? ? nn.BatchNorm2d(ch_out)
? ? ? ? ? ? )

? ? def forward(self, x):
? ? ? ? """

? ? ? ? :param x: [b, ch, h, w]
? ? ? ? :return:
? ? ? ? """
? ? ? ? out = F.relu(self.bn1(self.conv1(x)))
? ? ? ? out = self.bn2(self.conv2(out))

? ? ? ? # short cut
? ? ? ? # extra module:[b, ch_in, h, w] => [b, ch_out, h, w]
? ? ? ? # element-wise add:
? ? ? ? out = self.extra(x) + out
? ? ? ? out = F.relu(out)

? ? ? ? return out


class ResNet18(nn.Module):
? ? def __init__(self):
? ? ? ? super(ResNet18, self).__init__()

? ? ? ? self.conv1 = nn.Sequential(
? ? ? ? ? ? nn.Conv2d(1, 64, kernel_size=3, stride=3, padding=0),
? ? ? ? ? ? nn.BatchNorm2d(64)
? ? ? ? )
? ? ? ? # followed 4 blocks

? ? ? ? # [b, 64, h, w] => [b, 128, h, w]
? ? ? ? self.blk1 = ResBlk(64, 128, stride=2)

? ? ? ? # [b, 128, h, w] => [b, 256, h, w]
? ? ? ? self.blk2 = ResBlk(128, 256, stride=2)

? ? ? ? # [b, 256, h, w] => [b, 512, h, w]
? ? ? ? self.blk3 = ResBlk(256, 512, stride=2)

? ? ? ? # [b, 512, h, w] => [b, 512, h, w]
? ? ? ? self.blk4 = ResBlk(512, 512, stride=2)

? ? ? ? self.outlayer = nn.Linear(512 * 1 * 1, 10)

? ? def forward(self, x):
? ? ? ? """

? ? ? ? :param x:
? ? ? ? :return:
? ? ? ? """
? ? ? ? # [b, 1, h, w] => [b, 64, h, w]
? ? ? ? x = F.relu(self.conv1(x))

? ? ? ? # [b, 64, h, w] => [b, 512, h, w]
? ? ? ? x = self.blk1(x)
? ? ? ? x = self.blk2(x)
? ? ? ? x = self.blk3(x)
? ? ? ? x = self.blk4(x)

? ? ? ? # print(x.shape) # [b, 512, 1, 1]
? ? ? ? # 意思就是不管之前的特征圖尺寸為多少,只要設(shè)置為(1,1),那么最終特征圖大小都為(1,1)
? ? ? ? # [b, 512, h, w] => [b, 512, 1, 1]
? ? ? ? x = F.adaptive_avg_pool2d(x, [1, 1])
? ? ? ? x = x.view(x.size(0), -1)
? ? ? ? x = self.outlayer(x)

? ? ? ? return x


def main():
? ? blk = ResBlk(1, 128, stride=4)
? ? tmp = torch.randn(512, 1, 28, 28)
? ? out = blk(tmp)
? ? print('blk', out.shape)

? ? model = ResNet18()
? ? x = torch.randn(512, 1, 28, 28)
? ? out = model(x)
? ? print('resnet', out.shape)
? ? print(model)


if __name__ == '__main__':
? ? main()

再寫繪圖utils.py

代碼如下

import torch
from matplotlib import pyplot as plt

device = torch.device('cuda')


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).cuda()
? ? idx = label.view(-1, 1)
? ? out.scatter_(dim=1, index=idx, value=1)
? ? return out

最后是主函數(shù)mnist_train.py

代碼如下:

import torch
from torch import nn
from torch.nn import functional as F
from torch import optim
from resnet18 import ResNet18

import torchvision
from matplotlib import pyplot as plt

from utils import plot_image, plot_curve, one_hot

batch_size = 512

# 加載數(shù)據(jù)
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)

# 在裝載完成后,我們可以選取其中一個批次的數(shù)據(jù)進(jìn)行預(yù)覽
x, y = next(iter(train_loader))

# x:[512, 1, 28, 28], y:[512]
print(x.shape, y.shape, x.min(), x.max())
plot_image(x, y, 'image sample')

device = torch.device('cuda')

net = ResNet18().to(device)

optimizer = optim.SGD(net.parameters(), lr=0.01, momentum=0.9)

train_loss = []

for epoch in range(5):

? ? # 訓(xùn)練
? ? net.train()
? ? for batch_idx, (x, y) in enumerate(train_loader):

? ? ? ? # x: [b, 1, 28, 28], y: [512]
? ? ? ? # [b, 1, 28, 28] => [b, 10]
? ? ? ? x, y = x.to(device), y.to(device)
? ? ? ? out = net(x)
? ? ? ? # [b, 10]
? ? ? ? y_onehot = one_hot(y)
? ? ? ? # loss = mse(out, y_onehot)
? ? ? ? loss = F.mse_loss(out, y_onehot).to(device)
? ? ? ? # 先給梯度清0
? ? ? ? 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]

# 測試
net.eval()
total_correct = 0
for x, y in test_loader:
? ? x, y = x.cuda(), y.cuda()
? ? out = net(x)
? ? # out: [b, 10] => pred: [b]
? ? 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('test acc:', acc)

x, y = next(iter(test_loader))
x, y = x.cuda(), y.cuda()
out = net(x)
pred = out.argmax(dim=1)
x = x.cpu()
pred = pred.cpu()
plot_image(x, pred, 'test')

結(jié)果為:

4 90 0.009581390768289566
4 100 0.010348389856517315
4 110 0.01111914124339819
test acc: 0.9703

運(yùn)行時注意把模型和參數(shù)放在GPU里,這樣節(jié)省時間,此代碼作為測試代碼,僅供參考。

總結(jié)

以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。

相關(guān)文章

  • python GUI庫圖形界面開發(fā)之PyQt5窗口類QMainWindow詳細(xì)使用方法

    python GUI庫圖形界面開發(fā)之PyQt5窗口類QMainWindow詳細(xì)使用方法

    這篇文章主要介紹了python GUI庫圖形界面開發(fā)之PyQt5窗口類QMainWindow詳細(xì)使用方法,需要的朋友可以參考下
    2020-02-02
  • 一文搞定Scrapy和Selenium整合使用

    一文搞定Scrapy和Selenium整合使用

    Scrapy和Selenium都是常用的Python爬蟲框架,下面這篇文章主要給大家介紹了關(guān)于如何通過一文搞定Scrapy和Selenium整合使用的相關(guān)資料,文中通過實例代碼介紹的非常詳細(xì),需要的朋友可以參考下
    2023-06-06
  • 基于FME使用Python過程圖解

    基于FME使用Python過程圖解

    這篇文章主要介紹了基于FME使用Python過程圖解,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
    2020-05-05
  • django項目運(yùn)行因中文而亂碼報錯的幾種情況解決

    django項目運(yùn)行因中文而亂碼報錯的幾種情況解決

    django是一個不錯的WEB開源框架。今天測試,發(fā)現(xiàn)有些頁面中文亂碼,后來發(fā)現(xiàn)出現(xiàn)中文亂碼還不止一種情況,所以這篇文章主要給大家介紹了關(guān)于django項目運(yùn)行過程中因為中文而導(dǎo)致亂碼報錯的幾種情況的解決方法,需要的朋友可以參考下。
    2017-11-11
  • python處理SQLite數(shù)據(jù)庫的方法

    python處理SQLite數(shù)據(jù)庫的方法

    這篇文章主要介紹了python處理SQLite數(shù)據(jù)庫的方法,python處理數(shù)據(jù)庫非常簡單。而且不同類型的數(shù)據(jù)庫處理邏輯方式大同小異。本文以sqlite數(shù)據(jù)庫為例,介紹一下python操作數(shù)據(jù)庫的方,需要的朋友可以參考下,希望能幫助到大家
    2022-02-02
  • python3利用Dlib19.7實現(xiàn)人臉68個特征點(diǎn)標(biāo)定

    python3利用Dlib19.7實現(xiàn)人臉68個特征點(diǎn)標(biāo)定

    這篇文章主要為大家詳細(xì)介紹了python3利用Dlib19.7實現(xiàn)人臉68個特征點(diǎn)標(biāo)定,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2018-02-02
  • python數(shù)據(jù)處理實戰(zhàn)(必看篇)

    python數(shù)據(jù)處理實戰(zhàn)(必看篇)

    下面小編就為大家?guī)硪黄猵ython數(shù)據(jù)處理實戰(zhàn)(必看篇)。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2017-06-06
  • 利用Pytorch實現(xiàn)簡單的線性回歸算法

    利用Pytorch實現(xiàn)簡單的線性回歸算法

    今天小編就為大家分享一篇利用Pytorch實現(xiàn)簡單的線性回歸算法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-01-01
  • Python 數(shù)值區(qū)間處理_對interval 庫的快速入門詳解

    Python 數(shù)值區(qū)間處理_對interval 庫的快速入門詳解

    今天小編就為大家分享一篇Python 數(shù)值區(qū)間處理_對interval 庫的快速入門詳解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2018-11-11
  • 如何使用repr調(diào)試python程序

    如何使用repr調(diào)試python程序

    這篇文章主要介紹了如何使用repr調(diào)試python程序,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
    2020-02-02

最新評論

洪江市| 封丘县| 乌拉特后旗| 奉节县| 日照市| 土默特右旗| 遵化市| 隆昌县| 泰宁县| 乐亭县| 当涂县| 汉中市| 扬州市| 驻马店市| 嘉荫县| 平阴县| 迭部县| 青州市| 安陆市| 大英县| 兴海县| 牙克石市| 潜江市| 革吉县| 都昌县| 利辛县| 峡江县| 长丰县| 来凤县| 弋阳县| 海门市| 金坛市| 乐东| 方山县| 东阳市| 泗洪县| 林口县| 新绛县| 斗六市| 宁强县| 淮阳县|