P10打卡——pytorch实现车牌识别

1.检查GPU

from torchvision.transforms import transforms
from torch.utils.data import DataLoader
from torchvision import datasets
import torchvision.models as models
import torch.nn.functional as F
import torch.nn as nn
import torch,torchvision
device=torch.device("cuda" if torch.cuda.is_available() else "cpu")
device

​​​

2.查看数据

import os,PIL,random,pathlib
import matplotlib.pyplot as plt
# 支持中文
plt.rcParams['font.sans-serif'] = ['SimHei']  # 用来正常显示中文标签
plt.rcParams['axes.unicode_minus'] = False  # 用来正常显示负号

data_dir='data/015_licence_plate'
data_dir = pathlib.Path(data_dir)
data_paths  = list(data_dir.glob('*'))
classeNames = [str(path).split("\\")[2].split("_")[1].split(".")[0] for path in data_paths]
print(classeNames)

data_paths=list(data_dir.glob('*'))
data_paths_str=[str(path) for path in data_paths]
data_paths_str

plt.figure(figsize=(14,5))
plt.suptitle("数据示例)",fontsize=15)
for i in range(18):
    plt.subplot(3,6,i+1)
    images=plt.imread(data_paths_str[i])
    plt.imshow(images)
plt.show()

3.划分数据集

python 复制代码
import numpy as np
char_enum=["京","沪","津","渝","冀","晋","蒙","辽","吉","黑","苏","浙","皖","闽","赣","鲁",\
              "豫","鄂","湘","粤","桂","琼","川","贵","云","藏","陕","甘","青","宁","新","军","使"]
number=[str(i) for i in range(0, 10)]   
alphabet=[chr(i) for i in range(65, 91)]   
char_set=char_enum + number + alphabet
char_set_len=len(char_set)
label_name_len=len(classeNames[0])
def text2vec(text):
    vector=np.zeros([label_name_len,char_set_len])
    for i, c in enumerate(text):
        idx=char_set.index(c)
        vector[i][idx]=1.0
    return vector
all_labels=[text2vec(i) for i in classeNames]

import os
import pandas as pd
from torchvision.io import read_image
from torch.utils.data import Dataset
import torch.utils.data as data
from PIL import Image

class MyDataset(data.Dataset):
    def __init__(self, all_labels, data_paths_str, transform):
        self.img_labels=all_labels     
        self.img_dir=data_paths_str  
        self.transform=transform       
    def __len__(self):
        return len(self.img_labels)
    def __getitem__(self, index):
        image=Image.open(self.img_dir[index]).convert('RGB')
        label=self.img_labels[index]  
        if self.transform:
            image=self.transform(image)
        return image, label  

total_datadir = './03_traffic_sign/'
train_transforms = transforms.Compose([
    transforms.Resize([224, 224]),  
    transforms.ToTensor(),          
    transforms.Normalize(           
        mean=[0.485, 0.456, 0.406], 
        std =[0.229, 0.224, 0.225])  
])
total_data = MyDataset(all_labels, data_paths_str, train_transforms)
total_data

train_size=int(0.8*len(total_data))
test_size=len(total_data)-train_size
train_dataset,test_dataset=torch.utils.data.random_split(total_data, [train_size, test_size])
train_size,test_size

train_loader = torch.utils.data.DataLoader(train_dataset,batch_size=16,shuffle=True)
test_loader = torch.utils.data.DataLoader(test_dataset,batch_size=16,shuffle=True)
print("The number of images in a training set is:",len(train_loader)*16)
print("The number of images in a test set is:",len(test_loader)*16)
print("The number of batches per epoch is:",len(train_loader))

for X, y in test_loader:
    print("Shape of X [N, C, H, W]: ", X.shape)
    print("Shape of y: ", y.shape, y.dtype)
    break

​​​​​​​​​​​

4.创建模型

