欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

pytorch实现图像识别(实战)

程序员文章站 2023-08-13 21:03:19
目录1. 代码讲解1.1 导库1.2 标准化、transform、设置gpu1.3 预处理数据1.4 建立模型1.5 训练模型1.6 测试模型1.7结果1. 代码讲解1.1 导库import os.p...

1. 代码讲解

1.1 导库

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 标准化、transform、设置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])  # 转换

1.3 预处理数据

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

# 多少长图片
    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 = []
# 训练集图片路径
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))  
# 测试集图片路径
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)  
# 把字符标签离散化,因为数据有120种狗,不离散化后面把数据给模型时会报错:字符标签过多。把字符标签从0-119编号
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_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 = []  # 准确率

1.5 训练模型

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)
    # 计算损失
        loss_train = criterion(output_train, label)
        epoch_loss = epoch_loss + loss_train.item()
    # 计算精确率
        pred = torch.max(output_train, 1)[1]
        train_correct = (pred == label).sum()
        correct = correct + train_correct.item()
    # 梯度归零、反向传播、更新参数
        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 测试模型

和训练集差不多。

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结果

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

pytorch实现图像识别(实战)

到此这篇关于pytorch实现图像识别(实战)的文章就介绍到这了,更多相关pytorch实现图像识别内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!