Re:从零开始的行人重识别(六)

Zheng Z, Zheng L, Yang Y. A discriminatively learned CNN embedding for person reidentification[J]. ACM Transactions on Multimedia Computing, Communications, and Applications (TOMM), 2018, 14(1): 13.

从本篇开始复现论文,这里参考的模型结构是著名的IDE网络,这个网络的思想就是结合分类和验证网络来共同学习,使得模型提取得到的行人特征嵌入既能比较两个行人是否是同一人,又能分类得知这个人是谁。而在推理阶段,则是使用分类器之前的特征张量来计算距离。

前期准备

由于模型评估指标计算时间较长,于是采用Cython编写的外部库来计算。如果没安装的同学要注意自行安装,可能需要重新编译。(下载链接 提取码:xerh)

需要使用的库文件如下:

import copy
import os
import random
import re
import time
from collections import defaultdict

import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import torchvision
import torchvision.models as models
import torchvision.transforms as transforms
from PIL import Image
from torch.nn import init
from torch.utils.data import DataLoader, Dataset
from torch.utils.data.sampler import RandomSampler, Sampler

import metrics

try:
    from metrics.rank_cylib.rank_cy import evaluate_cy
    IS_CYTHON_AVAI = True
except ImportError:
    IS_CYTHON_AVAI = False
    warnings.warn(
        'Cython evaluation (very fast so highly recommended) is '
        'unavailable, now use python evaluation.'
    )

device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")

首先我们需要定义一个AverageMeter类来帮助我们记录训练过程中的变量:

class AverageMeter(object):
    """Computes and stores the average and current value.

    Examples::
        >>> # Initialize a meter to record loss
        >>> losses = AverageMeter()
        >>> # Update meter after every minibatch update
        >>> losses.update(loss_value, batch_size)
    """
    def __init__(self):
        self.reset()

    def reset(self):
        self.val = 0
        self.avg = 0
        self.sum = 0
        self.count = 0

    def update(self, val, n=1):
        self.val = val
        self.sum += val * n
        self.count += n
        self.avg = self.sum / self.count

模型核心代码

首先我们需要定义一个数据集类,将数据集划分为训练集、查询集和测试集:

class Market1501(Dataset):
    """Market1501.
    
    Reference:
        Zheng et al. Scalable Person Re-identification: A Benchmark. ICCV 2015.
        
    Dataset statistics:
        - identities: 1501 (+1 for background).
        - images: 12936 (train) + 3368 (query) + 15913 (gallery).
    """
    def __init__(self,root,mode='train',transform=None):
        super(Market1501,self).__init__()
        self.root = root
        self.mode = mode
        self.transform = transform
        
        if self.mode == 'train':
            self.train_dir = os.path.join(self.root,'bounding_box_train')
            self.train = self.process_path(self.train_dir, relabel=True)
            self.data = self.train
        elif self.mode == 'query':
            self.query_dir = os.path.join(self.root,'query')
            self.query = self.process_path(self.query_dir, relabel=False)
            self.data = self.query
        elif self.mode == 'gallery':
            self.gallery_dir = os.path.join(self.root,'bounding_box_test')
            self.gallery = self.process_path(self.gallery_dir, relabel=False)
            self.data = self.gallery
        else:
            raise ValueError('Invalid mode. Got {}, but expected to be one of [train | query | gallery]'.format(self.mode))
        
    def __len__(self):
        return len(self.data)
        
        
    def __getitem__(self,index):
        img_path, pid, camid = self.data[index]
        img = Image.open(img_path).convert('RGB')
        if self.transform is not None:
            img = self.transform(img)
        return img, pid, camid, img_path
    
    def process_path(self,path,relabel=False):
        img_paths = [os.path.join(path, x) for x in os.listdir(path) if x.endswith('.jpg')]
        pattern = re.compile(r'([-\d]+)_c(\d)')
        pid_container = set()
        for img_path in img_paths:
            pid,_ = map(int,pattern.search(img_path).groups())
            if pid == -1:
                continue
            pid_container.add(pid)
        pid2label = {pid:label for label, pid in enumerate(pid_container)}
        
        data = []
        for img_path in img_paths:
            pid,camid = map(int, pattern.search(img_path).groups())
            if pid == -1:
                continue
            camid -= 1
            if relabel:
                pid = pid2label[pid]
            data.append((img_path, pid, camid))
            
        return data

