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

pytorch實(shí)現(xiàn)圖像識(shí)別(實(shí)戰(zhàn))

 更新時(shí)間:2022年02月18日 08:41:51   作者:AI?AX?AT  
這篇文章主要介紹了pytorch實(shí)現(xiàn)圖像識(shí)別(實(shí)戰(zhàn)),文章主要分享實(shí)現(xiàn)代碼,但也具有一定的參考價(jià)值,需要的小伙伴可以才可以一下,希望對(duì)你有所幫助

1. 代碼講解

1.1 導(dǎo)庫(kù)

import os.path
from os import listdir
import numpy as np
import pandas as pd
from PIL import Image
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.nn import AdaptiveAvgPool2d
from torch.utils.data.sampler import SubsetRandomSampler
from torch.utils.data import Dataset
import torchvision.transforms as transforms
from sklearn.model_selection import train_test_split

1.2 標(biāo)準(zhǔn)化、transform、設(shè)置GPU

device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
normalize = transforms.Normalize(
? ?mean=[0.485, 0.456, 0.406],
? ?std=[0.229, 0.224, 0.225]
)
transform = transforms.Compose([transforms.ToTensor(), normalize]) ?# 轉(zhuǎn)換

1.3 預(yù)處理數(shù)據(jù)

class DogDataset(Dataset):
# 定義變量
? ? def __init__(self, img_paths, img_labels, size_of_images): ?
? ? ? ? self.img_paths = img_paths
? ? ? ? self.img_labels = img_labels
? ? ? ? self.size_of_images = size_of_images

# 多少長(zhǎng)圖片
? ? def __len__(self):
? ? ? ? return len(self.img_paths)

# 打開每組圖片并處理每張圖片
? ? def __getitem__(self, index):
? ? ? ? PIL_IMAGE = Image.open(self.img_paths[index]).resize(self.size_of_images)
? ? ? ? TENSOR_IMAGE = transform(PIL_IMAGE)
? ? ? ? label = self.img_labels[index]
? ? ? ? return TENSOR_IMAGE, label


print(len(listdir(r'C:\Users\AIAXIT\Desktop\DeepLearningProject\Deep_Learning_Data\dog-breed-identification\train')))
print(len(pd.read_csv(r'C:\Users\AIAXIT\Desktop\DeepLearningProject\Deep_Learning_Data\dog-breed-identification\labels.csv')))
print(len(listdir(r'C:\Users\AIAXIT\Desktop\DeepLearningProject\Deep_Learning_Data\dog-breed-identification\test')))

train_paths = []
test_paths = []
labels = []
# 訓(xùn)練集圖片路徑
train_paths_lir = r'C:\Users\AIAXIT\Desktop\DeepLearningProject\Deep_Learning_Data\dog-breed-identification\train'
for path in listdir(train_paths_lir):
? ? train_paths.append(os.path.join(train_paths_lir, path)) ?
# 測(cè)試集圖片路徑
labels_data = pd.read_csv(r'C:\Users\AIAXIT\Desktop\DeepLearningProject\Deep_Learning_Data\dog-breed-identification\labels.csv')
labels_data = pd.DataFrame(labels_data) ?
# 把字符標(biāo)簽離散化,因?yàn)閿?shù)據(jù)有120種狗,不離散化后面把數(shù)據(jù)給模型時(shí)會(huì)報(bào)錯(cuò):字符標(biāo)簽過多。把字符標(biāo)簽從0-119編號(hào)
size_mapping = {}
value = 0
size_mapping = dict(labels_data['breed'].value_counts())
for kay in size_mapping:
? ? size_mapping[kay] = value
? ? value += 1
# print(size_mapping)
labels = labels_data['breed'].map(size_mapping)
labels = list(labels)
# print(labels)
print(len(labels))
# 劃分訓(xùn)練集和測(cè)試集
X_train, X_test, y_train, y_test = train_test_split(train_paths, labels, test_size=0.2)

train_set = DogDataset(X_train, y_train, (32, 32))
test_set = DogDataset(X_test, y_test, (32, 32))

train_loader = torch.utils.data.DataLoader(train_set, batch_size=64)
test_loader = torch.utils.data.DataLoader(test_set, batch_size=64)

