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

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 人文社科 > 生活经验 >内容正文

生活经验

CV算法复现(分类算法1/6):LeNet5(1998年 LeCun)

發(fā)布時間:2023/11/27 生活经验 38 豆豆
生活随笔 收集整理的這篇文章主要介紹了 CV算法复现(分类算法1/6):LeNet5(1998年 LeCun) 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

致謝:霹靂吧啦Wz:https://space.bilibili.com/18161609

目錄

致謝:霹靂吧啦Wz:https://space.bilibili.com/18161609

1 本次要點

1.1 Python庫語法

1.2 Pytorch框架語法

2 環(huán)境

3 網(wǎng)絡(luò)結(jié)構(gòu)

4 代碼結(jié)構(gòu)

4.1 model.py

4.2 utils.py

4.3 train.py

4.4 test.py

?


1 本次要點

1.1 Python庫語法

  1. PIL 和 numpy 中維度順序:H*W*C
  2. enumerate() 函數(shù)用于將一個可遍歷的數(shù)據(jù)對象(如列表、元組或字符串)組合為一個索引序列,同時列出數(shù)據(jù)和數(shù)據(jù)下標,一般用在 for 循環(huán)當中。如
  3. with:上下文管理器。with 語句適用于對資源進行訪問的場合,相當于try….except….finlally,確保使用過程中不管是否發(fā)生異常都會執(zhí)行必要的“清理”操作,釋放資源,比如文件使用后自動關(guān)閉、線程中鎖的自動獲取和釋放等。
  4. :解決多層繼承中可能出現(xiàn)的一些問題。使用多繼承時,一般要用此函數(shù)。

1.2 Pytorch框架語法

  1. pytorch 中 tensor 維度順序:C*H*W
  2. optimizer.zero_grad():每計算一次batch后,要將歷史梯度清零,防止累加。

  3. item():得到元素張量里面的元素值。(將張量值變?yōu)榭捎嬎愕闹?#xff1f;)
  4. #不計算損失和梯度。(節(jié)省內(nèi)存和計算量)

?

2 環(huán)境

  • win10,GPU 1060 3G
  • pytorch 1.4
  • Python 3.6

3 網(wǎng)絡(luò)結(jié)構(gòu)

4 代碼結(jié)構(gòu)

  • model.py
  • utils.py
  • train.py
  • test.py
  • data(存放cifar數(shù)據(jù)集:需要解壓,不能更改壓縮包名字)
  • 1.jpg(測試圖)

4.1 model.py

import torch.nn as nn
import torch.nn.functional as Fclass LeNet(nn.Module):def __init__(self): #初始化函數(shù)super(LeNet, self).__init__() #super解決多層繼承中可能出現(xiàn)的一些問題。使用多繼承,一般要用此函數(shù)。self.conv1 = nn.Conv2d(3, 6, 5)self.pool1 = nn.MaxPool2d(2, 2)self.conv2 = nn.Conv2d(6, 16, 5)self.pool2 = nn.MaxPool2d(2, 2)self.fc1 = nn.Linear(16*5*5, 120) #輸入要展平成1維向量(16通道,每通道5*5特征圖)self.fc2 = nn.Linear(120, 84)self.fc3 = nn.Linear(84, 10)def forward(self, x): #x代表輸入的數(shù)據(jù)x = F.relu(self.conv1(x)) # input(3, 32, 32) output(6, 28, 28)x = self.pool1(x)         # output(6, 14, 14)x = F.relu(self.conv2(x)) # output(16, 10, 10)x = self.pool2(x)         # output(16, 5, 5)x = x.view(-1, 16*5*5)    # output(16*5*5 = 400)x = F.relu(self.fc1(x))   # output(120)x = F.relu(self.fc2(x))   # output(84)x = self.fc3(x)           # output(10)return x# # 測試網(wǎng)絡(luò)輸入輸出維度是否寫對
# import torch
# input1 = torch.rand([2, 3, 32, 32]) #B C H W
# print(input1)# model = LeNet()
# print(model)# output = model(input1)
# print(output)

4.2 utils.py

