- 🍨 本文为 🔗365天深度学习训练营中的学习记录博客
- 🍖 原作者: K同学啊
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
用于评估模型在未见过的数据上的性能。该函数首先将模型设置为评估模式,并禁用梯度计算以减少内存占用和加速计算。接着,遍历测试数据加载器中的批次数据,执行前向传播获取预测结果并计算损失。通过比较预测标签与真实标签的最大索引来计算分类准确率,并最终输出平均损失和整体准确率,以便直观了解模型的泛化能力。