python 复制代码
class Network_bn(nn.Module):
    def __init__(self):
        super(Network_bn, self).__init__()
        """
        nn.Conv2d()函数:
        第一个参数(in_channels)是输入的channel数量
        第二个参数(out_channels)是输出的channel数量
        第三个参数(kernel_size)是卷积核大小
        第四个参数(stride)是步长,默认为1
        第五个参数(padding)是填充大小,默认为0
        """
        self.conv1 = nn.Conv2d(in_channels=3, out_channels=12, kernel_size=5, stride=1, padding=0)
        self.bn1 = nn.BatchNorm2d(12)
        self.conv2 = nn.Conv2d(in_channels=12, out_channels=12, kernel_size=5, stride=1, padding=0)
        self.bn2 = nn.BatchNorm2d(12)
        self.pool = nn.MaxPool2d(2,2)
        self.conv4 = nn.Conv2d(in_channels=12, out_channels=24, kernel_size=5, stride=1, padding=0)
        self.bn4 = nn.BatchNorm2d(24)
        self.conv5 = nn.Conv2d(in_channels=24, out_channels=24, kernel_size=5, stride=1, padding=0)
        self.bn5 = nn.BatchNorm2d(24)
        self.fc1 = nn.Linear(24*50*50, label_name_len*char_set_len)
        self.reshape = Reshape([label_name_len,char_set_len])

    def forward(self, x):
        x = F.relu(self.bn1(self.conv1(x)))      
        x = F.relu(self.bn2(self.conv2(x)))     
        x = self.pool(x)                        
        x = F.relu(self.bn4(self.conv4(x)))     
        x = F.relu(self.bn5(self.conv5(x)))  
        x = self.pool(x)                        
        x = x.view(-1, 24*50*50)
        x = self.fc1(x)
        
        # 最终reshape
        x = self.reshape(x)

        return x
    
# 定义Reshape层
class Reshape(nn.Module):
    def __init__(self, shape):
        super(Reshape, self).__init__()
        self.shape = shape

    def forward(self, x):
        return x.view(x.size(0), *self.shape)

device = "cuda" if torch.cuda.is_available() else "cpu"
print("Using {} device".format(device))

model = Network_bn().to(device)
model

import torchsummary
torchsummary.summary(model,(3, 224, 224))

​​​​​​

5.编译及训练模型

python 复制代码
optimizer  = torch.optim.Adam(model.parameters(),lr=1e-4,weight_decay=0.0001)
loss_model = nn.CrossEntropyLoss()

from torch.autograd import Variable

import torch

def test(model, test_loader, loss_model):
    size = len(test_loader.dataset)
    num_batches = len(test_loader)
    
    model.eval()
    test_loss, correct = 0, 0
    with torch.no_grad():
        for X, y in test_loader:
            X, y = X.to(device), y.to(device)
            pred = model(X)
 
            test_loss += loss_model(pred, y).item()
            
            # 获取预测和真实标签的最大索引
            _, predicted_labels = torch.max(pred, dim=2)
            _, true_labels = torch.max(y, dim=2)
            
            # 计算准确率
            correct += (predicted_labels == true_labels).all(dim=1).sum().item()
 
    test_loss /= num_batches
    accuracy = correct / size
 
    print(f"Avg loss: {test_loss:>8f}, Accuracy: {accuracy:.2f} \n")
    return correct, test_loss

def train(model,train_loader,loss_model,optimizer):
    model=model.to(device)
    model.train()
    
    for i, (images, labels) in enumerate(train_loader, 0): 

        images = Variable(images.to(device))
        labels = Variable(labels.to(device))

        optimizer.zero_grad()
        outputs = model(images)

        loss = loss_model(outputs, labels)
        loss.backward()
        optimizer.step()

        if i % 1000 == 0:    
            print('[%5d] loss: %.3f' % (i, loss))

test_acc_list  = []
test_loss_list = []
epochs = 10

for t in range(epochs):
    print(f"Epoch {t+1}\n-------------------------------")
    train(model,train_loader,loss_model,optimizer)
    test_acc,test_loss = test(model, test_loader, loss_model)
    test_acc_list.append(test_acc)
    test_loss_list.append(test_loss)