1.4 建立模型

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

? ? ? ? self.features = nn.Sequential(
? ? ? ? ? ? nn.Conv2d(in_channels=3, out_channels=6, kernel_size=5), ?
? ? ? ? ? ? nn.ReLU(),
? ? ? ? ? ? nn.AvgPool2d(kernel_size=2, stride=2),
? ? ? ? ? ? nn.Conv2d(in_channels=6, out_channels=16, kernel_size=5),
? ? ? ? ? ? nn.ReLU(),
? ? ? ? ? ? nn.AvgPool2d(kernel_size=2, stride=2)
? ? ? ? )
? ? ? ? self.classifier = nn.Sequential(
? ? ? ? ? ? nn.Linear(16 * 5 * 5, 120),
? ? ? ? ? ? nn.ReLU(),
? ? ? ? ? ? nn.Linear(120, 84),
? ? ? ? ? ? nn.ReLU(),
? ? ? ? ? ? nn.Linear(84, 120)
? ? ? ? )

? ? def forward(self, x):
? ? ? ? batch_size = x.shape[0]
? ? ? ? x = self.features(x)
? ? ? ? x = x.view(batch_size, -1)
? ? ? ? x = self.classifier(x)
? ? ? ? return x


model = LeNet().to(device)
criterion = nn.CrossEntropyLoss().to(device)
optimizer = optim.Adam(model.parameters())
TRAIN_LOSS = [] ?# 損失
TRAIN_ACCURACY = [] ?# 準(zhǔn)確率

1.5 訓(xùn)練模型

def train(epoch):
? ? model.train()
? ? epoch_loss = 0.0 # 損失
? ? correct = 0 ?# 精確率
? ? for batch_index, (Data, Label) in enumerate(train_loader):
? ? # 扔到GPU中
? ? ? ? Data = Data.to(device)
? ? ? ? Label = Label.to(device)
? ? ? ? output_train = model(Data)
? ? # 計(jì)算損失
? ? ? ? loss_train = criterion(output_train, Label)
? ? ? ? epoch_loss = epoch_loss + loss_train.item()
? ? # 計(jì)算精確率
? ? ? ? pred = torch.max(output_train, 1)[1]
? ? ? ? train_correct = (pred == Label).sum()
? ? ? ? correct = correct + train_correct.item()
? ? # 梯度歸零、反向傳播、更新參數(shù)
? ? ? ? optimizer.zero_grad()
? ? ? ? loss_train.backward()
? ? ? ? optimizer.step()
? ? print('Epoch: ', epoch, 'Train_loss: ', epoch_loss / len(train_set), 'Train correct: ', correct / len(train_set))

1.6 測(cè)試模型

和訓(xùn)練集差不多。

def test():
? ? model.eval()
? ? correct = 0.0
? ? test_loss = 0.0
? ? with torch.no_grad():
? ? ? ? for Data, Label in test_loader:
? ? ? ? ? ? Data = Data.to(device)
? ? ? ? ? ? Label = Label.to(device)
? ? ? ? ? ? test_output = model(Data)
? ? ? ? ? ? loss = criterion(test_output, Label)
? ? ? ? ? ? pred = torch.max(test_output, 1)[1]
? ? ? ? ? ? test_correct = (pred == Label).sum()
? ? ? ? ? ? correct = correct + test_correct.item()
? ? ? ? ? ? test_loss = test_loss + loss.item()
? ? print('Test_loss: ', test_loss / len(test_set), 'Test correct: ', correct / len(test_set))

1.7結(jié)果

epoch = 10
for n_epoch in range(epoch):
? ? train(n_epoch)
test()