然后就是定义我们的网络结构了,我们这里就使用ResNet-50作为骨干网络。这里需要注意的是我们的输出既要返回分类后的结果用于训练,也要返回特征张量用于推理和评估。这里模型的参数基本都初始化为ResNet-50在ImageNet上预训练的模型,其余参数则是采用了正态分布或者何凯明提出方法进行初始化:

def weights_init_kaiming(m):
    classname = m.__class__.__name__
    if classname.find('Conv') != -1:
        init.kaiming_normal_(m.weight.data, a=0, mode='fan_in') # For old pytorch, you may use kaiming_normal.
    elif classname.find('Linear') != -1:
        init.kaiming_normal_(m.weight.data, a=0, mode='fan_out')
        init.constant_(m.bias.data, 0.0)
    elif classname.find('BatchNorm1d') != -1:
        init.normal_(m.weight.data, 1.0, 0.02)
        init.constant_(m.bias.data, 0.0)

def weights_init_normal(m):
    classname = m.__class__.__name__
    if classname.find('Linear') != -1:
        init.normal_(m.weight.data, std=0.001)
        init.constant_(m.bias.data, 0.0)       

class IDE(nn.Module):
    def __init__(self, num_classes, reduced_dim=512):
        super(IDE, self).__init__()
        base_model = models.resnet50(pretrained=True)
        base_model.avgpool = nn.AdaptiveAvgPool2d((1,1))
        self.model = base_model
        
        add_block = []
        add_block += [nn.Linear(2048,reduced_dim)]
        add_block += [nn.BatchNorm1d(reduced_dim)]
        add_block = nn.Sequential(*add_block)
        add_block.apply(weights_init_kaiming)
        classifier = []
        classifier += [nn.Linear(reduced_dim,num_classes)]
        classifier = nn.Sequential(*classifier)
        classifier.apply(weights_init_normal)
        
        self.add_block = add_block
        self.classifier = classifier
        
    def forward(self, x):
        x = self.model.conv1(x)
        x = self.model.bn1(x)
        x = self.model.relu(x)
        x = self.model.maxpool(x)
        x = self.model.layer1(x)
        x = self.model.layer2(x)
        x = self.model.layer3(x)
        x = self.model.layer4(x)
        x = self.model.avgpool(x)
        x = x.view(x.size(0), x.size(1))
        # feature
        f = self.add_block(x)
        # classifier
        x = self.classifier(f)
        return x, f

训练

加载数据集,需要用到一些数据增强:

mean = np.array([0.485, 0.456, 0.406])
std = np.array([0.229, 0.224, 0.225])

train_transform = transforms.Compose([
    transforms.Resize((256,128)),
    transforms.RandomHorizontalFlip(),
    transforms.RandomCrop((256,128),padding=(8,16,8,16)),
    transforms.ToTensor(),
    transforms.Normalize(mean,std)
])

dataset_path = 'D:\\backup\\datasets\\market1501\\Market-1501-v15.09.15' # dataset path
train_dataset = Market1501(dataset_path,mode='train',transform=train_transform)
train_dataloader = DataLoader(
    train_dataset,
    batch_size=32,
    pin_memory=torch.cuda.is_available(),
    drop_last=False
)

创建模型,为模型的不同参数设置不同的学习率,并设置损失函数:

model = IDE(751)
lr = 0.0003
ignored_params = list(map(id, model.add_block.parameters()))
ignored_params += list(map(id, model.classifier.parameters()))
base_params = filter(lambda p: id(p) not in ignored_params, model.parameters())
optimizer = torch.optim.Adam([
    {'params':base_params,'lr':0.1*lr},
    {'params':model.add_block.parameters(),'lr':lr},
    {'params':model.classifier.parameters(),'lr':lr}],
    lr=lr,
    betas=(0.9,0.99),
    weight_decay=5e-04
)
criterion = nn.CrossEntropyLoss().to(device)

训练,这里需要默默等待一会儿:

model.to(device)
model.train()

