深度学习 / 55.7

迁移学习:车型分类实验

张量、模型与训练过程。 迁移学习:车型分类实验。

阅读说明: 保留原笔记的编号与章节顺序;代码只供查看,没有在本站运行。历史输出不代表当前版本的复现结果。截图/外链图以独立整理的公式、表格、示意或文字替换;纠错与必要补充均作说明。

1.introduction

This project is about car classification for stanford car dataset. The Cars dataset contains 16,185 images of 196 classes of cars. The data is split into 8,144 training images and 8,041 testing images, where each class has been split roughly in a 50-50 split. Classes are typically at the level of Make, Model, Year, e.g. 2012 Tesla Model S or 2012 BMW M3 coupe.

It is difficult to directly train deep learning model on this dataset because the limited number of images. Thus we decide to use transfer learning, a common approch used in deep learning to utilize the pretrained model on imagenet and fine-tune on our own dataset, i.e. car dataset.

This project can show you how to train and fine-tune a deep learning model using PyTorch.

分类任务的独立关系图: 车型图片 → 特征提取器 → 196维分类头 → 类别分数。使用文字流程替代原车辆照片拼图,不分发原数据集照片;数据集来源仍保留链接。

1.1 Transfer Learning

Transfer learning is one of the most widely used technologies in deep learning and computer vision. If you are not familar with the concept of transfer learning, please refer to our course materials.

迁移学习: 预训练backbone提供初始特征参数;替换分类头匹配新类别;可先冻结backbone训练新头,再用较小学习率微调。是否冻结与数据量、分布差异有关。

2.Making a car classifier using Pytorch

In this notebook I’m making a car classifier using the Stanford car dataset, which contains 196 classes. I’ll be using a pre-trained model with transfer learning to train the model. All layers will be fine tuned and the last fully connected layer will be replaced entirely.

Dataset (196 classes):

Train folder: 8144 images, avg: 41.5 images per class.

Test folder: 8041 images, avg: 41.0 images per class.

2.1 mount google drive to colab

PYTHON · 仅供阅读
# from google.colab import drive
# drive.mount('/content/drive')

2.2 Copy file from google drive to colab

PYTHON · 仅供阅读
# # copy dataset from google drive to colab
# !cp ./drive/My\ Drive/stanford_car_dataset.zip ./

2.3 Extract dataset files

PYTHON · 仅供阅读
# %%time
# # unzip dataset in colab
# !mkdir ./stanford_car_dataset
# !unzip -q stanford_car_dataset.zip -d ./stanford_car_dataset

3.Build model

3.1 Load packages

The pytorch have been pre-installled on colab, and we do not need re-install these packages.

PYTHON · 仅供阅读
import matplotlib.pyplot as plt
import numpy as np

import torch
import torch.nn as nn
import torch.optim as optim
import torchvision
import torchvision.models as models
import torchvision.transforms as transforms

import time
import os
import tqdm
import PIL.Image as Image
from IPython.display import display

device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
print(device)
if device.type == 'cuda':
    print(torch.cuda.get_device_name(device))
原笔记输出 · 本次未执行
cuda:0
NVIDIA GeForce RTX 2060 SUPER

版本说明: 上方代码含局部修正;下方/相邻输出来自原笔记运行记录(隐私字段已占位),不是本次重新运行修正版得到的结果。

3.2 Load the data and transform

First, lets create some transforms for our data and load the train/test data+labels from the folders.

Here we are using 224x224 images (you can also change the resolution) with random horizontal flip, random rotation and normalization

PYTHON · 仅供阅读
dataset_dir = "stanford_car_dataset/car_data/car_data/"

# data transformation, you can try different transformation/ data augmentation here
# note: no data augmentation for test data

# width, height = 224, 224 # models except to inception_V3
width, height = 299, 299  # for inception_v3
train_tfms = transforms.Compose([transforms.Resize((width, height)),
                                 # transforms.RandomHorizontalFlip(),
                                 # transforms.RandomRotation(15),
                                 transforms.ToTensor(),
                                 transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])])
test_tfms = transforms.Compose([transforms.Resize((width, height)),
                                transforms.ToTensor(),
                                transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])])

# create datasets
dataset = torchvision.datasets.ImageFolder(root=dataset_dir + "train", transform=train_tfms)
trainloader = torch.utils.data.DataLoader(dataset, batch_size=32, shuffle=True, num_workers=2)

dataset2 = torchvision.datasets.ImageFolder(root=dataset_dir+"test", transform = test_tfms)
testloader = torch.utils.data.DataLoader(dataset2, batch_size=32, shuffle=False, num_workers=2)

3.3 Model training function

Here we train our model, after each epoch, we test the model on the test data to see how it’s going