print("Done!")

​​​​​​​​​​​​​​​​

6.结果可视化

python 复制代码
import numpy as np
import matplotlib.pyplot as plt
 
epochs = len(test_loss_list) 
x = np.arange(1, epochs + 1)  
 
plt.figure(figsize=(10, 5)) 
plt.plot(x, test_loss_list, label="Loss", alpha=0.8) 
plt.plot(x, test_acc_list, label="Accuracy", alpha=0.8) 
 
plt.xlabel("Epoch")  
plt.ylabel("Metric")  
plt.title("Training Loss and Accuracy")  
plt.legend()  
plt.grid(True)  
plt.show()  

​​​​​

​​总结:

这些代码展示了如何使用PyTorch构建并训练一个车牌识别模型。首先,通过检查GPU可用性来确定计算设备,确保模型训练可以在GPU上加速进行。接着,定义了一个数据集类MyDataset用于加载和预处理图像数据,并将数据划分为训练集和测试集以便评估模型性能。然后,创建了一个名为Network_bn的卷积神经网络模型,该模型包含了多个卷积层、批归一化层以及全连接层,以提取图像特征并进行分类。在模型编译与训练阶段,采用了Adam优化器和交叉熵损失函数进行参数更新,并通过循环执行多次epoch对模型进行了训练。最后,通过可视化训练过程中的损失值和准确率变化情况,可以直观地了解模型的学习进展。整个流程涵盖了从数据准备到模型训练及结果分析的完整机器学习项目实施步骤。

其中

训练函数 (train)

训练函数 train 用于在给定的训练数据集上更新模型参数。它首先将模型设置为训练模式并移动到合适的计算设备(如GPU)。然后,通过遍历训练数据加载器中的批次数据,执行前向传播计算预测结果,并使用交叉熵损失函数计算损失。接着,通过反向传播计算梯度并使用优化器更新模型参数。每处理1000个批次,函数会打印当前的损失值以监控训练进度。

测试函数 (test)

测试函数 test 用于评估模型在未见过的数据上的性能。该函数首先将模型设置为评估模式,并禁用梯度计算以减少内存占用和加速计算。接着,遍历测试数据加载器中的批次数据,执行前向传播获取预测结果并计算损失。通过比较预测标签与真实标签的最大索引来计算分类准确率,并最终输出平均损失和整体准确率,以便直观了解模型的泛化能力。

相关推荐
埃菲尔铁塔_CV算法6 分钟前
双线性插值算法:原理、实现、优化及在图像处理和多领域中的广泛应用与发展趋势(二)
c++·人工智能·算法·机器学习·计算机视觉
程序猿阿伟17 分钟前
《AI赋能鸿蒙Next,打造极致沉浸感游戏》
人工智能·游戏·harmonyos
遇健李的幸运33 分钟前
深入浅出:Agent如何调用工具——从OpenAI Function Call到CrewAI框架
人工智能
天天讯通35 分钟前
AI语音机器人大模型是什么?
人工智能·机器人
说私域42 分钟前
微商关系维系与服务创新:链动2+1模式、AI智能名片与S2B2C商城小程序的应用研究
人工智能·小程序
人机与认知实验室1 小时前
人-AI协同如何重塑未来战争?
人工智能
学技术的大胜嗷1 小时前
小目标检测难点分析和解决策略
人工智能·目标检测·计算机视觉
李加号pluuuus1 小时前
【论文阅读+复现】High-fidelity Person-centric Subject-to-Image Synthesis
论文阅读·人工智能·计算机视觉
XianxinMao2 小时前
o3模型重大突破:引领推理语言模型新纪元,展望2025年AI发展新格局
人工智能·语言模型
martian6652 小时前
深入详解人工智能自然语言处理(NLP)之文本处理:分词、词性标注、命名实体识别
人工智能·自然语言处理