本文为365天深度学习训练营 中的学习记录博客
参考文章:Pytorch实战 | 第P7周:咖啡豆识别(训练营内部成员可读)
原作者:K同学啊|接辅导、项目定制
本期博客我们将探索完成使用Pytorch框架搭建VGG16网络模型进行咖啡豆的识别任务。
import torch
import torch.nn as nn
import torchvision.transforms as transforms
import torchvision
from torchvision import transforms, datasets
import os,PIL,pathlib,warnings
warnings.filterwarnings("ignore") #忽略警告信息
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
device
device(type='cuda')
import os,PIL,random,pathlib
data_dir = 'E:\深度学习\data\Day16'
data_dir = pathlib.Path(data_dir)
data_paths = list(data_dir.glob('*'))
classeNames = [str(path).split("\\")[4] for path in data_paths]
classeNames
['Dark', 'Green', 'Light', 'Medium']
使用transforms.Compose对数据进行预处理的方法,包括将输入图片resize成统一尺寸、归一化处理等。其中,train_transforms和test_transform是训练集和测试集的预处理方法,total_data是处理后的数据集。
train_transforms = transforms.Compose([
transforms.Resize([224, 224]), # 将输入图片resize成统一尺寸
# transforms.RandomHorizontalFlip(), # 随机水平翻转
transforms.ToTensor(), # 将PIL Image或numpy.ndarray转换为tensor,并归一化到[0,1]之间
transforms.Normalize( # 标准化处理-->转换为标准正太分布(高斯分布),使模型更容易收敛
mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225]) # 其中 mean=[0.485,0.456,0.406]与std=[0.229,0.224,0.225] 从数据集中随机抽样计算得到的。
])
test_transform = transforms.Compose([
transforms.Resize([224, 224]), # 将输入图片resize成统一尺寸
transforms.ToTensor(), # 将PIL Image或numpy.ndarray转换为tensor,并归一化到[0,1]之间
transforms.Normalize( # 标准化处理-->转换为标准正太分布(高斯分布),使模型更容易收敛
mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225]) # 其中 mean=[0.485,0.456,0.406]与std=[0.229,0.224,0.225] 从数据集中随机抽样计算得到的。
])
total_data = datasets.ImageFolder(data_dir,transform=train_transforms)
total_data
Dataset ImageFolder
Number of datapoints: 1200
Root location: E:\深度学习\data\Day16
StandardTransform
Transform: Compose(
Resize(size=[224, 224], interpolation=bilinear, max_size=None, antialias=None)
ToTensor()
Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
)
total_data.class_to_idx # 查看类别对应的索引
{'Dark': 0, 'Green': 1, 'Light': 2, 'Medium': 3}
将数据集分为训练集和测试集,首先通过数据总量的80%来计算训练集大小,然后用总量减去训练集大小得到测试集大小,最后使用PyTorch的random_split函数将数据集随机分为训练集和测试集。
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_dataset, test_dataset
(<torch.utils.data.dataset.Subset at 0x2168b369670>,
<torch.utils.data.dataset.Subset at 0x2168b369df0>)
定义两个数据加载器,分别是train_dl和test_dl。每个加载器都有一个batch_size参数,用于指定每个批次的大小。此外,还有shuffle和num_workers参数,用于打乱数据集并指定使用的线程数。
batch_size = 32
train_dl = torch.utils.data.DataLoader(train_dataset, batch_size=batch_size, shuffle=True,num_workers=1)
test_dl = torch.utils.data.DataLoader(test_dataset, batch_size=batch_size, shuffle=True,num_workers=1)
使用test_dl数据集进行迭代,输出X和y的形状和数据类型。其中X的形状为[N, C, H, W],y的形状和数据类型则分别输出。
for x, y in test_dl:
print(x.shape, y.shape)
break
torch.Size([32, 3, 224, 224]) torch.Size([32])
import torch.nn.functional as F
class vgg16(nn.Module):
def __init__(self):
super(vgg16, self).__init__()
# 卷积块1
self.block1 = nn.Sequential(
nn.Conv2d(3, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1)),
nn.ReLU(),
nn.Conv2d(64, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1)),
nn.ReLU(),
nn.MaxPool2d(kernel_size=(2, 2), stride=(2, 2))
)
# 卷积块2
self.block2 = nn.Sequential(
nn.Conv2d(64, 128, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1)),
nn.ReLU(),
nn.Conv2d(128, 128, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1)),
nn.ReLU(),
nn.MaxPool2d(kernel_size=(2, 2), stride=(2, 2))
)
# 卷积块3
self.block3 = nn.Sequential(
nn.Conv2d(128, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1)),
nn.ReLU(),
nn.Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1)),
nn.ReLU(),
nn.Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1)),
nn.ReLU(),
nn.MaxPool2d(kernel_size=(2, 2), stride=(2, 2))
)
# 卷积块4
self.block4 = nn.Sequential(
nn.Conv2d(256, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1)),
nn.ReLU(),
nn.Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1)),
nn.ReLU(),
nn.Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1)),
nn.ReLU(),
nn.MaxPool2d(kernel_size=(2, 2), stride=(2, 2))
)
# 卷积块5
self.block5 = nn.Sequential(
nn.Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1)),
nn.ReLU(),
nn.Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1)),
nn.ReLU(),
nn.Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1)),
nn.ReLU(),
nn.MaxPool2d(kernel_size=(2, 2), stride=(2, 2))
)
# 全连接网络层,用于分类
self.classifier = nn.Sequential(
nn.Linear(in_features=512*7*7, out_features=4096),
nn.ReLU(),
nn.Linear(in_features=4096, out_features=4096),
nn.ReLU(),
nn.Linear(in_features=4096, out_features=4)
)
def forward(self, x):
x = self.block1(x)
x = self.block2(x)
x = self.block3(x)
x = self.block4(x)
x = self.block5(x)
x = torch.flatten(x, start_dim=1)
x = self.classifier(x)
return x
device = "cuda" if torch.cuda.is_available() else "cpu"
print("Using {} device".format(device))
model = vgg16().to(device)
model
Using cuda device
Output exceeds the size limit. Open the full output data in a text editor
vgg16(
(block1): Sequential(
(0): Conv2d(3, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
(1): ReLU()
(2): Conv2d(64, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
(3): ReLU()
(4): MaxPool2d(kernel_size=(2, 2), stride=(2, 2), padding=0, dilation=1, ceil_mode=False)
)
(block2): Sequential(
(0): Conv2d(64, 128, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
(1): ReLU()
(2): Conv2d(128, 128, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
(3): ReLU()
(4): MaxPool2d(kernel_size=(2, 2), stride=(2, 2), padding=0, dilation=1, ceil_mode=False)
)
(block3): Sequential(
(0): Conv2d(128, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
(1): ReLU()
(2): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
(3): ReLU()
(4): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
(5): ReLU()
(6): MaxPool2d(kernel_size=(2, 2), stride=(2, 2), padding=0, dilation=1, ceil_mode=False)
)
(block4): Sequential(
...
(2): Linear(in_features=4096, out_features=4096, bias=True)
(3): ReLU()
(4): Linear(in_features=4096, out_features=4, bias=True)
)
)
这是一个使用PyTorch实现的VGG16模型,包括5个卷积块和1个全连接网络层,用于分类。模型输入为3通道的图像,输出为4个类别的概率分布。模型使用ReLU作为激活函数,最大池化作为下采样方式。模型已移植到GPU上。
# 查看模型参数
for name, param in model.named_parameters():
print(name, '\t', param.shape)
block1.0.weight torch.Size([64, 3, 3, 3])
block1.0.bias torch.Size([64])
block1.2.weight torch.Size([64, 64, 3, 3])
block1.2.bias torch.Size([64])
block2.0.weight torch.Size([128, 64, 3, 3])
block2.0.bias torch.Size([128])
block2.2.weight torch.Size([128, 128, 3, 3])
block2.2.bias torch.Size([128])
block3.0.weight torch.Size([256, 128, 3, 3])
block3.0.bias torch.Size([256])
block3.2.weight torch.Size([256, 256, 3, 3])
block3.2.bias torch.Size([256])
block3.4.weight torch.Size([256, 256, 3, 3])
block3.4.bias torch.Size([256])
block4.0.weight torch.Size([512, 256, 3, 3])
block4.0.bias torch.Size([512])
block4.2.weight torch.Size([512, 512, 3, 3])
block4.2.bias torch.Size([512])
block4.4.weight torch.Size([512, 512, 3, 3])
block4.4.bias torch.Size([512])
block5.0.weight torch.Size([512, 512, 3, 3])
block5.0.bias torch.Size([512])
block5.2.weight torch.Size([512, 512, 3, 3])
block5.2.bias torch.Size([512])
block5.4.weight torch.Size([512, 512, 3, 3])
...
classifier.2.weight torch.Size([4096, 4096])
classifier.2.bias torch.Size([4096])
classifier.4.weight torch.Size([4, 4096])
classifier.4.bias torch.Size([4])
可以使用 PyTorch 提供的 torchvision.models 模块中的 vgg16 函数来调用官方的 VGG16 网络框架。
import torch
import torch.nn as nn
import torchvision.models as models
# 加载预训练的 VGG16 模型
model = models.vgg16(pretrained=True)
# 将模型移动到 GPU 上
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model.to(device)
# 定义损失函数和优化器
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model.parameters(), lr=0.001)
# 训练模型
for epoch in range(num_epochs):
for images, labels in train_loader:
images = images.to(device)
labels = labels.to(device)
optimizer.zero_grad()
outputs = model(images)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
# 测试模型
with torch.no_grad():
correct = 0
total = 0
for images, labels in test_loader:
images = images.to(device)
labels = labels.to(device)
outputs = model(images)
_, predicted = torch.max(outputs.data, 1)
total += labels.size(0)
correct += (predicted == labels).sum().item()
print('Accuracy: {} %'.format(100 * correct / total))
我们首先加载了预训练的 VGG16 模型,然后将模型移动到 GPU 上,并定义了损失函数和优化器。在训练过程中,我们遍历训练集,计算损失并反向传播更新参数。在测试过程中,我们遍历测试集,计算模型的准确率。
# 训练循环
def train(dataloader, model, loss_fn, optimizer):
size = len(dataloader.dataset) # 训练集的大小
num_batches = len(dataloader) # 批次数目, (size/batch_size,向上取整)
train_loss, train_acc = 0, 0 # 初始化训练损失和正确率
for X, y in dataloader: # 获取图片及其标签
X, y = X.to(device), y.to(device)
# 计算预测误差
pred = model(X) # 网络输出
loss = loss_fn(pred, y) # 计算网络输出和真实值之间的差距,targets为真实值,计算二者差值即为损失
# 反向传播
optimizer.zero_grad() # grad属性归零
loss.backward() # 反向传播
optimizer.step() # 每一步自动更新
# 记录acc与loss
train_acc += (pred.argmax(1) == y).type(torch.float).sum().item()
train_loss += loss.item()
train_acc /= size
train_loss /= num_batches
return train_acc, train_loss
该函数为训练循环,输入数据集、模型、损失函数和优化器,返回训练损失和正确率。函数中进行了模型预测、损失计算、反向传播和参数更新等操作。最终计算并返回训练集的正确率和损失。
def test (dataloader, model, loss_fn):
size = len(dataloader.dataset) # 测试集的大小
num_batches = len(dataloader) # 批次数目, (size/batch_size,向上取整)
test_loss, test_acc = 0, 0
# 当不进行训练时,停止梯度更新,节省计算内存消耗
with torch.no_grad():
for imgs, target in dataloader:
imgs, target = imgs.to(device), target.to(device)
# 计算loss
target_pred = model(imgs)
loss = loss_fn(target_pred, target)
test_loss += loss.item()
test_acc += (target_pred.argmax(1) == target).type(torch.float).sum().item()
test_acc /= size
test_loss /= num_batches
return test_acc, test_loss
该函数用于测试模型在给定数据集上的准确率和损失。函数会遍历数据集并计算每个批次的损失和准确率,最后返回整个数据集的平均准确率和平均损失。
import copy
optimizer = torch.optim.Adam(model.parameters(), lr= 1e-4)
loss_fn = nn.CrossEntropyLoss() # 创建损失函数
epochs = 40
train_loss = []
train_acc = []
test_loss = []
test_acc = []
best_acc = 0 # 设置一个最佳准确率,作为最佳模型的判别指标
for epoch in range(epochs):
model.train()
epoch_train_acc, epoch_train_loss = train(train_dl, model, loss_fn, optimizer)
model.eval()
epoch_test_acc, epoch_test_loss = test(test_dl, model, loss_fn)
# 保存最佳模型到 best_model
if epoch_test_acc > best_acc:
best_acc = epoch_test_acc
best_model = copy.deepcopy(model)
train_acc.append(epoch_train_acc)
train_loss.append(epoch_train_loss)
test_acc.append(epoch_test_acc)
test_loss.append(epoch_test_loss)
# 获取当前的学习率
lr = optimizer.state_dict()['param_groups'][0]['lr']
template = ('Epoch:{:2d}, Train_acc:{:.1f}%, Train_loss:{:.3f}, Test_acc:{:.1f}%, Test_loss:{:.3f}, Lr:{:.2E}')
print(template.format(epoch+1, epoch_train_acc*100, epoch_train_loss,
epoch_test_acc*100, epoch_test_loss, lr))
# 保存最佳模型到文件中
PATH = './best_model.pth' # 保存的参数文件名
torch.save(model.state_dict(), PATH)
print('Done')
Epoch: 1, Train_acc:25.8%, Train_loss:1.378, Test_acc:21.2%, Test_loss:1.311, Lr:1.00E-04
Epoch: 2, Train_acc:52.6%, Train_loss:1.062, Test_acc:58.3%, Test_loss:0.798, Lr:1.00E-04
Epoch: 3, Train_acc:59.4%, Train_loss:0.829, Test_acc:71.2%, Test_loss:0.765, Lr:1.00E-04
Epoch: 4, Train_acc:65.8%, Train_loss:0.695, Test_acc:71.7%, Test_loss:0.652, Lr:1.00E-04
Epoch: 5, Train_acc:74.7%, Train_loss:0.576, Test_acc:66.7%, Test_loss:0.577, Lr:1.00E-04
Epoch: 6, Train_acc:74.7%, Train_loss:0.549, Test_acc:77.5%, Test_loss:0.539, Lr:1.00E-04
Epoch: 7, Train_acc:81.4%, Train_loss:0.425, Test_acc:82.5%, Test_loss:0.370, Lr:1.00E-04
Epoch: 8, Train_acc:82.3%, Train_loss:0.381, Test_acc:85.4%, Test_loss:0.315, Lr:1.00E-04
Epoch: 9, Train_acc:84.8%, Train_loss:0.336, Test_acc:85.8%, Test_loss:0.320, Lr:1.00E-04
Epoch:10, Train_acc:87.8%, Train_loss:0.303, Test_acc:91.7%, Test_loss:0.205, Lr:1.00E-04
Epoch:11, Train_acc:90.4%, Train_loss:0.247, Test_acc:89.6%, Test_loss:0.349, Lr:1.00E-04
Epoch:12, Train_acc:94.2%, Train_loss:0.163, Test_acc:97.1%, Test_loss:0.062, Lr:1.00E-04
Epoch:13, Train_acc:96.1%, Train_loss:0.139, Test_acc:86.2%, Test_loss:0.367, Lr:1.00E-04
Epoch:14, Train_acc:95.0%, Train_loss:0.154, Test_acc:93.3%, Test_loss:0.203, Lr:1.00E-04
Epoch:15, Train_acc:97.5%, Train_loss:0.066, Test_acc:98.3%, Test_loss:0.027, Lr:1.00E-04
Epoch:16, Train_acc:96.9%, Train_loss:0.072, Test_acc:97.9%, Test_loss:0.079, Lr:1.00E-04
Epoch:17, Train_acc:98.0%, Train_loss:0.055, Test_acc:98.3%, Test_loss:0.032, Lr:1.00E-04
Epoch:18, Train_acc:98.5%, Train_loss:0.031, Test_acc:100.0%, Test_loss:0.008, Lr:1.00E-04
Epoch:19, Train_acc:99.0%, Train_loss:0.025, Test_acc:99.6%, Test_loss:0.021, Lr:1.00E-04
Epoch:20, Train_acc:98.0%, Train_loss:0.065, Test_acc:98.3%, Test_loss:0.045, Lr:1.00E-04
Epoch:21, Train_acc:96.6%, Train_loss:0.099, Test_acc:96.2%, Test_loss:0.112, Lr:1.00E-04
Epoch:22, Train_acc:99.5%, Train_loss:0.025, Test_acc:99.2%, Test_loss:0.015, Lr:1.00E-04
Epoch:23, Train_acc:99.8%, Train_loss:0.006, Test_acc:99.6%, Test_loss:0.012, Lr:1.00E-04
Epoch:24, Train_acc:95.2%, Train_loss:0.156, Test_acc:96.7%, Test_loss:0.114, Lr:1.00E-04
Epoch:25, Train_acc:98.9%, Train_loss:0.039, Test_acc:98.8%, Test_loss:0.033, Lr:1.00E-04
...
Epoch:38, Train_acc:99.8%, Train_loss:0.005, Test_acc:99.6%, Test_loss:0.016, Lr:1.00E-04
Epoch:39, Train_acc:100.0%, Train_loss:0.000, Test_acc:99.6%, Test_loss:0.007, Lr:1.00E-04
Epoch:40, Train_acc:100.0%, Train_loss:0.000, Test_acc:99.6%, Test_loss:0.006, Lr:1.00E-04
Done
import matplotlib.pyplot as plt
#隐藏警告
import warnings
warnings.filterwarnings("ignore") #忽略警告信息
plt.rcParams['font.sans-serif'] = ['SimHei'] # 用来正常显示中文标签
plt.rcParams['axes.unicode_minus'] = False # 用来正常显示负号
plt.rcParams['figure.dpi'] = 100 #分辨率
epochs_range = range(epochs)
plt.figure(figsize=(12, 3))
plt.subplot(1, 2, 1)
plt.plot(epochs_range, train_acc, label='Training Accuracy')
plt.plot(epochs_range, test_acc, label='Test Accuracy')
plt.legend(loc='lower right')
plt.title('Training and Validation Accuracy')
plt.subplot(1, 2, 2)
plt.plot(epochs_range, train_loss, label='Training Loss')
plt.plot(epochs_range, test_loss, label='Test Loss')
plt.legend(loc='upper right')
plt.title('Training and Validation Loss')
plt.show()
from PIL import Image
classes = list(total_data.class_to_idx)
def predict_one_image(image_path, model, transform, classes):
test_img = Image.open(image_path).convert('RGB')
plt.imshow(test_img) # 展示预测的图片
test_img = transform(test_img)
img = test_img.to(device).unsqueeze(0)
model.eval()
output = model(img)
_,pred = torch.max(output,1)
pred_class = classes[pred]
print(f'预测结果是:{pred_class}')
# 预测训练集中的某张照片
predict_one_image(image_path='E:\深度学习\data\Day16\Medium\medium (1).png', model=model, transform=train_transforms, classes=classes)
best_model.eval()
epoch_test_acc, epoch_test_loss = test(test_dl, best_model, loss_fn)
epoch_test_acc, epoch_test_loss
(1.0, 0.009578780613082927)
我这里训练之后准确率达到了100%。
import torch
import torch.nn as nn
import torchvision.models as models
num_epochs = 20
# 加载预训练的 MobileNetV2 模型
model = models.mobilenet_v2(pretrained=True)
# 将最后一层替换为新的全连接层
model.classifier = nn.Sequential(
nn.Dropout(0.2),
nn.Linear(1280, 4),
)
# 将模型移动到 GPU 上
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model.to(device)
# 定义损失函数和优化器
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model.parameters(), lr=0.001)
# 训练模型
for epoch in range(num_epochs):
for images, labels in train_dl:
images = images.to(device)
labels = labels.to(device)
optimizer.zero_grad()
outputs = model(images)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
# 测试模型
with torch.no_grad():
correct = 0
total = 0
for images, labels in test_dl:
images = images.to(device)
labels = labels.to(device)
outputs = model(images)
_, predicted = torch.max(outputs.data, 1)
total += labels.size(0)
correct += (predicted == labels).sum().item()
print('Accuracy: {} %'.format(100 * correct / total))
MobileNetV2 模型和 VGG16 模型在网络结构上有很大的不同。MobileNetV2 模型采用了深度可分离卷积的设计,可以在保持较高准确率的同时,大幅度减小模型的参数量和计算量,因此更加轻量级。而 VGG16 模型则是传统的卷积神经网络,参数量和计算量相对较大。