整理注: 每轮调度器都读取的数据集应称验证集;若用testloader调参,就不能再把它当作无偏的最终测试集,正式评估需要另留未参与选择的测试数据。

PYTHON · 仅供阅读
def train_model(model, criterion, optimizer, scheduler, n_epochs=5, inception_v3=False):
    
    losses = []
    accuracies = []
    test_accuracies = []

    # set the model to train mode initially
    model.train()
    for epoch in tqdm.tqdm(range(n_epochs)):
        since = time.time()
        running_loss = 0.0
        running_correct = 0.0
        for i, data in enumerate(trainloader, 0):

            # get the inputs and assign them to cuda
            inputs, labels = data
            #inputs = inputs.to(device).half() # uncomment for half precision model
            inputs = inputs.to(device)
            labels = labels.to(device)
            optimizer.zero_grad()
            
            # forward + backward + optimize
            outputs = model(inputs)
            # print(outputs)
            if not inception_v3:
                _, predicted = torch.max(outputs.data, 1)
            else:
                _, predicted = torch.max(outputs, 1)
            loss = criterion(outputs, labels)
            loss.backward()
            optimizer.step()
            
            # calculate the loss/acc later
            running_loss += loss.item()
            running_correct += (labels==predicted).sum().item()

        epoch_duration = time.time() - since
        epoch_loss = running_loss / len(trainloader)
        epoch_acc = 100.0 * running_correct / len(trainloader.dataset)
        print("Epoch %s, duration: %d s, loss: %.4f, acc: %.4f" % (epoch+1, epoch_duration, epoch_loss, epoch_acc))
        
        losses.append(epoch_loss)
        accuracies.append(epoch_acc)
        
        # switch the model to eval mode to evaluate on test data
        model.eval()
        test_acc = eval_model(model)
        test_accuracies.append(test_acc)
        
        # re-set the model to train mode after validating
        model.train()
        scheduler.step(test_acc)
        since = time.time()
    print('Finished Training')
    return model, losses, accuracies, test_accuracies

3.4 Evaluate on training data

This function is called out after each epoch of training on the training data. We then measure the accuracy of the model.

PYTHON · 仅供阅读
def eval_model(model):
    correct = 0.0
    total = 0.0
    with torch.no_grad():
        for i, data in enumerate(testloader, 0):
            images, labels = data
            #images = images.to(device).half() # uncomment for half precision model
            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()

    test_acc = 100.0 * correct / total
    print('Accuracy of the network on the test images: %d %%' % (
        test_acc))
    return test_acc

4.Experiment

4.1 define parameters

PYTHON · 仅供阅读
NUM_CAR_CLASSES = 196
model_ft = models.inception_v3(pretrained=True)
model_ft.aux_logits = False

# Freezing model parameters and defining the fully connected network to be attached to the model, 
# loss function and the optimizer.
# We there after put the model on the GPUs
# for param in model_ft.parameters():
#     param.require_grad = False

# replace the last fc layer with an untrained one (requires grad by default)

# for inception_V3
num_ftrs = model_ft.fc.in_features
model_ft.fc = nn.Linear(num_ftrs, NUM_CAR_CLASSES)

model_ft = model_ft.to(device)

# uncomment this block for half precision model
"""
model_ft = model_ft.half()


for layer in model_ft.modules():
    if isinstance(layer, nn.BatchNorm2d):
        layer.float()
"""

criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(model_ft.parameters(), lr=0.01, momentum=0.9)

"""
probably not the best metric to track, but we are tracking the training accuracy and measuring whether
it increases by atleast 0.9 per epoch and if it hasn't increased by 0.9 reduce the lr by 0.1x.
However in this model it did not benefit me.
"""
lrscheduler = optim.lr_scheduler.ReduceLROnPlateau(optimizer, mode='max', patience=3, threshold=0.9)
原笔记输出 · 已脱敏 · 本次未执行
Downloading: "https://download.pytorch.org/models/inception_v3_google-0cc3c7bd.pth" to C:\Users\[USER]/.cache\torch\hub\checkpoints\inception_v3_google-0cc3c7bd.pth
原笔记输出 · 本次未执行
  0%|          | 0.00/104M [00:00<?, ?B/s]

4.2 model training

PYTHON · 仅供阅读
# use inception_v3
model_ft, training_losses, training_accs, test_accs = train_model(model_ft, criterion, optimizer, lrscheduler, n_epochs=20, inception_v3=True)
原笔记输出 · 已脱敏 · 本次未执行
  0%|                                                                                           | 0/20 [00:00<?, ?it/s]C:\Users\[USER]\Anaconda3\envs\myenv\lib\site-packages\torch\nn\functional.py:718: UserWarning: Named tensors and all their associated APIs are an experimental feature and subject to change. Please do not use them for anything important until they are released as stable. (Triggered internally at  ..\c10/core/TensorImpl.h:1156.)
  return torch.max_pool2d(input, kernel_size, stride, padding, dilation, ceil_mode)