num_batches = len(train_dataloader)
max_epoch = 50
for epoch in range(0, max_epoch):
    losses = AverageMeter()
    accs = AverageMeter()
    batch_time = AverageMeter()
    data_time = AverageMeter()
    
    end = time.time()
    for batch_idx, data in enumerate(train_dataloader):
        data_time.update(time.time() - end)
        
        imgs = data[0]
        pids = data[1]
        imgs = imgs.to(device)
        pids = pids.to(device)
        
        optimizer.zero_grad()
        outputs = model(imgs)
        preds = outputs[0]
        loss = criterion(preds,pids)
        loss.backward()
        optimizer.step()
        
        batch_time.update(time.time() - end)
        
        losses.update(loss.item(), pids.size(0))
        accs.update(metrics.accuracy(preds, pids)[0].item())
        
        if (batch_idx+1) % 10 == 0:
            print('Epoch: [{0}/{1}][{2}/{3}]\t'
                  'Time {batch_time.val:.3f} ({batch_time.avg:.3f})\t'
                  'Data {data_time.val:.3f} ({data_time.avg:.3f})\t'
                  'Loss {loss.val:.4f} ({loss.avg:.4f})\t'
                  'Acc {acc.val:.2f} ({acc.avg:.2f})\t'.format(
                  epoch+1, max_epoch, batch_idx+1, num_batches,
                  batch_time=batch_time,
                  data_time=data_time,
                  loss=losses,
                  acc=accs,
                  )
            )
        end = time.time()
 
    if True:
        state = {
            'state_dict': model.state_dict(),
            'epoch': epoch,
            'optimizer': optimizer.state_dict()
        }
        save_path = './model/IDE'
        save_filename = os.path.join(save_path,'checkpoint-'+str(epoch)+'.pth.tar')
        if not os.path.exists(save_path):
            os.makedirs(save_path)
        torch.save(state, save_filename)

评估

先把训练好的模型重新加载,同时也把测试数据加载了:

model.to(device)
state = torch.load('model/IDE/checkpoint-49.pth.tar')
model.load_state_dict(state['state_dict'])

test_transform = transforms.Compose([
    transforms.Resize((256,128)),
    transforms.ToTensor(),
    transforms.Normalize(mean,std)
])
query_dataset = Market1501(dataset_path,mode='query',transform=test_transform)
gallery_dataset = Market1501(dataset_path,mode='gallery',transform=test_transform)
query_dataloader = DataLoader(
    query_dataset,
    batch_size=32,
    pin_memory=torch.cuda.is_available(),
    drop_last=False
)
gallery_dataloader = DataLoader(
    gallery_dataset,
    batch_size=32,
    pin_memory=torch.cuda.is_available(),
    drop_last=False
)

从查询集和测试集提取特征张量:

print('Extracting features from query set ...')
qf, q_pids, q_camids = [], [], []
for batch_idx, data in enumerate(query_dataloader):
    imgs, pids, camids = data[0], data[1], data[2]
    imgs = imgs.to(device)
    model.eval()
    features = model(imgs)[1]
    features = features.data.cpu()
    qf.append(features)
    q_pids.extend(pids)
    q_camids.extend(camids)
qf = torch.cat(qf,0)
q_pids = np.asarray(q_pids)
q_camids = np.asarray(q_camids)
print('Done, obtained {}-by-{} matrix'.format(qf.size(0), qf.size(1)))
print('Extracting features from gallery set ...')
gf, g_pids, g_camids = [], [], [] 
for batch_idx, data in enumerate(gallery_dataloader):
    imgs, pids, camids = data[0], data[1], data[2]
    imgs = imgs.to(device)
    model.eval()
    features = model(imgs)[1]
    features = features.data.cpu()
    gf.append(features)
    g_pids.extend(pids)
    g_camids.extend(camids)
gf = torch.cat(gf, 0)
g_pids = np.asarray(g_pids)
g_camids = np.asarray(g_camids)
print('Done, obtained {}-by-{} matrix'.format(gf.size(0), gf.size(1)))

计算距离矩阵,这里可以对特征归一化和重排序:

# normalize, better performance
# qf = F.normalize(qf, p=2, dim=1)
# gf = F.normalize(gf, p=2, dim=1)

distmat = metrics.compute_distance_matrix(qf, gf, 'euclidean') # cosine may have better performance
distmat = distmat.numpy()

# re-ranking, better performance
# distmat_qq = metrics.compute_distance_matrix(qf, qf, 'euclidean')
# distmat_gg = metrics.compute_distance_matrix(gf, gf, 'euclidean')
# distmat = re_ranking(distmat, distmat_qq, distmat_gg)

如果需要re-ranking,需要以下函数:

def re_ranking(q_g_dist, q_q_dist, g_g_dist, k1=20, k2=6, lambda_value=0.3):

    # The following naming, e.g. gallery_num, is different from outer scope.
    # Don't care about it.

    original_dist = np.concatenate(
      [np.concatenate([q_q_dist, q_g_dist], axis=1),
       np.concatenate([q_g_dist.T, g_g_dist], axis=1)],
      axis=0)
    original_dist = np.power(original_dist, 2).astype(np.float32)
    original_dist = np.transpose(1. * original_dist/np.max(original_dist,axis = 0))
    V = np.zeros_like(original_dist).astype(np.float32)
    initial_rank = np.argsort(original_dist).astype(np.int32)

    query_num = q_g_dist.shape[0]
    gallery_num = q_g_dist.shape[0] + q_g_dist.shape[1]
    all_num = gallery_num

    for i in range(all_num):
        # k-reciprocal neighbors
        forward_k_neigh_index = initial_rank[i,:k1+1]
        backward_k_neigh_index = initial_rank[forward_k_neigh_index,:k1+1]
        fi = np.where(backward_k_neigh_index==i)[0]
        k_reciprocal_index = forward_k_neigh_index[fi]
        k_reciprocal_expansion_index = k_reciprocal_index
        for j in range(len(k_reciprocal_index)):
            candidate = k_reciprocal_index[j]
            candidate_forward_k_neigh_index = initial_rank[candidate,:int(np.around(k1/2.))+1]
            candidate_backward_k_neigh_index = initial_rank[candidate_forward_k_neigh_index,:int(np.around(k1/2.))+1]
            fi_candidate = np.where(candidate_backward_k_neigh_index == candidate)[0]
            candidate_k_reciprocal_index = candidate_forward_k_neigh_index[fi_candidate]
            if len(np.intersect1d(candidate_k_reciprocal_index,k_reciprocal_index))> 2./3*len(candidate_k_reciprocal_index):
                k_reciprocal_expansion_index = np.append(k_reciprocal_expansion_index,candidate_k_reciprocal_index)

        k_reciprocal_expansion_index = np.unique(k_reciprocal_expansion_index)
        weight = np.exp(-original_dist[i,k_reciprocal_expansion_index])
        V[i,k_reciprocal_expansion_index] = 1.*weight/np.sum(weight)
    original_dist = original_dist[:query_num,]
    if k2 != 1:
        V_qe = np.zeros_like(V,dtype=np.float32)
        for i in range(all_num):
            V_qe[i,:] = np.mean(V[initial_rank[i,:k2],:],axis=0)
        V = V_qe
        del V_qe
    del initial_rank
    invIndex = []
    for i in range(gallery_num):
        invIndex.append(np.where(V[:,i] != 0)[0])

    jaccard_dist = np.zeros_like(original_dist,dtype = np.float32)


    for i in range(query_num):
        temp_min = np.zeros(shape=[1,gallery_num],dtype=np.float32)
        indNonZero = np.where(V[i,:] != 0)[0]
        indImages = []
        indImages = [invIndex[ind] for ind in indNonZero]
        for j in range(len(indNonZero)):
            temp_min[0,indImages[j]] = temp_min[0,indImages[j]]+ np.minimum(V[i,indNonZero[j]],V[indImages[j],indNonZero[j]])
        jaccard_dist[i] = 1-temp_min/(2.-temp_min)

    final_dist = jaccard_dist*(1-lambda_value) + original_dist*lambda_value
    del original_dist
    del V
    del jaccard_dist
    final_dist = final_dist[:query_num,query_num:]
    return final_dist

最后算一下rank-1和mAP:

cmc, mAP = metrics.evaluate_rank(
            distmat,
            q_pids,
            g_pids,
            q_camids,
            g_camids,
        )
print(cmc[0], mAP)

参考

[1] Zhou K, Xiang T. Torchreid: A Library for Deep Learning Person Re-Identification in Pytorch[J]. arXiv preprint arXiv:1910.10093, 2019.

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 203,098评论 5 476
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,213评论 2 380
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 149,960评论 0 336
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,519评论 1 273
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,512评论 5 364
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,533评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,914评论 3 395
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,574评论 0 256
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,804评论 1 296
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,563评论 2 319
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,644评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,350评论 4 318
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,933评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,908评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,146评论 1 259
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,847评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,361评论 2 342

推荐阅读更多精彩内容