到此這篇關(guān)于pytorch實(shí)現(xiàn)圖像識(shí)別(實(shí)戰(zhàn))的文章就介紹到這了,更多相關(guān)pytorch實(shí)現(xiàn)圖像識(shí)別內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • python中property屬性的介紹及其應(yīng)用詳解

    python中property屬性的介紹及其應(yīng)用詳解

    這篇文章主要介紹了python中property屬性的介紹及其應(yīng)用詳解,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2019-08-08
  • 如何使用python自帶IDLE的幾種方法

    如何使用python自帶IDLE的幾種方法

    這篇文章主要介紹了如何使用python自帶IDLE的幾種方法,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-10-10
  • python計(jì)算auc指標(biāo)實(shí)例

    python計(jì)算auc指標(biāo)實(shí)例

    下面小編就為大家?guī)硪黄猵ython計(jì)算auc指標(biāo)實(shí)例。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧
    2017-07-07
  • python機(jī)器學(xué)習(xí)Sklearn實(shí)戰(zhàn)adaboost算法示例詳解

    python機(jī)器學(xué)習(xí)Sklearn實(shí)戰(zhàn)adaboost算法示例詳解

    這篇文章主要為大家介紹了python機(jī)器學(xué)習(xí)Sklearn實(shí)戰(zhàn)adaboost算法的示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步早日升職加薪
    2021-11-11
  • python?Pandas庫(kù)read_excel()參數(shù)實(shí)例詳解

    python?Pandas庫(kù)read_excel()參數(shù)實(shí)例詳解

    人們經(jīng)常用pandas處理表格型數(shù)據(jù),時(shí)常需要讀入excel表格數(shù)據(jù),下面這篇文章主要給大家介紹了關(guān)于python?Pandas庫(kù)read_excel()參數(shù)的相關(guān)資料,文中通過實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下
    2022-07-07
  • 淺析AST抽象語(yǔ)法樹及Python代碼實(shí)現(xiàn)

    淺析AST抽象語(yǔ)法樹及Python代碼實(shí)現(xiàn)

    Abstract Syntax Tree抽象語(yǔ)法樹簡(jiǎn)寫為ATS,是相當(dāng)于用樹結(jié)構(gòu)將代碼程式表現(xiàn)出來的一種數(shù)據(jù)結(jié)構(gòu),這里我們就來淺析AST抽象語(yǔ)法樹及Python代碼實(shí)現(xiàn)
    2016-06-06
  • python版學(xué)生管理系統(tǒng)

    python版學(xué)生管理系統(tǒng)

    這篇文章主要為大家詳細(xì)介紹了python版學(xué)生管理系統(tǒng),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2018-01-01
  • Python實(shí)用秘技之快速優(yōu)化導(dǎo)包順序詳解

    Python實(shí)用秘技之快速優(yōu)化導(dǎo)包順序詳解

    這篇文章主要來和大家分享一個(gè)Python中的實(shí)用秘技,那就是如何快速優(yōu)化導(dǎo)包順序,文中的示例代碼簡(jiǎn)潔易懂,快跟隨小編一起學(xué)習(xí)起來吧
    2023-06-06
  • python中concurrent.futures的具體使用

    python中concurrent.futures的具體使用

    concurrent.futures是Python標(biāo)準(zhǔn)庫(kù)的一部分,提供了ThreadPoolExecutor和ProcessPoolExecutor兩種執(zhí)行器,用于管理線程池和進(jìn)程池,通過這些執(zhí)行器,可以簡(jiǎn)化多線程和多進(jìn)程任務(wù)的管理,提高程序執(zhí)行效率
    2024-09-09
  • Numpy實(shí)現(xiàn)矩陣運(yùn)算及線性代數(shù)應(yīng)用

    Numpy實(shí)現(xiàn)矩陣運(yùn)算及線性代數(shù)應(yīng)用

    這篇文章主要介紹了Numpy實(shí)現(xiàn)矩陣運(yùn)算及線性代數(shù)應(yīng)用,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2021-03-03

最新評(píng)論

东乡族自治县| 仁寿县| 井冈山市| 鄂尔多斯市| 杂多县| 内丘县| 嵊州市| 舒城县| 金湖县| 万宁市| 邵阳市| 莱州市| 海门市| 宣化县| 两当县| 长泰县| 长治市| 互助| 蒲江县| 新化县| 青田县| 科技| 托克逊县| 孟连| 商丘市| 红桥区| 平安县| 上栗县| 大荔县| 亳州市| 恩施市| 曲麻莱县| 永春县| 安达市| 新丰县| 乡宁县| 崇左市| 临洮县| 金平| 清水河县| 潍坊市|