原笔记输出 · 本次未执行
Epoch 1, duration: 86 s, loss: 3.9857, acc: 14.0196
原笔记输出 · 本次未执行
  5%|████                                                                              | 1/20 [02:11<41:44, 131.84s/it]
原笔记输出 · 本次未执行
Accuracy of the network on the test images: 33 %
Epoch 2, duration: 84 s, loss: 1.7716, acc: 52.1201
原笔记输出 · 本次未执行
 10%|████████▏                                                                         | 2/20 [04:22<39:25, 131.39s/it]
原笔记输出 · 本次未执行
Accuracy of the network on the test images: 61 %
Epoch 3, duration: 82 s, loss: 0.8268, acc: 76.4951
原笔记输出 · 本次未执行
 15%|████████████▎                                                                     | 3/20 [06:30<36:44, 129.68s/it]
原笔记输出 · 本次未执行
Accuracy of the network on the test images: 68 %
Epoch 4, duration: 81 s, loss: 0.4413, acc: 87.2917
原笔记输出 · 本次未执行
 20%|████████████████▍                                                                 | 4/20 [08:36<34:11, 128.23s/it]
原笔记输出 · 本次未执行
Accuracy of the network on the test images: 76 %
Epoch 5, duration: 80 s, loss: 0.2428, acc: 93.0882
原笔记输出 · 本次未执行
 25%|████████████████████▌                                                             | 5/20 [10:42<31:48, 127.24s/it]
原笔记输出 · 本次未执行
Accuracy of the network on the test images: 78 %
Epoch 6, duration: 81 s, loss: 0.1523, acc: 95.8456
原笔记输出 · 本次未执行
 30%|████████████████████████▌                                                         | 6/20 [12:48<29:36, 126.87s/it]
原笔记输出 · 本次未执行
Accuracy of the network on the test images: 82 %
Epoch 7, duration: 80 s, loss: 0.0878, acc: 97.8799
原笔记输出 · 本次未执行
 35%|████████████████████████████▋                                                     | 7/20 [14:53<27:23, 126.39s/it]
原笔记输出 · 本次未执行
Accuracy of the network on the test images: 83 %
Epoch 8, duration: 81 s, loss: 0.0474, acc: 98.9706
原笔记输出 · 本次未执行
 40%|████████████████████████████████▊                                                 | 8/20 [16:59<25:16, 126.33s/it]
原笔记输出 · 本次未执行
Accuracy of the network on the test images: 87 %
Epoch 9, duration: 80 s, loss: 0.0282, acc: 99.4975
原笔记输出 · 本次未执行
 45%|████████████████████████████████████▉                                             | 9/20 [19:05<23:06, 126.07s/it]
原笔记输出 · 本次未执行
Accuracy of the network on the test images: 87 %
Epoch 10, duration: 81 s, loss: 0.0256, acc: 99.4608
原笔记输出 · 本次未执行
 50%|████████████████████████████████████████▌                                        | 10/20 [21:11<21:00, 126.07s/it]
原笔记输出 · 本次未执行
Accuracy of the network on the test images: 87 %
Epoch 11, duration: 80 s, loss: 0.0223, acc: 99.5221
原笔记输出 · 本次未执行
 55%|████████████████████████████████████████████▌                                    | 11/20 [23:17<18:53, 125.96s/it]
原笔记输出 · 本次未执行
Accuracy of the network on the test images: 88 %
Epoch 12, duration: 80 s, loss: 0.0196, acc: 99.5711
原笔记输出 · 本次未执行
 60%|████████████████████████████████████████████████▌                                | 12/20 [25:22<16:45, 125.73s/it]
原笔记输出 · 本次未执行
Accuracy of the network on the test images: 88 %
Epoch 13, duration: 79 s, loss: 0.0180, acc: 99.6078
原笔记输出 · 本次未执行
 65%|████████████████████████████████████████████████████▋                            | 13/20 [27:26<14:36, 125.23s/it]
原笔记输出 · 本次未执行
Accuracy of the network on the test images: 88 %
Epoch 14, duration: 78 s, loss: 0.0182, acc: 99.6201
原笔记输出 · 本次未执行
 70%|████████████████████████████████████████████████████████▋                        | 14/20 [29:29<12:28, 124.71s/it]
原笔记输出 · 本次未执行
Accuracy of the network on the test images: 88 %
Epoch 15, duration: 79 s, loss: 0.0182, acc: 99.6201
原笔记输出 · 本次未执行
 75%|████████████████████████████████████████████████████████████▊                    | 15/20 [31:33<10:21, 124.38s/it]