import torchvision.transforms as transformstransform_train = transforms.Compose([transforms.ToTensor(), #將數(shù)據(jù)轉(zhuǎn)為tensor,維度順序c*h*w, 值歸一化[0,1]transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)) # 再對數(shù)據(jù)進行標準化]
)transform_test = transforms.Compose([transforms.Resize((32, 32)),transforms.ToTensor(),transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))]
)clases_cifar10 = ('plane', 'car', 'bird', 'cat', 'deer''dog', 'frog', 'horse', 'ship', 'truck')

4.3 train.py

import torch
import torchvision
import torch.nn as nn
import torch.optim as optim
import torchvision.transforms as transformsimport matplotlib.pyplot as plt 
import numpy as np from utils import clases_cifar10, transform_train
from model import LeNet# 1 加載訓練集(5萬),預處理,打亂順序并分割成一批批的batch
train_data = torchvision.datasets.CIFAR10(root='M:/CV_data/cifar-10/', train=True,download=False, transform=transform_train)
# win系統(tǒng)下num_work要設(shè)為0.
train_loader = torch.utils.data.DataLoader(train_data, batch_size=32,shuffle=True, num_workers=0)# 2 加載驗證集(1萬),預處理,打亂順序并分割成1個batch
val_data = torchvision.datasets.CIFAR10(root='M:/CV_data/cifar-10/', train=False,download=False, transform=transform_train)
val_loader = torch.utils.data.DataLoader(val_data, batch_size=10000,shuffle=False, num_workers=0)
#創(chuàng)建迭代器對象(每次調(diào)用.next(),就會自動迭代集合中下一個元素,由于val集batch就1個,所以調(diào)用一次.next()就全部取完了)
val_data_iter = iter(val_loader)
val_images, val_labels = val_data_iter.next()# 3 初始化模型,損失函數(shù),優(yōu)化器
net = LeNet()
loss_function = nn.CrossEntropyLoss()
optimizer = optim.Adam(net.parameters(), lr=0.001)# 4 開始訓練
for epoch in range(5):running_loss = 0.0 #累加損失for step, data in enumerate(train_loader, start=0): #遍歷訓練數(shù)據(jù),并返回當前indexinputs, labels = data# 每計算一次batch, 將歷史梯度清零,防止累加。optimizer.zero_grad()# forward backward optimizeoutputs = net(inputs)loss = loss_function(outputs, labels)loss.backward()optimizer.step() # 參數(shù)更新# 打印訓練過程信息running_loss += loss.item() # item()得到元素張量里面的數(shù)值if step % 500 == 499:with torch.no_grad():#不計算損失和梯度。(節(jié)省內(nèi)存和計算量)outputs = net(val_images) #[batch=10000, 10]predict_y = torch.max(outputs, dim=1)[1]accuracy = (predict_y == val_labels).sum().item() / val_labels.size(0)print('[%d, %5d] train_loss: %.3f val_accuracy: %.3f' %(epoch + 1, step + 1, running_loss / 500, accuracy))running_loss = 0.0# 5 保存模型
print("finished training")
save_path = './Lenet.pth'
torch.save(net.state_dict(), save_path)

輸出

4.4 test.py

import torch
from PIL import Image
from model import LeNet
from utils import clases_cifar10, transform_testnet = LeNet()
net.load_state_dict(torch.load('Lenet.pth'))im = Image.open('1.jpg')
im = transform_test(im) # [c, h, w]
im = torch.unsqueeze(im, dim=0) # [n, c, h, w]with torch.no_grad(): # 此句可以不要,但大批量測試時,必須加此句,節(jié)省內(nèi)存和計算量。outputs = net(im) # 輸出值誰最大,預測的就是誰predict = torch.softmax(outputs, dim=1) # 將值轉(zhuǎn)換成預測概率print(predict)max_index = torch.max(predict, dim=1)[1].data.numpy() # 返回一個1*1數(shù)組。print(clases_cifar10[int(max_index)]) # 打印對應的便簽

輸出

?

總結(jié)

以上是生活随笔為你收集整理的CV算法复现(分类算法1/6):LeNet5(1998年 LeCun)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

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