原笔记输出 · 本次未执行
Accuracy of the network on the test images: 88 %
Epoch 16, duration: 79 s, loss: 0.0182, acc: 99.5956
原笔记输出 · 本次未执行
 80%|████████████████████████████████████████████████████████████████▊                | 16/20 [33:37<08:16, 124.12s/it]
原笔记输出 · 本次未执行
Accuracy of the network on the test images: 88 %
Epoch 17, duration: 79 s, loss: 0.0180, acc: 99.6078
原笔记输出 · 本次未执行
 85%|████████████████████████████████████████████████████████████████████▊            | 17/20 [35:40<06:11, 124.00s/it]
原笔记输出 · 本次未执行
Accuracy of the network on the test images: 88 %
Epoch 18, duration: 78 s, loss: 0.0183, acc: 99.5833
原笔记输出 · 本次未执行
 90%|████████████████████████████████████████████████████████████████████████▉        | 18/20 [37:44<04:07, 123.79s/it]
原笔记输出 · 本次未执行
Accuracy of the network on the test images: 88 %
Epoch 19, duration: 78 s, loss: 0.0190, acc: 99.5956
原笔记输出 · 本次未执行
 95%|████████████████████████████████████████████████████████████████████████████▉    | 19/20 [39:47<02:03, 123.72s/it]
原笔记输出 · 本次未执行
Accuracy of the network on the test images: 88 %
Epoch 20, duration: 79 s, loss: 0.0184, acc: 99.5833
原笔记输出 · 本次未执行
100%|█████████████████████████████████████████████████████████████████████████████████| 20/20 [41:50<00:00, 125.55s/it]
原笔记输出 · 本次未执行
Accuracy of the network on the test images: 88 %
Finished Training
原笔记输出 · 本次未执行

4.3 As we can see the model reached 90% training accuracy by epoch 10.

PYTHON · 仅供阅读
# plot the stats

f, axarr = plt.subplots(2,2, figsize = (12, 8))
axarr[0, 0].plot(training_losses)
axarr[0, 0].set_title("Training loss")
axarr[0, 1].plot(training_accs)
axarr[0, 1].set_title("Training acc")
axarr[1, 0].plot(test_accs)

axarr[1, 0].set_title("Test acc")
原笔记输出 · 本次未执行
Text(0.5, 1.0, 'Test acc')
原笔记输出 · 本次未执行
<Figure size 864x576 with 4 Axes>

输出图整理: 训练loss、训练准确率与逐轮验证准确率可从上方原日志阅读。模型经修正的计数方式未重跑,保留旧日志并说明评估边界。

4.4 Evaluate the model on single images (e.g for production)

Next we can use the model on our own images. For that we need to tie the class numbers for which the model returns probablities with the names of those classes.

PYTHON · 仅供阅读
# tie the class indices to their names

def find_classes(dir):
    classes = os.listdir(dir)
    classes.sort()
    class_to_idx = {classes[i]: i for i in range(len(classes))}
    return classes, class_to_idx
classes, c_to_idx = find_classes(dataset_dir+"train")
PYTHON · 仅供阅读
# test the model on random images

# switch the model to evaluation mode to make dropout and batch norm work in eval mode
model_ft.eval()

# transforms for the input image
loader = transforms.Compose([transforms.Resize((400, 400)),
                                transforms.ToTensor(),
                                transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])
image = Image.open(dataset_dir+"test/Mercedes-Benz C-Class Sedan 2012/01977.jpg")
image = loader(image).float()
image = torch.autograd.Variable(image, requires_grad=True)
image = image.unsqueeze(0)
image = image.to(device)
output = model_ft(image)
conf, predicted = torch.max(torch.softmax(output, dim=1), 1)

整理注: 原单图预处理与训练的尺寸/归一化不同;实际推理应复用test_tfms。原输出8.37是logit,不是概率;修正版输出层先softmax,历史输出保留并注明。

PYTHON · 仅供阅读
# get the class name of the prediction
display(Image.open(dataset_dir+"test/Mercedes-Benz C-Class Sedan 2012/01977.jpg"))
print(classes[predicted.item()], "confidence: ", conf.item())
原笔记输出 · 已脱敏 · 本次未执行
<PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=569x355 at [ADDRESS]>

输出图整理: 原车辆照片改为分类流程说明:加载图片→与训练一致的预处理→模型→类别分数/概率→索引映射车型。原打印结果仍是旧logit记录,不再发布照片。

原笔记输出 · 本次未执行
Mercedes-Benz C-Class Sedan 2012 confidence:  8.371956825256348

5.Save and load model

PYTHON · 仅供阅读
PATH = 'car_model.pth'
torch.save(model_ft.state_dict(), PATH)
PYTHON · 仅供阅读
model_loaded = torch.load(PATH)
model_loaded

整理参考资料