def get_train_loader(dataset, height, width, batch_size, workers, num_instances, iters, trainset=None): normalizer = T.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) train_transformer = T.Compose([ T.Resize((height, width), interpolation=3), T.RandomHorizontalFlip(p=0.5), T.Pad(10), T.RandomCrop((height, width)), T.ToTensor(), normalizer, T.RandomErasing(probability=0.5, mean=[0.485, 0.456, 0.406]) ]) train_set = dataset.train if trainset is None else trainset rmgs_flag = num_instances > 0 if rmgs_flag: sampler = RandomMultipleGallerySampler(train_set, num_instances) else: sampler = None train_loader = IterLoader( DataLoader(Preprocessor(train_set, root=dataset.images_dir, transform=train_transformer, mutual=False), batch_size=batch_size, num_workers=workers, sampler=sampler, shuffle=not rmgs_flag, pin_memory=True, drop_last=True), length=iters) return train_loader
def get_data(name, split_id, data_dir, height, width, batch_size, num_instances, workers, combine_trainval): root = osp.join(data_dir, name) dataset = datasets.create(name, root, num_val=0.1, split_id=split_id) normalizer = T.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) train_set = dataset.trainval if combine_trainval else dataset.train num_classes = (dataset.num_trainval_ids if combine_trainval else dataset.num_train_ids) train_transformer = T.Compose([ Resize((256, 128)), T.RandomSizedRectCrop(height, width), T.RandomHorizontalFlip(), T.ToTensor(), normalizer, T.RandomErasing(probability=0.5, sh=0.2, r1=0.3) ]) test_transformer = T.Compose([ T.RectScale(height, width), T.ToTensor(), normalizer, ]) train_loader = DataLoader(Preprocessor(train_set, root=dataset.images_dir, transform=train_transformer), batch_size=batch_size, num_workers=workers, sampler=RandomIdentitySampler( train_set, num_instances), pin_memory=True, drop_last=True) val_loader = DataLoader(Preprocessor(dataset.val, root=dataset.images_dir, transform=test_transformer), batch_size=batch_size, num_workers=workers, shuffle=False, pin_memory=True) test_loader = DataLoader(Preprocessor( list(set(dataset.query) | set(dataset.gallery)), root=dataset.images_dir, transform=test_transformer), batch_size=batch_size, num_workers=workers, shuffle=False, pin_memory=True) return dataset, num_classes, train_loader, val_loader, test_loader
def get_data(dataname, data_dir, height, width, batch_size, camstyle=0, re=0, workers=8): root = osp.join(data_dir, dataname) dataset = datasets.create(dataname, root) normalizer = T.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) num_classes = dataset.num_train_ids train_transformer = T.Compose([ T.RandomSizedRectCrop(height, width), T.RandomHorizontalFlip(), T.ToTensor(), normalizer, T.RandomErasing(EPSILON=re), ]) test_transformer = T.Compose([ T.Resize((height, width), interpolation=3), T.ToTensor(), normalizer, ]) train_loader = DataLoader( Preprocessor(dataset.train, root=osp.join(dataset.images_dir, dataset.train_path), transform=train_transformer), batch_size=batch_size, num_workers=workers, shuffle=True, pin_memory=True, drop_last=True) query_loader = DataLoader( Preprocessor(dataset.query, root=osp.join(dataset.images_dir, dataset.query_path), transform=test_transformer), batch_size=batch_size, num_workers=workers, shuffle=False, pin_memory=True) gallery_loader = DataLoader( Preprocessor(dataset.gallery, root=osp.join(dataset.images_dir, dataset.gallery_path), transform=test_transformer), batch_size=batch_size, num_workers=workers, shuffle=False, pin_memory=True) if camstyle <= 0: camstyle_loader = None else: camstyle_loader = DataLoader( Preprocessor(dataset.camstyle, root=osp.join(dataset.images_dir, dataset.camstyle_path), transform=train_transformer), batch_size=camstyle, num_workers=workers, shuffle=True, pin_memory=True, drop_last=True) return dataset, num_classes, train_loader, query_loader, gallery_loader, camstyle_loader
def get_data(data_dir, source, target, height, width, batch_size, re=0, workers=8): dataset = DA(data_dir, source, target) normalizer = T.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) num_classes = dataset.num_train_ids train_transformer = T.Compose([ T.RandomSizedRectCrop(height, width), T.RandomHorizontalFlip(), T.ToTensor(), normalizer, T.RandomErasing(EPSILON=re), ]) test_transformer = T.Compose([ T.Resize((height, width), interpolation=3), T.ToTensor(), normalizer, ]) source_train_loader = DataLoader( Preprocessor(dataset.source_train, root=osp.join(dataset.source_images_dir, dataset.source_train_path), transform=train_transformer), batch_size=batch_size, num_workers=workers, shuffle=True, pin_memory=True, drop_last=True) target_train_loader = DataLoader( UnsupervisedCamStylePreprocessor(dataset.target_train, root=osp.join(dataset.target_images_dir, dataset.target_train_path), camstyle_root=osp.join(dataset.target_images_dir, dataset.target_train_camstyle_path), num_cam=dataset.target_num_cam, transform=train_transformer), batch_size=batch_size, num_workers=workers, shuffle=True, pin_memory=True, drop_last=True) query_loader = DataLoader( Preprocessor(dataset.query, root=osp.join(dataset.target_images_dir, dataset.query_path), transform=test_transformer), batch_size=batch_size, num_workers=workers, shuffle=False, pin_memory=True) gallery_loader = DataLoader( Preprocessor(dataset.gallery, root=osp.join(dataset.target_images_dir, dataset.gallery_path), transform=test_transformer), batch_size=batch_size, num_workers=workers, shuffle=False, pin_memory=True) return dataset, num_classes, source_train_loader, target_train_loader, query_loader, gallery_loader
def get_data(name, split_id, data_dir, big_height, big_width, target_height, target_width, batch_size, num_instances, workers, combine_trainval): root = osp.join(data_dir, name) dataset = datasets.create(name, root, split_id=split_id, download=True) normalizer = T.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) train_set = dataset.trainval if combine_trainval else dataset.train num_classes = (dataset.num_trainval_ids if combine_trainval else dataset.num_train_ids) train_transformer = T.Compose([ T.ResizeRandomCrop(big_height, big_width, target_height, target_width), T.RandomHorizontalFlip(), T.ToTensor(), normalizer, T.RandomErasing(0.5), ]) test_transformer = T.Compose([ T.RectScale(target_height, target_width), T.ToTensor(), normalizer, ]) train_loader = DataLoader( Attribute_Preprocessor(train_set, root=dataset.images_dir, transform=train_transformer), batch_size=batch_size, num_workers=workers, sampler=RandomIdentityAttributeSampler(train_set, num_instances), pin_memory=True, drop_last=True) test_loader = DataLoader(Attribute_Preprocessor( list(set(dataset.query) | set(dataset.gallery)), root=dataset.images_dir, transform=test_transformer), batch_size=batch_size, num_workers=workers, shuffle=False, pin_memory=True) return dataset, num_classes, train_loader, test_loader
def get_data(sourceName, mteName, split_id, data_dir, height, width, batch_size, workers, combine,num_instances=8): root = osp.join(data_dir, sourceName) rootMte = osp.join(data_dir, mteName) sourceSet = datasets.create(sourceName, root, num_val=0.1, split_id=split_id) mteSet = datasets.create(mteName, rootMte, num_val=0.1, split_id=split_id) num_classes = sourceSet.num_trainval_ids if combine else sourceSet.num_train_ids class_meta = mteSet.num_trainval_ids if combine else mteSet.num_train_ids normalizer = T.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) test_transformer = T.Compose([ T.RectScale(height, width), T.ToTensor(), normalizer, ]) defen_train_transformer = T.Compose([ Resize((height, width)), T.RandomSizedRectCrop(height, width), T.RandomHorizontalFlip(), T.ToTensor(), normalizer, T.RandomErasing(probability=0.5, sh=0.2, r1=0.3) ]) meta_train_loader = DataLoader( Preprocessor(sourceSet.trainval, root=sourceSet.images_dir, transform=defen_train_transformer), batch_size=batch_size, num_workers=workers, sampler=RandomIdentitySampler(sourceSet.trainval, num_instances), pin_memory=True, drop_last=True) meta_test_loader=DataLoader( Preprocessor(mteSet.trainval, root=mteSet.images_dir, transform=defen_train_transformer), batch_size=batch_size, num_workers=workers, sampler=RandomIdentitySampler(mteSet.trainval, num_instances), pin_memory=True, drop_last=True) sc_test_loader = DataLoader( Preprocessor(list(set(sourceSet.query) | set(sourceSet.gallery)), root=sourceSet.images_dir, transform=test_transformer), batch_size=batch_size, num_workers=workers, shuffle=False, pin_memory=True) return sourceSet, mteSet, num_classes, meta_train_loader, meta_test_loader,sc_test_loader,class_meta
def get_dataloader(self, dataset, training=False): normalizer = T.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) if training: transformer = T.Compose([ T.RandomSizedRectCrop(self.data_height, self.data_width), T.RandomHorizontalFlip(), T.ToTensor(), normalizer, T.RandomErasing(probability=0.5, sh=0.2, r1=0.3) ]) else: transformer = T.Compose([ T.Resize((self.data_height, self.data_width)), T.ToTensor(), normalizer, ]) if training and self.num_classes == 0: data_loader = DataLoader(Preprocessor(dataset, root='', transform=transformer), batch_size=self.batch_size, num_workers=self.data_workers, sampler=RandomIdentitySampler( dataset, self.num_instances), pin_memory=True, drop_last=training) else: data_loader = DataLoader(Preprocessor(dataset, root='', transform=transformer), batch_size=self.batch_size, num_workers=self.data_workers, shuffle=training, pin_memory=True, drop_last=training) current_status = "Training" if training else "Test" print("create dataloader for {} with batch_size {}".format( current_status, self.batch_size)) return data_loader
def main(args): os.environ['CUDA_VISIBLE_DEVICES'] = args.gpu_devices np.random.seed(args.seed) torch.manual_seed(args.seed) cudnn.benchmark = True # Redirect print to both console and log file if not args.evaluate: sys.stdout = Logger(osp.join(args.logs_dir, 'log.txt')) # Create data loaders assert args.num_instances > 1, "num_instances should be greater than 1" assert args.batch_size % args.num_instances == 0, \ 'num_instances should divide batch_size' if args.height is None or args.width is None: args.height, args.width = (144, 56) if args.arch == 'inception' else \ (256, 128) ## get_source_data src_dataset, src_extfeat_loader = \ get_source_data(args.src_dataset, args.data_dir, args.height, args.width, args.batch_size, args.workers) # get_target_data tgt_dataset, num_classes, tgt_extfeat_loader, test_loader = \ get_data(args.tgt_dataset, args.data_dir, args.height, args.width, args.batch_size, args.workers) # Create model # Hacking here to let the classifier be the last feature embedding layer # Net structure: avgpool -> FC(2048) -> FC(args.features) num_class = 0 if args.src_dataset == 'dukemtmc': model = models.create(args.arch, num_classes=num_class, num_split=args.num_split, cluster=args.dce_loss) #duke elif args.src_dataset == 'market1501': model = models.create(args.arch, num_classes=num_class, num_split=args.num_split, cluster=args.dce_loss) else: raise RuntimeError('Please specify the number of classes (ids) of the network.') # Load from checkpoint start_epoch = best_top1 = 0 if args.resume: print('Resuming checkpoints from finetuned model on another dataset...\n') checkpoint = load_checkpoint(args.resume) model.load_state_dict(checkpoint, strict=False) else: raise RuntimeWarning('Not using a pre-trained model') model = nn.DataParallel(model).cuda() # Distance metric metric = DistanceMetric(algorithm=args.dist_metric) # Evaluator evaluator = Evaluator(model, print_freq=args.print_freq) print("Test with the original model trained on source domain:") best_top1 = evaluator.evaluate(test_loader, tgt_dataset.query, tgt_dataset.gallery) if args.evaluate: return # Criterion criterion = [] criterion.append(TripletLoss(margin=args.margin,num_instances=args.num_instances).cuda()) criterion.append(TripletLoss(margin=args.margin,num_instances=args.num_instances).cuda()) #multi lr base_param_ids = set(map(id, model.module.base.parameters())) new_params = [p for p in model.parameters() if id(p) not in base_param_ids] param_groups = [ {'params': model.module.base.parameters(), 'lr_mult': 1.0}, {'params': new_params, 'lr_mult': 1.0}] # Optimizer optimizer = torch.optim.SGD(param_groups, lr=args.lr, momentum=0.9, weight_decay=args.weight_decay) ##### adjust lr def adjust_lr(epoch): if epoch <= 7: lr = args.lr elif epoch <=14: lr = 0.3 * args.lr else: lr = 0.1 * args.lr for g in optimizer.param_groups: g['lr'] = lr * g.get('lr_mult', 1) ##### training stage transformer on input images normalizer = T.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) train_transformer = T.Compose([ Resize((args.height,args.width)), T.RandomHorizontalFlip(), T.ToTensor(), normalizer, T.RandomErasing(probability=0.5, sh=0.2, r1=0.3) ]) # Start training iter_nums = args.iteration start_epoch = args.start_epoch cluster_list = [] top_percent = args.rho EF = 100 // iter_nums + 1 eug = None for iter_n in range(start_epoch, iter_nums): #### get source datas' feature if args.load_dist and iter_n == 0: dist = pickle.load(open('dist' + str(args.num_split) + '.pkl', 'rb')) euclidean_dist_list = dist['euclidean'] rerank_dist_list = dist['rerank'] else: source_features, _ = extract_features(model, src_extfeat_loader, for_eval=False) if isinstance(source_features[src_dataset.trainval[0][0]], list): len_f = len(source_features[src_dataset.trainval[0][0]]) source_features = [torch.cat([source_features[f][i].unsqueeze(0) for f, _, _ in src_dataset.trainval], 0) for i in range(len_f)] else: source_features = torch.cat([source_features[f].unsqueeze(0) for f, _, _ in src_dataset.trainval], 0) # synchronization feature order with s_dataset.trainval #### extract training images' features print('Iteration {}: Extracting Target Dataset Features...'.format(iter_n+1)) target_features, _ = extract_features(model, tgt_extfeat_loader, for_eval=False) if isinstance(target_features[tgt_dataset.trainval[0][0]], list): len_f = len(target_features[tgt_dataset.trainval[0][0]]) target_features = [torch.cat([target_features[f][i].unsqueeze(0) for f, _, _ in tgt_dataset.trainval], 0) for i in range(len_f)] else: target_features = torch.cat([target_features[f].unsqueeze(0) for f, _, _ in tgt_dataset.trainval], 0) # synchronization feature order with dataset.trainval #### calculate distance and rerank result print('Calculating feature distances...') # target_features = target_features.numpy() euclidean_dist_list, rerank_dist_list = compute_dist( source_features, target_features, lambda_value=args.lambda_value, no_rerank=args.no_rerank, num_split=args.num_split) # lambda=1 means only source dist del target_features del source_features labels_list, cluster_list = generate_selflabel( euclidean_dist_list, rerank_dist_list, iter_n, args, cluster_list) #### generate new dataset train_loader = generate_dataloader(tgt_dataset, labels_list, train_transformer, iter_n, args) if iter_n == 5: u_data, l_data = updata_lable(tgt_dataset, labels_list[0], args.tgt_dataset, sample=args.sample) eug = EUG(model_name=args.arch, batch_size=args.batch_size, mode=args.mode, num_classes=num_class, data_dir=args.data_dir, l_data=l_data, u_data=u_data, print_freq=args.print_freq, save_path=args.logs_dir, pretrained_model=model, rerank=True) eug.model = model if eug is not None: nums_to_select = int(min((iter_n + 1) * int(len(u_data) // (iter_nums)), len(u_data))) pred_y, pred_score = eug.estimate_label() print('This is running {} with EF= {}%, step {}:\t Nums_to_be_select {}, \t Logs-dir {}'.format( args.mode, EF, iter_n+1, nums_to_select, args.logs_dir )) selected_idx = eug.select_top_data(pred_score, nums_to_select) new_train_data = eug.generate_new_train_data(selected_idx, pred_y) eug_dataloader = eug.get_dataloader(new_train_data, training=True) top1 = iter_trainer(model, tgt_dataset, train_loader, eug_dataloader, test_loader, optimizer, criterion, args.epochs, args.logs_dir, args.print_freq, args.lr) eug.model = model del train_loader # del eug_dataloader else: top1 = iter_trainer(model, tgt_dataset, train_loader, None, test_loader, optimizer, criterion, args.epochs, args.logs_dir, args.print_freq, args.lr) del train_loader is_best = top1 > best_top1 best_top1 = max(top1, best_top1) save_checkpoint({ 'state_dict': model.module.state_dict(), 'epoch': iter_n + 1, 'best_top1': best_top1, # 'num_ids': num_ids, }, is_best, fpath=osp.join(args.logs_dir, 'checkpoint.pth.tar')) print('\n * Finished epoch {:3d} top1: {:5.1%} best: {:5.1%}{}\n'. format(iter_n+1, top1, best_top1, ' *' if is_best else ''))
def main(args): np.random.seed(args.seed) torch.manual_seed(args.seed) cudnn.benchmark = True # Create data loaders assert args.num_instances > 1, "num_instances should be greater than 1" assert args.batch_size % args.num_instances == 0, \ 'num_instances should divide batch_size' if args.height is None or args.width is None: args.height, args.width = (144, 56) if args.arch == 'inception' else \ (256, 128) # get source data src_dataset, src_extfeat_loader = \ get_source_data(args.src_dataset, args.data_dir, args.height, args.width, args.batch_size, args.workers) # get target data tgt_dataset, num_classes, tgt_extfeat_loader, test_loader = \ get_data(args.tgt_dataset, args.data_dir, args.height, args.width, args.batch_size, args.workers) # Create model # Hacking here to let the classifier be the number of source ids if args.src_dataset == 'dukemtmc': model = models.create(args.arch, num_classes=632, pretrained=False) elif args.src_dataset == 'market1501': model = models.create(args.arch, num_classes=676, pretrained=False) else: raise RuntimeError('Please specify the number of classes (ids) of the network.') # Load from checkpoint if args.resume: print('Resuming checkpoints from finetuned model on another dataset...\n') checkpoint = load_checkpoint(args.resume) model.load_state_dict(checkpoint['state_dict'], strict=False) else: raise RuntimeWarning('Not using a pre-trained model.') model = nn.DataParallel(model).cuda() # evaluator.evaluate(test_loader, tgt_dataset.query, tgt_dataset.gallery) # if args.evaluate: return # Criterion criterion = [ # TripletLoss(args.margin, args.num_instances, isAvg=True, use_semi=True).cuda(), SortedTripletLoss(args.margin, isAvg=True).cuda(), # HoughTripletLoss(args.margin, args.num_instances, isAvg=True, use_semi=True).cuda(), # None, None, None, None ] # Optimizer optimizer = torch.optim.Adam( model.parameters(), lr=args.lr ) # training stage transformer on input images normalizer = T.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) train_transformer = T.Compose([ T.Resize((args.height,args.width)), T.RandomHorizontalFlip(), T.ToTensor(), normalizer, T.RandomErasing(probability=0.5, sh=0.2, r1=0.3) ]) evaluator = Evaluator(model, print_freq=args.print_freq) evaluator.evaluate(test_loader, tgt_dataset.query, tgt_dataset.gallery) st_model = ST_Model(tgt_dataset.meta['num_cameras']) same = None # train_loader2 = None best_mAP = 0 # # Start training for iter_n in range(args.iteration): if args.lambda_value == 0: source_features = 0 else: # get source datas' feature source_features, _ = extract_features(model, src_extfeat_loader, print_freq=args.print_freq) # synchronization feature order with src_dataset.train source_features = torch.cat([source_features[f].unsqueeze(0) for f, _, _, _ in src_dataset.train], 0) # extract training images' features print('Iteration {}: Extracting Target Dataset Features...'.format(iter_n+1)) target_features, tarNames = extract_features(model, tgt_extfeat_loader, print_freq=args.print_freq) # synchronization feature order with dataset.train target_features = torch.cat([target_features[f].unsqueeze(0) for f, _, _, _ in tgt_dataset.trainval], 0) # target_real_label = np.asarray([tarNames[f].unsqueeze(0) for f, _, _, _ in tgt_dataset.trainval]) target_features = target_features.numpy() rerank_dist = re_ranking(source_features, target_features, lambda_value=args.lambda_value) ranking = np.argsort(rerank_dist)[:, 1:] if iter_n != 0: st_dist = np.zeros(rerank_dist.shape) for i, (_, _, c1, t1) in enumerate(tgt_dataset.trainval): for j, (_, _, c2, t2) in enumerate(tgt_dataset.trainval): if not same.in_peak(c1, c2, t1, t2, 0.25): st_dist[i, j] = 1 rerank_dist = rerank_dist + st_dist * 10 # if iter_n > 0: # rerank_dist = st_model.apply(rerank_dist, tgt_dataset.trainval, tgt_dataset.trainval) cluster = HDBSCAN(metric='precomputed', min_samples=10) # select & cluster images as training set of this epochs clusterRes = cluster.fit(rerank_dist.astype(np.float64)) labels, label_num = clusterRes.labels_, clusterRes.labels_.max() + 1 centers = np.zeros((label_num, target_features.shape[1])) nums = [0] * target_features.shape[1] print('clusters num =', label_num) # generate new dataset new_dataset = [] index = -1 for (fname, _, cam, timestamp), label in zip(tgt_dataset.trainval, labels): index += 1 if label == -1: continue # dont need to change codes in trainer.py _parsing_input function and sampler function after add 0 new_dataset.append((fname, label, cam, timestamp)) centers[label] += target_features[index] nums[label] += 1 print('Iteration {} have {} training images'.format(iter_n+1, len(new_dataset))) # learn ST model # if iter_n % 2 == 0: # if iter_n == 0: # cluster = HDBSCAN(metric='precomputed', min_samples=10) # # select & cluster images as training set of this epochs # clusterRes = cluster.fit(rerank_dist.astype(np.float64)) # labels, label_num = clusterRes.labels_, clusterRes.labels_.max() + 1 # centers = np.zeros((label_num, target_features.shape[1])) # nums = [0] * target_features.shape[1] # print('clusters num =', label_num) # # # generate new dataset # new_dataset = [] # index = -1 # for (fname, _, cam, timestamp), label in zip(tgt_dataset.trainval, labels): # index += 1 # if label == -1: continue # # dont need to change codes in trainer.py _parsing_input function and sampler function after add 0 # new_dataset.append((fname, label, cam, timestamp)) # centers[label] += target_features[index] # nums[label] += 1 # print('Iteration {} have {} training images'.format(iter_n + 1, len(new_dataset))) # same, _ = st_model.fit(new_dataset) # st_model.fit(tgt_dataset.trainval) same, _ = st_model.fit(new_dataset) train_loader = DataLoader( Preprocessor(new_dataset, root=tgt_dataset.images_dir, transform=train_transformer), batch_size=args.batch_size, num_workers=4, sampler=RandomIdentitySampler(new_dataset, args.num_instances), pin_memory=True, drop_last=True ) def filter(i, j): _, _, c1, t1 = tgt_dataset.trainval[i] _, _, c2, t2 = tgt_dataset.trainval[j] return st_model.val(c1, c2, t1, t2) > 0.01 # if iter_n == 0: # ranking = np.argsort(rerank_dist)[:, 1:] # dukemtmc # cluster_size = 23.535612535612536 # market1501 cluster_size = 17.22503328894807 must_conn = int(cluster_size / 2) might_conn = int(cluster_size * 2) length = len(tgt_dataset.trainval) pos = [[] for _ in range(length)] neg = [[] for _ in range(length)] for i in range(length): for j_ in range(might_conn): j = ranking[i][j_] if j_ < must_conn and i in ranking[j][:must_conn]: pos[i].append(j) elif i in ranking[j][:might_conn] and filter(i, j): pos[i].append(j) else: neg[i].append(j) # pos[i] = pos[i][-1:] # neg[i] = neg[i][:1] SP, SF, DP, DF = 0, 0, 0, 0 for i in range(length): for j in pos[i]: if tgt_dataset.trainval[i][1] == tgt_dataset.trainval[j][1]: SP += 1 else: SF += 1 for j in neg[i]: if tgt_dataset.trainval[i][1] == tgt_dataset.trainval[j][1]: DP += 1 else: DF += 1 print('stat: %.1f %.1f %.3f, %.3f' % ((SP + SF) / length, (DP + DF) / length, SP / (SP + SF), DF / (DP + DF))) train_loader2 = DataLoader( Preprocessor(tgt_dataset.trainval, root=tgt_dataset.images_dir, transform=train_transformer), batch_size=args.batch_size, num_workers=4, # sampler=RandomIdentitySampler(new_dataset, args.num_instances), # shuffle=True, sampler=TripletSampler(tgt_dataset.trainval, pos, neg), pin_memory=True, drop_last=True ) # learn visual model for i in range(label_num): centers[i] /= nums[i] criterion[3] = ClassificationLoss(normalize(centers, axis=1)).cuda() classOptimizer = torch.optim.Adam([ {'params': model.parameters()}, {'params': criterion[3].classifier.parameters(), 'lr': 1e-3} ], lr=args.lr) # trainer = HoughTrainer(model, st_model, train_loader, criterion, classOptimizer) trainer = ClassificationTrainer(model, train_loader, criterion, classOptimizer) trainer2 = Trainer(model, train_loader2, criterion, optimizer) for epoch in range(args.epochs): trainer.train(epoch) if epoch % 8 == 0: trainer2.train(epoch) # evaluator.evaluate(test_loader, tgt_dataset.query, tgt_dataset.gallery) rank_score = evaluator.evaluate(test_loader, tgt_dataset.query, tgt_dataset.gallery) if rank_score.map > best_mAP: best_mAP = rank_score.map save_checkpoint({ 'state_dict': model.module.state_dict(), 'epoch': epoch + 1, 'best_top1': rank_score.market1501[0], }, True, fpath=osp.join(args.logs_dir, 'adapted.pth.tar')) # Evaluate rank_score = evaluator.evaluate(test_loader, tgt_dataset.query, tgt_dataset.gallery) save_checkpoint({ 'state_dict': model.module.state_dict(), 'epoch': epoch + 1, 'best_top1': rank_score.market1501[0], }, False, fpath=osp.join(args.logs_dir, 'adapted.pth.tar')) return (rank_score.map, rank_score.market1501[0])
def main(args): np.random.seed(args.seed) torch.manual_seed(args.seed) cudnn.benchmark = True # Create data loaders assert args.num_instances > 1, "num_instances should be greater than 1" assert args.batch_size % args.num_instances == 0, \ 'num_instances should divide batch_size' if args.height is None or args.width is None: args.height, args.width = (144, 56) if args.arch == 'inception' else \ (256, 128) # get source data src_dataset, src_extfeat_loader = \ get_source_data(args.src_dataset, args.data_dir, args.height, args.width, args.batch_size, args.workers) # get target data tgt_dataset, num_classes, tgt_extfeat_loader, test_loader = \ get_data(args.tgt_dataset, args.data_dir, args.height, args.width, args.batch_size, args.workers) # Create model # Hacking here to let the classifier be the number of source ids if args.src_dataset == 'dukemtmc': model = models.create(args.arch, num_classes=632, pretrained=False) elif args.src_dataset == 'market1501': model = models.create(args.arch, num_classes=676, pretrained=False) else: raise RuntimeError( 'Please specify the number of classes (ids) of the network.') # Load from checkpoint if args.resume: print( 'Resuming checkpoints from finetuned model on another dataset...\n' ) checkpoint = load_checkpoint(args.resume) model.load_state_dict(checkpoint['state_dict'], strict=False) else: raise RuntimeWarning('Not using a pre-trained model.') model = nn.DataParallel(model).cuda() # Distance metric metric = DistanceMetric(algorithm=args.dist_metric) # Evaluator evaluator = Evaluator(model, print_freq=args.print_freq) print( "Test with the original model trained on target domain (direct transfer):" ) evaluator.evaluate(test_loader, tgt_dataset.query, tgt_dataset.gallery) if args.evaluate: return # Criterion criterion = [ TripletLoss(args.margin, args.num_instances).cuda(), TripletLoss(args.margin, args.num_instances).cuda(), ] # Optimizer optimizer = torch.optim.SGD( model.parameters(), lr=args.lr, momentum=0.9, ) # training stage transformer on input images normalizer = T.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) train_transformer = T.Compose([ T.Resize((args.height, args.width)), T.RandomHorizontalFlip(), T.ToTensor(), normalizer, T.RandomErasing(probability=0.5, sh=0.2, r1=0.3) ]) # Start training for iter_n in range(args.iteration): if args.lambda_value == 0: source_features = 0 else: # get source datas' feature source_features, _ = extract_features(model, src_extfeat_loader, print_freq=args.print_freq) # synchronization feature order with src_dataset.train source_features = torch.cat([ source_features[f].unsqueeze(0) for f, _, _ in src_dataset.train ], 0) # extract training images' features print('Iteration {}: Extracting Target Dataset Features...'.format( iter_n + 1)) target_features, _ = extract_features(model, tgt_extfeat_loader, print_freq=args.print_freq) # synchronization feature order with dataset.train target_features = torch.cat([ target_features[f].unsqueeze(0) for f, _, _ in tgt_dataset.trainval ], 0) # calculate distance and rerank result print('Calculating feature distances...') target_features = target_features.numpy() rerank_dist = re_ranking(source_features, target_features, lambda_value=args.lambda_value) if iter_n == 0: # DBSCAN cluster tri_mat = np.triu(rerank_dist, 1) # tri_mat.dim=2 tri_mat = tri_mat[np.nonzero(tri_mat)] # tri_mat.dim=1 tri_mat = np.sort(tri_mat, axis=None) top_num = np.round(args.rho * tri_mat.size).astype(int) eps = tri_mat[:top_num].mean() print('eps in cluster: {:.3f}'.format(eps)) cluster = DBSCAN(eps=eps, min_samples=4, metric='precomputed', n_jobs=8) # select & cluster images as training set of this epochs print('Clustering and labeling...') labels = cluster.fit_predict(rerank_dist) num_ids = len(set(labels)) - 1 print('Iteration {} have {} training ids'.format(iter_n + 1, num_ids)) # generate new dataset new_dataset = [] for (fname, _, _), label in zip(tgt_dataset.trainval, labels): if label == -1: continue # dont need to change codes in trainer.py _parsing_input function and sampler function after add 0 new_dataset.append((fname, label, 0)) print('Iteration {} have {} training images'.format( iter_n + 1, len(new_dataset))) train_loader = DataLoader(Preprocessor(new_dataset, root=tgt_dataset.images_dir, transform=train_transformer), batch_size=args.batch_size, num_workers=4, sampler=RandomIdentitySampler( new_dataset, args.num_instances), pin_memory=True, drop_last=True) # train model with new generated dataset trainer = Trainer(model, criterion, print_freq=args.print_freq) evaluator = Evaluator(model, print_freq=args.print_freq) # Start training for epoch in range(args.epochs): trainer.train(epoch, train_loader, optimizer) # Evaluate rank_score = evaluator.evaluate(test_loader, tgt_dataset.query, tgt_dataset.gallery) return (rank_score.map, rank_score.market1501[0])
def main(args): np.random.seed(args.seed) torch.manual_seed(args.seed) cudnn.benchmark = True # Create data loaders assert args.num_instances > 1, "num_instances should be greater than 1" assert args.batch_size % args.num_instances == 0, \ 'num_instances should divide batch_size' if args.height is None or args.width is None: args.height, args.width = (144, 56) if args.arch == 'inception' else \ (256, 128) # get source data src_dataset, src_extfeat_loader = \ get_source_data(args.src_dataset, args.data_dir, args.height, args.width, args.batch_size, args.workers) # get target data tgt_dataset, num_classes, tgt_extfeat_loader, test_loader = \ get_data(args.tgt_dataset, args.data_dir, args.height, args.width, args.batch_size, args.workers) # Create model # Hacking here to let the classifier be the number of source ids if args.src_dataset == 'dukemtmc': model = models.create(args.arch, num_classes=632, pretrained=False) elif args.src_dataset == 'market1501': model = models.create(args.arch, num_classes=676, pretrained=False) else: raise RuntimeError( 'Please specify the number of classes (ids) of the network.') # Load from checkpoint if args.resume: print( 'Resuming checkpoints from finetuned model on another dataset...\n' ) checkpoint = load_checkpoint(args.resume) model.load_state_dict(checkpoint['state_dict'], strict=False) else: raise RuntimeWarning('Not using a pre-trained model.') model = nn.DataParallel(model).cuda() # Distance metric # metric = DistanceMetric(algorithm=args.dist_metric) # Evaluator evaluator = Evaluator(model, print_freq=args.print_freq) print( "Test with the original model trained on source domain (direct transfer):" ) rank_score_best = evaluator.evaluate(test_loader, tgt_dataset.query, tgt_dataset.gallery) best_map = rank_score_best.map #market1501[0]-->rank-1 if args.evaluate: return # Criterion criterion = [ TripletLoss(args.margin, args.num_instances).cuda(), TripletLoss(args.margin, args.num_instances).cuda(), AccumulatedLoss(args.margin, args.num_instances).cuda(), nn.CrossEntropyLoss().cuda() ] # Optimizer optimizer = torch.optim.SGD( model.parameters(), lr=args.lr, momentum=0.9, ) # training stage transformer on input images normalizer = T.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) train_transformer = T.Compose([ T.Resize((args.height, args.width)), T.RandomHorizontalFlip(), T.ToTensor(), normalizer, T.RandomErasing(probability=0.5, sh=0.2, r1=0.3) ]) # Start training for iter_n in range(args.iteration): if args.lambda_value == 0: source_features = 0 #this value controls the usage of source data else: # get source datas' feature source_features, _ = extract_features(model, src_extfeat_loader, print_freq=args.print_freq) # synchronization feature order with src_dataset.train source_features = torch.cat([ source_features[f].unsqueeze(0) for f, _, _ in src_dataset.train ], 0) # extract training images' features print('Iteration {}: Extracting Target Dataset Features...'.format( iter_n + 1)) target_features, _ = extract_features(model, tgt_extfeat_loader, print_freq=args.print_freq) # synchronization feature order with dataset.train target_features = torch.cat([ target_features[f].unsqueeze(0) for f, _, _ in tgt_dataset.trainval ], 0) # calculate distance and rerank result print('Calculating feature distances...') target_features = target_features.numpy() rerank_dist = re_ranking(source_features, target_features, lambda_value=args.lambda_value) if iter_n == 0: # DBSCAN cluster tri_mat = np.triu(rerank_dist, 1) # tri_mat.dim=2 tri_mat = tri_mat[np.nonzero(tri_mat)] # tri_mat.dim=1 tri_mat = np.sort(tri_mat, axis=None) top_num = np.round(args.rho * tri_mat.size).astype(int) eps = tri_mat[:top_num].mean() print('eps in cluster: {:.3f}'.format(eps)) cluster = DBSCAN(eps=eps, min_samples=4, metric='precomputed', n_jobs=8) # HDBSCAN cluster import hdbscan cluster_hdbscan = hdbscan.HDBSCAN(min_cluster_size=10, min_samples=4, metric='precomputed') # select & cluster images as training set of this epochs print('Clustering and labeling...') if args.use_hdbscan_clustering: print( 'Use the better chlustering algorithm HDBSCAN for clustering' ) labels = cluster_hdbscan.fit_predict(rerank_dist) else: print('Use DBSCAN for clustering') labels = cluster.fit_predict(rerank_dist) num_ids = len(set(labels)) - 1 print('Only do once, Iteration {} have {} training ids'.format( iter_n + 1, num_ids)) # generate new dataset new_dataset = [] for (fname, _, _), label in zip(tgt_dataset.trainval, labels): if label == -1: continue # dont need to change codes in trainer.py _parsing_input function and sampler function after add 0 new_dataset.append((fname, label, 0)) print('Only do once, Iteration {} have {} training images'.format( iter_n + 1, len(new_dataset))) train_loader = DataLoader( Preprocessor_return_index(new_dataset, root=tgt_dataset.images_dir, transform=train_transformer), batch_size=args.batch_size, num_workers=4, sampler=RandomIdentitySampler(new_dataset, args.num_instances), pin_memory=True, drop_last=True) # init pseudo/fake labels, y_tilde in cvpr19's paper: new_label = np.zeros([len(new_dataset), num_ids]) # init y_tilde, let softmax(y_tilde) is noisy labels for index, (imgs, _, pids, _, index) in enumerate(train_loader): index = index.numpy() onehot = torch.zeros(pids.size(0), num_ids).scatter_(1, pids.view(-1, 1), 10.0) onehot = onehot.numpy() new_label[index, :] = onehot # Using clustered label to init the new classifier: classifier = nn.Linear(2048, num_ids, bias=False) classifier.apply(weights_init_classifier) classifier = nn.DataParallel(classifier).cuda() optimizer_cla = torch.optim.SGD(classifier.parameters(), lr=args.lr * 10, momentum=0.9) # train model with new generated dataset trainer = Trainer_with_learnable_label(model, classifier, criterion, print_freq=args.print_freq) evaluator = Evaluator(model, print_freq=args.print_freq) # Start training for epoch in range(args.epochs): trainer.train(epoch, train_loader, new_label, optimizer, optimizer_cla) # Evaluate rank_score = evaluator.evaluate(test_loader, tgt_dataset.query, tgt_dataset.gallery) #Save the best ckpt: rank1 = rank_score.market1501[0] mAP = rank_score.map is_best_mAP = mAP > best_map best_map = max(mAP, best_map) save_checkpoint( { 'state_dict': model.module.state_dict(), 'epoch': iter_n + 1, 'best_mAP': best_map, # 'num_ids': num_ids, }, is_best_mAP, fpath=osp.join(args.logs_dir, 'checkpoint.pth.tar')) print( '\n * Finished epoch {:3d} top1: {:5.1%} mAP: {:5.1%} best_mAP: {:5.1%}{}\n' .format(iter_n + 1, rank1, mAP, best_map, ' *' if is_best_mAP else '')) return (rank_score.map, rank_score.market1501[0])
def main(args): np.random.seed(args.seed) torch.manual_seed(args.seed) cudnn.benchmark = True # Create data loaders assert args.num_instances > 1, "num_instances should be greater than 1" assert args.batch_size % args.num_instances == 0, \ 'num_instances should divide batch_size' if args.height is None or args.width is None: args.height, args.width = (144, 56) if args.arch == 'inception' else \ (256, 128) # get source data src_dataset, src_extfeat_loader = \ get_source_data(args.src_dataset, args.data_dir, args.height, args.width, args.batch_size, args.workers) # get target data tgt_dataset, num_classes, tgt_extfeat_loader, test_loader = \ get_data(args.tgt_dataset, args.data_dir, args.height, args.width, args.batch_size, args.workers) # Create model # Hacking here to let the classifier be the number of source ids if args.src_dataset == 'dukemtmc': model = models.create(args.arch, num_classes=632, pretrained=False) elif args.src_dataset == 'market1501': model = models.create(args.arch, num_classes=676, pretrained=False) else: raise RuntimeError( 'Please specify the number of classes (ids) of the network.') # Load from checkpoint if args.resume: print( 'Resuming checkpoints from finetuned model on another dataset...\n' ) checkpoint = load_checkpoint(args.resume) model.load_state_dict(checkpoint['state_dict'], strict=False) else: raise RuntimeWarning('Not using a pre-trained model.') model = nn.DataParallel(model).cuda() # Criterion criterion = [ TripletLoss(args.margin, args.num_instances, use_semi=False).cuda(), TripletLoss(args.margin, args.num_instances, use_semi=False).cuda() ] optimizer = torch.optim.Adam(model.parameters(), lr=args.lr) # training stage transformer on input images normalizer = T.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) train_transformer = T.Compose([ T.Resize((args.height, args.width)), T.RandomHorizontalFlip(), T.ToTensor(), normalizer, T.RandomErasing(probability=0.5, sh=0.2, r1=0.3) ]) # # Start training for iter_n in range(args.iteration): if args.lambda_value == 0: source_features = 0 else: # get source datas' feature source_features, _ = extract_features(model, src_extfeat_loader, print_freq=args.print_freq) # synchronization feature order with src_dataset.train source_features = torch.cat([ source_features[f].unsqueeze(0) for f, _, _ in src_dataset.train ], 0) # extract training images' features print('Iteration {}: Extracting Target Dataset Features...'.format( iter_n + 1)) target_features, _ = extract_features(model, tgt_extfeat_loader, print_freq=args.print_freq) # synchronization feature order with dataset.train target_features = torch.cat([ target_features[f].unsqueeze(0) for f, _, _ in tgt_dataset.trainval ], 0) # calculate distance and rerank result print('Calculating feature distances...') target_features = target_features.numpy() rerank_dist = re_ranking(source_features, target_features, lambda_value=args.lambda_value) if iter_n == 0: # DBSCAN cluster tri_mat = np.triu(rerank_dist, 1) # tri_mat.dim=2 tri_mat = tri_mat[np.nonzero(tri_mat)] # tri_mat.dim=1 tri_mat = np.sort(tri_mat, axis=None) top_num = np.round(args.rho * tri_mat.size).astype(int) eps = tri_mat[:top_num].mean() print('eps in cluster: {:.3f}'.format(eps)) cluster = DBSCAN(eps=eps, min_samples=4, metric='precomputed', n_jobs=8) # select & cluster images as training set of this epochs print('Clustering and labeling...') labels = cluster.fit_predict(rerank_dist) num_ids = len(set(labels)) - 1 print('Iteration {} have {} training ids'.format(iter_n + 1, num_ids)) # generate new dataset new_dataset = [] # assign label for target ones newLab = labelNoise(torch.from_numpy(target_features), torch.from_numpy(labels)) # unknownFeats = target_features[labels==-1,:] counter = 0 from collections import defaultdict realIDs, fakeIDs = defaultdict(list), [] for (fname, realID, cam), label in zip(tgt_dataset.trainval, newLab): # dont need to change codes in trainer.py _parsing_input function and sampler function after add 0 new_dataset.append((fname, label, cam)) realIDs[realID].append(counter) fakeIDs.append(label) counter += 1 precision, recall, fscore = calScores(realIDs, np.asarray(fakeIDs)) print('Iteration {} have {} training images'.format( iter_n + 1, len(new_dataset))) print( f'precision:{precision * 100}, recall:{100 * recall}, fscore:{fscore}' ) train_loader = DataLoader(Preprocessor(new_dataset, root=tgt_dataset.images_dir, transform=train_transformer), batch_size=args.batch_size, num_workers=4, sampler=RandomIdentitySampler( new_dataset, args.num_instances), pin_memory=True, drop_last=True) trainer = Trainer(model, criterion) # Start training for epoch in range(args.epochs): trainer.train(epoch, train_loader, optimizer) # to at most 80% # test only evaluator = Evaluator(model, print_freq=args.print_freq) # rank_score = evaluator.evaluate(test_loader, tgt_dataset.query, tgt_dataset.gallery) # Evaluate rank_score = evaluator.evaluate(test_loader, tgt_dataset.query, tgt_dataset.gallery) save_checkpoint( { 'state_dict': model.module.state_dict(), 'epoch': epoch + 1, 'best_top1': rank_score.market1501[0], }, True, fpath=osp.join(args.logs_dir, 'adapted.pth.tar')) return rank_score.map, rank_score.market1501[0]
def main(args): np.random.seed(args.seed) torch.manual_seed(args.seed) cudnn.benchmark = True # Create data loaders assert args.num_instances > 1, "num_instances should be greater than 1" assert args.batch_size % args.num_instances == 0, \ 'num_instances should divide batch_size' if args.height is None or args.width is None: args.height, args.width = (144, 56) if args.arch == 'inception' else \ (256, 128) # get source data src_dataset, src_extfeat_loader = \ get_source_data(args.src_dataset, args.data_dir, args.height, args.width, args.batch_size, args.workers) # get target data tgt_dataset, num_classes, tgt_extfeat_loader, test_loader = \ get_data(args.tgt_dataset, args.data_dir, args.height, args.width, args.batch_size, args.workers) # Create model # Hacking here to let the classifier be the number of source ids if args.src_dataset == 'dukemtmc': model = models.create(args.arch, num_classes=632, pretrained=False) coModel = models.create(args.arch, num_classes=632, pretrained=False) elif args.src_dataset == 'market1501': model = models.create(args.arch, num_classes=676, pretrained=False) coModel = models.create(args.arch, num_classes=676, pretrained=False) else: raise RuntimeError( 'Please specify the number of classes (ids) of the network.') # Load from checkpoint if args.resume: print( 'Resuming checkpoints from finetuned model on another dataset...\n' ) checkpoint = load_checkpoint(args.resume) model.load_state_dict(checkpoint['state_dict'], strict=False) coModel.load_state_dict(checkpoint['state_dict'], strict=False) else: raise RuntimeWarning('Not using a pre-trained model.') model = nn.DataParallel(model).cuda() coModel = nn.DataParallel(coModel).cuda() # evaluator.evaluate(test_loader, tgt_dataset.query, tgt_dataset.gallery) # if args.evaluate: return # Criterion criterion = [ TripletLoss(args.margin, args.num_instances, isAvg=False, use_semi=False).cuda(), TripletLoss(args.margin, args.num_instances, isAvg=False, use_semi=False).cuda(), ] # Optimizer optimizer = torch.optim.Adam(model.parameters(), lr=args.lr) coOptimizer = torch.optim.Adam(coModel.parameters(), lr=args.lr) optims = [optimizer, coOptimizer] # training stage transformer on input images normalizer = T.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) train_transformer = T.Compose([ T.Resize((args.height, args.width)), T.RandomHorizontalFlip(), T.ToTensor(), normalizer, T.RandomErasing(probability=0.5, sh=0.2, r1=0.3) ]) # # Start training for iter_n in range(args.iteration): if args.lambda_value == 0: source_features = 0 else: # get source datas' feature source_features, _ = extract_features(model, src_extfeat_loader, print_freq=args.print_freq) # synchronization feature order with src_dataset.train source_features = torch.cat([ source_features[f].unsqueeze(0) for f, _, _ in src_dataset.train ], 0) # extract training images' features print('Iteration {}: Extracting Target Dataset Features...'.format( iter_n + 1)) target_features, tarNames = extract_features( model, tgt_extfeat_loader, print_freq=args.print_freq) # synchronization feature order with dataset.train target_features = torch.cat([ target_features[f].unsqueeze(0) for f, _, _ in tgt_dataset.trainval ], 0) target_real_label = np.asarray( [tarNames[f].unsqueeze(0) for f, _, _ in tgt_dataset.trainval]) numTarID = len(set(target_real_label)) # calculate distance and rerank result print('Calculating feature distances...') target_features = target_features.numpy() cluster = KMeans(n_clusters=numTarID, n_jobs=8, n_init=1) # select & cluster images as training set of this epochs print('Clustering and labeling...') clusterRes = cluster.fit(target_features) labels, centers = clusterRes.labels_, clusterRes.cluster_centers_ labels = splitLowconfi(target_features, labels, centers) # num_ids = len(set(labels)) # print('Iteration {} have {} training ids'.format(iter_n+1, num_ids)) # generate new dataset new_dataset, unknown_dataset = [], [] # assign label for target ones unknownLab = labelNoise(torch.from_numpy(target_features), torch.from_numpy(labels)) # unknownFeats = target_features[labels==-1,:] unCounter = 0 for (fname, _, cam), label in zip(tgt_dataset.trainval, labels): if label == -1: unknown_dataset.append( (fname, int(unknownLab[unCounter]), cam)) # unknown data unCounter += 1 continue # dont need to change codes in trainer.py _parsing_input function and sampler function after add 0 new_dataset.append((fname, label, cam)) print('Iteration {} have {} training images'.format( iter_n + 1, len(new_dataset))) train_loader = DataLoader(Preprocessor(new_dataset, root=tgt_dataset.images_dir, transform=train_transformer), batch_size=args.batch_size, num_workers=4, sampler=RandomIdentitySampler( new_dataset, args.num_instances), pin_memory=True, drop_last=True) # hard samples unLoader = DataLoader(Preprocessor(unknown_dataset, root=tgt_dataset.images_dir, transform=train_transformer), batch_size=args.batch_size, num_workers=4, sampler=RandomIdentitySampler( unknown_dataset, args.num_instances), pin_memory=True, drop_last=True) # train model with new generated dataset trainer = CoTrainerAsy(model, coModel, train_loader, unLoader, criterion, optims) # trainer = CoTeaching( # model, coModel, train_loader, unLoader, criterion, optims # ) # trainer = CoTrainerAsySep( # model, coModel, train_loader, unLoader, criterion, optims # ) evaluator = Evaluator(model, print_freq=args.print_freq) #evaluatorB = Evaluator(coModel, print_freq=args.print_freq) # Start training for epoch in range(args.epochs): trainer.train(epoch, remRate=0.2 + (0.6 / args.iteration) * (1 + iter_n)) # to at most 80% # trainer.train(epoch, remRate=0.7+(0.3/args.iteration)*(1+iter_n)) # test only rank_score = evaluator.evaluate(test_loader, tgt_dataset.query, tgt_dataset.gallery) #print('co-model:\n') #rank_score = evaluatorB.evaluate(test_loader, tgt_dataset.query, tgt_dataset.gallery) # Evaluate rank_score = evaluator.evaluate(test_loader, tgt_dataset.query, tgt_dataset.gallery) save_checkpoint( { 'state_dict': model.module.state_dict(), 'epoch': epoch + 1, 'best_top1': rank_score.market1501[0], }, True, fpath=osp.join(args.logs_dir, 'adapted.pth.tar')) return (rank_score.map, rank_score.market1501[0])
def get_data(data_dir, source, target, height, width, batch_size, re=0, workers=8): dataset = DA(data_dir, source, target) dataset_2 = DA(data_dir, target, source) normalizer = T.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) num_classes = dataset.num_train_ids train_transformer = T.Compose([ T.Resize((height, width), interpolation=3), T.RandomHorizontalFlip(p=0.5), T.Pad(10), T.RandomCrop((height, width)), T.ToTensor(), normalizer, # T.RandomErasing(EPSILON=re), T.RandomErasing(probability=0.4, mean=[0.485, 0.456, 0.406]) ]) train_transformer_2 = T.Compose([ T.Resize((height, width), interpolation=3), T.RandomHorizontalFlip(p=0.5), T.Pad(10), T.RandomCrop((height, width)), T.ToTensor(), normalizer, # T.RandomErasing(EPSILON=re), T.RandomErasing(probability=0.4, mean=[0.485, 0.456, 0.406]) ]) test_transformer = T.Compose([ T.Resize((height, width), interpolation=3), T.ToTensor(), normalizer, ]) ''' num_instances=4 rmgs_flag = num_instances > 0 if rmgs_flag: sampler = RandomIdentitySampler(dataset.target_train, num_instances) else: sampler = None ''' source_train_loader = DataLoader( Preprocessor(dataset.source_train, root=osp.join(dataset.source_images_dir, dataset.source_train_path), transform=train_transformer), batch_size=batch_size, num_workers=workers, shuffle=True, pin_memory=True, drop_last=True) num_instances=0 rmgs_flag = num_instances > 0 if rmgs_flag: sampler = RandomIdentitySampler(dataset.target_train, num_instances) else: sampler = None target_train_loader = DataLoader( UnsupervisedCamStylePreprocessor(dataset.target_train, root=osp.join(dataset.target_images_dir, dataset.target_train_path), camstyle_root=osp.join(dataset.target_images_dir, dataset.target_train_camstyle_path), num_cam=dataset.target_num_cam, transform=train_transformer), batch_size=batch_size, num_workers=workers, shuffle=True, pin_memory=True, drop_last=True) query_loader = DataLoader( Preprocessor(dataset.query, root=osp.join(dataset.target_images_dir, dataset.query_path), transform=test_transformer), batch_size=batch_size, num_workers=workers, shuffle=False, pin_memory=True) query_loader_2 = DataLoader( Preprocessor(dataset_2.query, root=osp.join(dataset_2.target_images_dir, dataset_2.query_path), transform=test_transformer), batch_size=batch_size, num_workers=workers, shuffle=False, pin_memory=True) gallery_loader = DataLoader( Preprocessor(dataset.gallery, root=osp.join(dataset.target_images_dir, dataset.gallery_path), transform=test_transformer), batch_size=batch_size, num_workers=workers, shuffle=False, pin_memory=True) gallery_loader_2 = DataLoader( Preprocessor(dataset_2.gallery, root=osp.join(dataset_2.target_images_dir, dataset_2.gallery_path), transform=test_transformer), batch_size=batch_size, num_workers=workers, shuffle=False, pin_memory=True) return dataset,dataset_2, num_classes, source_train_loader, target_train_loader, query_loader, gallery_loader, query_loader_2, gallery_loader_2
def main(args): np.random.seed(args.seed) torch.manual_seed(args.seed) cudnn.benchmark = True # Create data loaders assert args.num_instances > 1, "num_instances should be greater than 1" assert args.batch_size % args.num_instances == 0, \ 'num_instances should divide batch_size' if args.height is None or args.width is None: args.height, args.width = (144, 56) if args.arch == 'inception' else \ (256, 128) # get source data src_dataset, src_extfeat_loader = \ get_source_data(args.src_dataset, args.data_dir, args.height, args.width, args.batch_size, args.workers) # get target data tgt_dataset, num_classes, tgt_extfeat_loader, test_loader = \ get_data(args.tgt_dataset, args.data_dir, args.height, args.width, args.batch_size, args.workers) # Create model # Hacking here to let the classifier be the number of source ids if args.src_dataset == 'dukemtmc': model = models.create(args.arch, num_classes=632, pretrained=False) elif args.src_dataset == 'market1501': model = models.create(args.arch, num_classes=676, pretrained=False) else: raise RuntimeError( 'Please specify the number of classes (ids) of the network.') # Load from checkpoint if args.resume: print( 'Resuming checkpoints from finetuned model on another dataset...\n' ) checkpoint = load_checkpoint(args.resume) model.load_state_dict(checkpoint['state_dict'], strict=False) else: raise RuntimeWarning('Not using a pre-trained model.') model = nn.DataParallel(model).cuda() # evaluator.evaluate(test_loader, tgt_dataset.query, tgt_dataset.gallery) # if args.evaluate: return # Criterion criterion = [ TripletLoss(args.margin, args.num_instances, isAvg=True, use_semi=True).cuda(), TripletLoss(args.margin, args.num_instances, isAvg=True, use_semi=True).cuda(), None, None ] # Optimizer optimizer = torch.optim.Adam(model.parameters(), lr=args.lr) # training stage transformer on input images normalizer = T.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) train_transformer = T.Compose([ T.Resize((args.height, args.width)), T.RandomHorizontalFlip(), T.ToTensor(), normalizer, T.RandomErasing(probability=0.5, sh=0.2, r1=0.3) ]) evaluator = Evaluator(model, print_freq=args.print_freq) evaluator.evaluate(test_loader, tgt_dataset.query, tgt_dataset.gallery) # # Start training for iter_n in range(args.iteration): if args.lambda_value == 0: source_features = 0 else: # get source datas' feature source_features, _ = extract_features(model, src_extfeat_loader, print_freq=args.print_freq) # synchronization feature order with src_dataset.train source_features = torch.cat([ source_features[f].unsqueeze(0) for f, _, _, _ in src_dataset.train ], 0) # extract training images' features print('Iteration {}: Extracting Target Dataset Features...'.format( iter_n + 1)) target_features, tarNames = extract_features( model, tgt_extfeat_loader, print_freq=args.print_freq) # synchronization feature order with dataset.train target_features = torch.cat([ target_features[f].unsqueeze(0) for f, _, _, _ in tgt_dataset.trainval ], 0) # target_real_label = np.asarray([tarNames[f].unsqueeze(0) for f, _, _, _ in tgt_dataset.trainval]) # calculate distance and rerank result # method 1 target_features = target_features.numpy() rerank_dist = re_ranking(source_features, target_features, lambda_value=args.lambda_value) # method 2 # distmat_qq = calDis(source_features, source_features) # distmat_qg = calDis(source_features, target_features) # distmat_gg = calDis(target_features, target_features) # rerank_dist = re_ranking2(distmat_qg.numpy(), distmat_qq.numpy(), distmat_gg.numpy()) cluster = HDBSCAN(metric='precomputed', min_samples=10) # select & cluster images as training set of this epochs clusterRes = cluster.fit(rerank_dist) labels, label_num = clusterRes.labels_, clusterRes.labels_.max() + 1 centers = np.zeros((label_num, target_features.shape[1])) nums = [0] * target_features.shape[1] print('clusters num =', label_num) # generate new dataset new_dataset = [] index = -1 for (fname, _, cam, timestamp), label in zip(tgt_dataset.trainval, labels): index += 1 if label == -1: continue # dont need to change codes in trainer.py _parsing_input function and sampler function after add 0 new_dataset.append((fname, label, cam, timestamp)) centers[label] += target_features[index] nums[label] += 1 print('Iteration {} have {} training images'.format( iter_n + 1, len(new_dataset))) train_loader = DataLoader(Preprocessor(new_dataset, root=tgt_dataset.images_dir, transform=train_transformer), batch_size=args.batch_size, num_workers=4, sampler=RandomIdentitySampler( new_dataset, args.num_instances), pin_memory=True, drop_last=True) for i in range(label_num): centers[i] /= nums[i] criterion[3] = ClassificationLoss(normalize(centers, axis=1)).cuda() classOptimizer = torch.optim.Adam( [{ 'params': model.parameters() }, { 'params': criterion[3].classifier.parameters(), 'lr': 1e-3 }], lr=args.lr) class_trainer = ClassificationTrainer(model, train_loader, criterion, classOptimizer) for epoch in range(args.epochs): class_trainer.train(epoch) rank_score = evaluator.evaluate(test_loader, tgt_dataset.query, tgt_dataset.gallery) # Evaluate rank_score = evaluator.evaluate(test_loader, tgt_dataset.query, tgt_dataset.gallery) save_checkpoint( { 'state_dict': model.module.state_dict(), 'epoch': epoch + 1, 'best_top1': rank_score.market1501[0], }, True, fpath=osp.join(args.logs_dir, 'adapted.pth.tar')) return (rank_score.map, rank_score.market1501[0])
def get_data(name, data_dir, height, width, batch_size, workers, combine_trainval, crop, tracking_icams, fps, re=0, num_instances=0, camstyle=0, zju=0, colorjitter=0): # if name == 'market1501': # root = osp.join(data_dir, 'Market-1501-v15.09.15') # elif name == 'duke_reid': # root = osp.join(data_dir, 'DukeMTMC-reID') # elif name == 'duke_tracking': # root = osp.join(data_dir, 'DukeMTMC') # else: # root = osp.join(data_dir, name) if name == 'duke_tracking': if tracking_icams != 0: tracking_icams = [tracking_icams] else: tracking_icams = list(range(1, 9)) dataset = datasets.create(name, data_dir, data_type='tracking_gt', iCams=tracking_icams, fps=fps, trainval=combine_trainval) elif name == 'aic_tracking': dataset = datasets.create(name, data_dir, data_type='tracking_gt', fps=fps, trainval=combine_trainval) else: dataset = datasets.create(name, data_dir) normalizer = T.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) num_classes = dataset.num_train_ids train_transformer = T.Compose([ T.ColorJitter(brightness=0.1 * colorjitter, contrast=0.1 * colorjitter, saturation=0.1 * colorjitter, hue=0), T.Resize((height, width)), T.RandomHorizontalFlip(), T.Pad(10 * crop), T.RandomCrop((height, width)), T.ToTensor(), normalizer, T.RandomErasing(probability=re), ]) test_transformer = T.Compose([ T.Resize((height, width)), # T.RectScale(height, width, interpolation=3), T.ToTensor(), normalizer, ]) if zju: train_loader = DataLoader( Preprocessor(dataset.train, root=dataset.train_path, transform=train_transformer), batch_size=batch_size, num_workers=workers, sampler=ZJU_RandomIdentitySampler(dataset.train, batch_size, num_instances) if num_instances else None, shuffle=False if num_instances else True, pin_memory=True, drop_last=False if num_instances else True) else: train_loader = DataLoader( Preprocessor(dataset.train, root=dataset.train_path, transform=train_transformer), batch_size=batch_size, num_workers=workers, sampler=RandomIdentitySampler(dataset.train, num_instances) if num_instances else None, shuffle=False if num_instances else True, pin_memory=True, drop_last=True) query_loader = DataLoader( Preprocessor(dataset.query, root=dataset.query_path, transform=test_transformer), batch_size=batch_size, num_workers=workers, shuffle=False, pin_memory=True) gallery_loader = DataLoader( Preprocessor(dataset.gallery, root=dataset.gallery_path, transform=test_transformer), batch_size=batch_size, num_workers=workers, shuffle=False, pin_memory=True) if camstyle <= 0: camstyle_loader = None else: camstyle_loader = DataLoader( Preprocessor(dataset.camstyle, root=dataset.camstyle_path, transform=train_transformer), batch_size=camstyle, num_workers=workers, shuffle=True, pin_memory=True, drop_last=True) return dataset, num_classes, train_loader, query_loader, gallery_loader, camstyle_loader
def main(args): np.random.seed(args.seed) torch.manual_seed(args.seed) cudnn.benchmark = True # Create data loaders assert args.num_instances > 1, "num_instances should be greater than 1" assert args.batch_size % args.num_instances == 0, \ 'num_instances should divide batch_size' if args.height is None or args.width is None: args.height, args.width = (144, 56) if args.arch == 'inception' else \ (256, 128) # get source data src_dataset, src_extfeat_loader = \ get_source_data(args.src_dataset, args.data_dir, args.height, args.width, args.batch_size, args.workers) # get target data tgt_dataset, num_classes, tgt_extfeat_loader, test_loader = \ get_data(args.tgt_dataset, args.data_dir, args.height, args.width, args.batch_size, args.workers) # Create model # Hacking here to let the classifier be the number of source ids if args.src_dataset == 'dukemtmc': model = models.create(args.arch, num_classes=632, pretrained=False) elif args.src_dataset == 'market1501': model = models.create(args.arch, num_classes=676, pretrained=False) elif args.src_dataset == 'msmt17': model = models.create(args.arch, num_classes=1041, pretrained=False) elif args.src_dataset == 'cuhk03': model = models.create(args.arch, num_classes=1230, pretrained=False) else: raise RuntimeError( 'Please specify the number of classes (ids) of the network.') # Load from checkpoint if args.resume: print( 'Resuming checkpoints from finetuned model on another dataset...\n' ) checkpoint = load_checkpoint(args.resume) model.load_state_dict(checkpoint['state_dict'], strict=False) else: raise RuntimeWarning('Not using a pre-trained model.') model = nn.DataParallel(model).cuda() evaluator = Evaluator(model, print_freq=args.print_freq) evaluator.evaluate(test_loader, tgt_dataset.query, tgt_dataset.gallery) # if args.evaluate: return # Criterion criterion = [ HoughTripletLoss(args.margin, args.num_instances, isAvg=False, use_semi=False).cuda(), HoughTripletLoss(args.margin, args.num_instances, isAvg=False, use_semi=False).cuda() ] # Optimizer optimizer = torch.optim.Adam(model.parameters(), lr=args.lr) # training stage transformer on input images normalizer = T.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) train_transformer = T.Compose([ T.Resize((args.height, args.width)), T.RandomHorizontalFlip(), T.ToTensor(), normalizer, T.RandomErasing(probability=0.5, sh=0.2, r1=0.3) ]) # # Start training for iter_n in range(args.iteration): if args.lambda_value == 0: source_features = 0 else: # get source datas' feature source_features, _ = extract_features(model, src_extfeat_loader, print_freq=args.print_freq) # synchronization feature order with src_dataset.train source_features = torch.cat([ source_features[f].unsqueeze(0) for f, _, _, _ in src_dataset.train ], 0) # extract training images' features print('Iteration {}: Extracting Target Dataset Features...'.format( iter_n + 1)) target_features, _ = extract_features(model, tgt_extfeat_loader, print_freq=args.print_freq) # synchronization feature order with dataset.train target_features = torch.cat([ target_features[f].unsqueeze(0) for f, _, _, _ in tgt_dataset.trainval ], 0) # calculate distance and rerank result print('Calculating feature distances...') target_features = target_features.numpy() rerank_dist = re_ranking(source_features, target_features, lambda_value=args.lambda_value) if iter_n == 0: # DBSCAN cluster tri_mat = np.triu(rerank_dist, 1) # tri_mat.dim=2 tri_mat = tri_mat[np.nonzero(tri_mat)] # tri_mat.dim=1 tri_mat = np.sort(tri_mat, axis=None) top_num = np.round(args.rho * tri_mat.size).astype(int) eps = tri_mat[:top_num].mean() print('eps in cluster: {:.3f}'.format(eps)) cluster = DBSCAN(eps=eps, min_samples=4, metric='precomputed', n_jobs=8) # select & cluster images as training set of this epochs print('Clustering and labeling...') labels = cluster.fit_predict(rerank_dist) num_ids = len(set(labels)) - 1 print('Iteration {} have {} training ids'.format(iter_n + 1, num_ids)) # generate new dataset new_dataset, unknown_dataset = [], [] # assign label for target ones unknownLab = labelNoise(torch.from_numpy(target_features), torch.from_numpy(labels)) # unknownFeats = target_features[labels==-1,:] unCounter, index = 0, 0 from collections import defaultdict realIDs, fakeIDs = defaultdict(list), [] record_labels = {} hough = Hough(8, 40, 230, 2935, 25, args.short_cut) for (fname, realPID, cam, timestamp), label in zip(tgt_dataset.trainval, labels): if label == -1: unknown_dataset.append((fname, int(unknownLab[unCounter]), cam, timestamp)) # unknown data fakeIDs.append(int(unknownLab[unCounter])) realIDs[realPID].append(index) unCounter += 1 index += 1 continue # dont need to change codes in trainer.py _parsing_input function and sampler function after add 0 if label not in record_labels: record_labels[label] = [] for index2 in record_labels[label]: hough.update(cam, tgt_dataset.trainval[index2][2], timestamp, tgt_dataset.trainval[index2][3]) record_labels[label].append(index) new_dataset.append((fname, label, cam, timestamp)) fakeIDs.append(label) realIDs[realPID].append(index) index += 1 print('Iteration {} have {} training images'.format( iter_n + 1, len(new_dataset))) precision, recall, fscore = calScores( realIDs, np.asarray(fakeIDs)) # fakeIDs does not contain -1 print('precision:{}, recall:{}, fscore: {}'.format( 100 * precision, 100 * recall, fscore)) T_pseu, TP_pseu, T_gt, TP_gt, index = (0, 0, 0, 0, -1) for (fname, realPID, cam, timestamp), label in zip(tgt_dataset.trainval, labels): index += 1 # calc by gt label T_gt = T_gt + len(realIDs[realPID]) - 1 for index2 in realIDs[realPID]: if index2 == index: continue if hough.on_peak(cam, tgt_dataset.trainval[index2][2], timestamp, tgt_dataset.trainval[index2][3]): TP_gt += 1 # calc by pseudo label if label == -1: continue T_pseu = T_pseu + len(record_labels[label]) - 1 for index2 in record_labels[label]: if index2 == index: continue if hough.on_peak(cam, tgt_dataset.trainval[index2][2], timestamp, tgt_dataset.trainval[index2][3]): TP_pseu += 1 print('gt label: T = %d, TP = %d, recall = %f' % (T_gt, TP_gt, TP_pseu / T_gt)) print('pseudo label: T = %d, TP = %d, recall = %f' % (T_pseu, TP_pseu, TP_pseu / T_pseu)) train_loader = DataLoader(Preprocessor(new_dataset, root=tgt_dataset.images_dir, transform=train_transformer), batch_size=args.batch_size, num_workers=4, sampler=RandomIdentitySampler( new_dataset, args.num_instances), pin_memory=True, drop_last=True) # hard samples # noiseImgs = [name[1] for name in unknown_dataset] # saveAll(noiseImgs, tgt_dataset.images_dir, 'noiseImg') # import ipdb; ipdb.set_trace() unLoader = DataLoader(Preprocessor(unknown_dataset, root=tgt_dataset.images_dir, transform=train_transformer), batch_size=args.batch_size, num_workers=4, sampler=RandomIdentitySampler( unknown_dataset, args.num_instances), pin_memory=True, drop_last=True) # train model with new generated dataset trainer1 = HoughTrainer(model, hough, train_loader, criterion, optimizer) trainer2 = HoughTrainer(model, hough, unLoader, criterion, optimizer) # Start training for epoch in range(args.epochs): trainer1.train(epoch) trainer2.train(epoch) # test only rank_score = evaluator.evaluate(test_loader, tgt_dataset.query, tgt_dataset.gallery) # print('co-model:\n') # rank_score = evaluatorB.evaluate(test_loader, tgt_dataset.query, tgt_dataset.gallery) # Evaluate rank_score = evaluator.evaluate(test_loader, tgt_dataset.query, tgt_dataset.gallery) save_checkpoint( { 'state_dict': model.module.state_dict(), 'epoch': epoch + 1, 'best_top1': rank_score.market1501[0], }, True, fpath=osp.join(args.logs_dir, 'asyCo.pth')) return rank_score.map, rank_score.market1501[0]
def update_train_loader(dataset, train_samples, updated_label, height, width, batch_size, re, workers, all_img_cams, sample_position=7): normalizer = T.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) train_transformer = T.Compose([ T.Resize((height, width), interpolation=3), T.RandomHorizontalFlip(p=0.5), T.Pad(10), T.RandomCrop((height, width)), T.ToTensor(), normalizer, T.RandomErasing(EPSILON=re) ]) # obtain global accumulated label from pseudo label and cameras pure_label = updated_label[updated_label >= 0] pure_cams = all_img_cams[updated_label >= 0] accumulate_labels = np.zeros(pure_label.shape, pure_label.dtype) prev_id_count = 0 id_count_each_cam = [] for this_cam in np.unique(pure_cams): percam_labels = pure_label[pure_cams == this_cam] unique_id = np.unique(percam_labels) id_count_each_cam.append(len(unique_id)) id_dict = {ID: i for i, ID in enumerate(unique_id.tolist())} for i in range(len(percam_labels)): percam_labels[i] = id_dict[percam_labels[i]] accumulate_labels[pure_cams == this_cam] = percam_labels + prev_id_count prev_id_count += len(unique_id) print(' sum(id_count_each_cam)= {}'.format(sum(id_count_each_cam))) new_accum_labels = -1 * np.ones(updated_label.shape, updated_label.dtype) new_accum_labels[updated_label >= 0] = accumulate_labels # update sample list new_train_samples = [] for sample in train_samples: lbl = updated_label[sample[3]] if lbl != -1: assert (new_accum_labels[sample[3]] >= 0) new_sample = sample + (lbl, new_accum_labels[sample[3]]) new_train_samples.append(new_sample) target_train_loader = DataLoader(UnsupervisedTargetPreprocessor( new_train_samples, root=osp.join(dataset.target_images_dir, dataset.target_train_path), num_cam=dataset.target_num_cam, transform=train_transformer, has_pseudo_label=True), batch_size=batch_size, num_workers=workers, pin_memory=True, drop_last=True, sampler=ClassUniformlySampler( new_train_samples, class_position=sample_position, k=4)) return target_train_loader, len(new_train_samples)
def main(args): np.random.seed(args.seed) torch.manual_seed(args.seed) cudnn.benchmark = True # Redirect print to both console and log file sys.stdout = Logger(osp.join(args.logs_dir, 'log.txt')) print(args) shutil.copy(sys.argv[0], osp.join(args.logs_dir, osp.basename(sys.argv[0]))) # Create data loaders if args.height is None or args.width is None: args.height, args.width = (256, 128) dataset, num_classes, train_loader, val_loader, test_loader = \ get_data(args.dataset, args.split, args.data_dir, args.height, args.width, args.batch_size * 8, args.workers, ) # Create model model = models.create("ft_net_inter", num_classes=num_classes, stride=args.stride) # Load from checkpoint start_epoch = 0 best_top1 = 0 top1 = 0 is_best = False if args.checkpoint is not None: if args.evaluate: checkpoint = load_checkpoint(args.checkpoint) param_dict = model.state_dict() for k, v in checkpoint['state_dict'].items(): if 'model' in k: param_dict[k] = v model.load_state_dict(param_dict) else: model.model.load_param(args.checkpoint) model = model.cuda() # Distance metric metric = None # Evaluator evaluator = Evaluator(model, use_cpu=args.use_cpu) if args.evaluate: print("Test:") evaluator.evaluate(test_loader, dataset.query, dataset.gallery, metric) return train_transformer = [ T.Resize((args.height, args.width), interpolation=3), T.RandomHorizontalFlip(), T.Pad(10), T.RandomCrop((args.height, args.width)), T.ToTensor(), T.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]), T.RandomErasing(probability=0.5), ] train_transformer = T.Compose(train_transformer) for cluster_epoch in range(args.cluster_epochs): # -------------------------Stage 1 intra camera training-------------------------- # Cluster and generate new dataset and model cluster_result = get_intra_cam_cluster_result(model, train_loader, args.class_number_stage1, args.linkage) cluster_datasets = [ datasets.create("cluster", osp.join(args.data_dir, args.dataset), cluster_result[cam_id], cam_id) for cam_id in cluster_result.keys() ] cluster_dataloaders = [ DataLoader(Preprocessor(dataset.train_set, root=dataset.images_dir, transform=train_transformer), batch_size=args.batch_size, num_workers=args.workers, shuffle=True, pin_memory=False, drop_last=True) for dataset in cluster_datasets ] param_dict = model.model.state_dict() model = models.create("ft_net_intra", num_classes=[ args.class_number_stage1 for cam_id in cluster_result.keys() ], stride=args.stride) model_param_dict = model.model.state_dict() for k, v in model_param_dict.items(): if k in param_dict.keys(): model_param_dict[k] = param_dict[k] model.model.load_state_dict(model_param_dict) model = model.cuda() criterion = nn.CrossEntropyLoss().cuda() # Optimizer param_groups = make_params(model, args.lr, args.weight_decay) optimizer = torch.optim.SGD(param_groups, momentum=0.9) # Trainer trainer = IntraCameraTrainer(model, criterion, warm_up_epoch=args.warm_up) print("start training") # Start training for epoch in range(0, args.epochs_stage1): trainer.train( cluster_epoch, epoch, cluster_dataloaders, optimizer, print_freq=args.print_freq, ) # -------------------------------------------Stage 2 inter camera training----------------------------------- mix_rate = get_mix_rate(args.mix_rate, cluster_epoch, args.cluster_epochs, power=args.decay_factor) cluster_result = get_inter_cam_cluster_result(model, train_loader, args.class_number_stage2, args.linkage, mix_rate, use_cpu=args.use_cpu) cluster_dataset = datasets.create( "cluster", osp.join(args.data_dir, args.dataset), cluster_result, 0) cluster_dataloaders = DataLoader( Preprocessor(cluster_dataset.train_set, root=cluster_dataset.images_dir, transform=train_transformer), batch_size=args.batch_size_stage2, num_workers=args.workers, sampler=RandomIdentitySampler(cluster_dataset.train_set, args.batch_size_stage2, args.instances), pin_memory=False, drop_last=True) param_dict = model.model.state_dict() model = models.create("ft_net_inter", num_classes=args.class_number_stage2, stride=args.stride) model.model.load_state_dict(param_dict) model = model.cuda() # Criterion criterion_entropy = nn.CrossEntropyLoss().cuda() criterion_triple = TripletLoss(margin=args.margin).cuda() # Optimizer param_groups = make_params(model, args.lr * args.batch_size_stage2 / 32, args.weight_decay) optimizer = torch.optim.SGD(param_groups, momentum=0.9) # Trainer trainer = InterCameraTrainer( model, criterion_entropy, criterion_triple, warm_up_epoch=args.warm_up, ) print("start training") # Start training for epoch in range(0, args.epochs_stage2): trainer.train(cluster_epoch, epoch, cluster_dataloaders, optimizer, print_freq=args.print_freq) if (cluster_epoch + 1) % 5 == 0: evaluator = Evaluator(model, use_cpu=args.use_cpu) top1, mAP = evaluator.evaluate(test_loader, dataset.query, dataset.gallery, metric, return_mAP=True) is_best = top1 > best_top1 best_top1 = max(top1, best_top1) save_checkpoint( { 'state_dict': model.state_dict(), 'epoch': cluster_epoch + 1, 'best_top1': best_top1, 'cluster_epoch': cluster_epoch + 1, }, is_best, fpath=osp.join(args.logs_dir, 'checkpoint.pth.tar')) if cluster_epoch == (args.cluster_epochs - 1): save_checkpoint( { 'state_dict': model.state_dict(), 'epoch': cluster_epoch + 1, 'best_top1': best_top1, 'cluster_epoch': cluster_epoch + 1, }, False, fpath=osp.join(args.logs_dir, 'latest.pth.tar')) print('\n * cluster_epoch: {:3d} top1: {:5.1%} best: {:5.1%}{}\n'. format(cluster_epoch, top1, best_top1, ' *' if is_best else '')) # Final test print('Test with best model:') checkpoint = load_checkpoint(osp.join(args.logs_dir, 'model_best.pth.tar')) model.load_state_dict(checkpoint['state_dict']) best_rank1, mAP = evaluator.evaluate(test_loader, dataset.query, dataset.gallery, metric, return_mAP=True)
def main(args): np.random.seed(args.seed) # With the seed reset (every time), the same set of numbers will appear every time. torch.manual_seed(args.seed) # Sets the seed for generating random numbers. cudnn.benchmark = True # This flag allows you to enable the inbuilt cudnn auto-tuner to find the best algorithm to use for your hardware. It enables benchmark mode in cudnn. # Redirect print to both console and log file sys.stdout = Logger(osp.join(args.logs_dir, 'log.txt')) print(args) shutil.copy(sys.argv[0], osp.join(args.logs_dir, osp.basename(sys.argv[0]))) # Create data loaders if args.height is None or args.width is None: args.height, args.width = (256, 128) dataset, num_classes, train_loader, val_loader, test_loader = \ get_data(args.dataset, args.split, args.data_dir, args.height, args.width, args.batch_size * 8, args.workers, #https://deeplizard.com/learn/video/kWVgvsejXsE#:~:text=The%20num_workers%20attribute%20tells%20the,sequentially%20inside%20the%20main%20process. ) # Create model model = models.create("ft_net_inter", num_classes=num_classes, stride=args.stride) # Load from checkpoint start_epoch = 0 best_top1 = 0 top1 = 0 is_best = False if args.checkpoint is not None: if args.evaluate: checkpoint = load_checkpoint(args.checkpoint) param_dict = model.state_dict() # A state_dict is simply a Python dictionary object that maps each layer to its parameter tensor. for k, v in checkpoint['state_dict'].items(): if 'model' in k: param_dict[k] = v model.load_state_dict(param_dict) else: model.model.load_param(args.checkpoint) model = model.cuda() # Distance metric metric = None # Evaluator evaluator = Evaluator(model, use_cpu=args.use_cpu) if args.evaluate: print("Test:") evaluator.evaluate(test_loader, dataset.query, dataset.gallery, metric) return train_transformer = [ T.Resize((args.height, args.width), interpolation=3), T.RandomHorizontalFlip(), T.Pad(10), T.RandomCrop((args.height, args.width)), T.ToTensor(), T.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]), T.RandomErasing(probability=0.5), ] train_transformer = T.Compose(train_transformer) for cluster_epoch in range(args.cluster_epochs): # -------------------------Stage 1 intra camera training-------------------------- # Cluster and generate new dataset and model # Divides the training set into (subsets) and according to that each camera id is there for each image # then it forms clustering on each subset according to the pair wise similarity # then assigning images with in each cluster with identical label # then cross entropy loss is used cluster_result = get_intra_cam_cluster_result(model, train_loader, args.class_number_stage1, args.linkage) cluster_datasets = [ datasets.create("cluster", osp.join(args.data_dir, args.dataset), cluster_result[cam_id], cam_id) for cam_id in cluster_result.keys() ] cluster_dataloaders = [ DataLoader(Preprocessor(dataset.train_set, root=dataset.images_dir, transform=train_transformer), batch_size=args.batch_size, num_workers=args.workers, shuffle=True, pin_memory=False, drop_last=True) for dataset in cluster_datasets ] param_dict = model.model.state_dict() model = models.create("ft_net_intra", num_classes=[ args.class_number_stage1 for cam_id in cluster_result.keys() ], stride=args.stride) model_param_dict = model.model.state_dict() for k, v in model_param_dict.items(): if k in param_dict.keys(): model_param_dict[k] = param_dict[k] model.model.load_state_dict(model_param_dict) model = model.cuda() criterion = nn.CrossEntropyLoss().cuda() # Optimizer param_groups = make_params(model, args.lr, args.weight_decay) optimizer = torch.optim.SGD(param_groups, momentum=0.9) # Trainer trainer = IntraCameraTrainer( model, criterion, warm_up_epoch=args.warm_up) print("start training") # Start training for epoch in range(0, args.epochs_stage1): trainer.train(cluster_epoch, epoch, cluster_dataloaders, optimizer, print_freq=args.print_freq, ) # -------------------------------------------Stage 2 inter camera training----------------------------------- mix_rate = get_mix_rate( args.mix_rate, cluster_epoch, args.cluster_epochs, power=args.decay_factor) cluster_result = get_inter_cam_cluster_result( model, train_loader, args.class_number_stage2, args.linkage, mix_rate, use_cpu=args.use_cpu) cluster_dataset = datasets.create( "cluster", osp.join(args.data_dir, args.dataset), cluster_result, 0) cluster_dataloaders = DataLoader( Preprocessor(cluster_dataset.train_set, root=cluster_dataset.images_dir, transform=train_transformer), batch_size=args.batch_size_stage2, num_workers=args.workers, sampler=RandomIdentitySampler(cluster_dataset.train_set, args.batch_size_stage2, args.instances), pin_memory=False, drop_last=True) param_dict = model.model.state_dict() model = models.create("ft_net_inter", num_classes=args.class_number_stage2, stride=args.stride) model.model.load_state_dict(param_dict) model = model.cuda() # Criterion criterion_entropy = nn.CrossEntropyLoss().cuda() criterion_triple = TripletLoss(margin=args.margin).cuda() # Optimizer param_groups = make_params(model, args.lr * args.batch_size_stage2 / 32, args.weight_decay) optimizer = torch.optim.SGD(param_groups, momentum=0.9) # Trainer trainer = InterCameraTrainer(model, criterion_entropy, criterion_triple, warm_up_epoch=args.warm_up, ) print("start training") # Start training for epoch in range(0, args.epochs_stage2): trainer.train(cluster_epoch, epoch, cluster_dataloaders, optimizer, print_freq=args.print_freq) if (cluster_epoch + 1) % 5 == 0: # in 4th, 9th, 14th epochs, see in the output evaluator = Evaluator(model, use_cpu=args.use_cpu) top1, mAP = evaluator.evaluate( test_loader, dataset.query, dataset.gallery, metric, return_mAP=True) is_best = top1 > best_top1 best_top1 = max(top1, best_top1) save_checkpoint( { 'state_dict': model.state_dict(), 'epoch': cluster_epoch + 1, 'best_top1': best_top1, 'cluster_epoch': cluster_epoch + 1, }, is_best, fpath=osp.join(args.logs_dir, 'checkpoint.pth.tar')) if cluster_epoch == (args.cluster_epochs - 1): save_checkpoint( { 'state_dict': model.state_dict(), 'epoch': cluster_epoch + 1, 'best_top1': best_top1, 'cluster_epoch': cluster_epoch + 1, }, False, fpath=osp.join(args.logs_dir, 'latest.pth.tar')) print('\n * cluster_epoch: {:3d} top1: {:5.1%} best: {:5.1%}{}\n'. format(cluster_epoch, top1, best_top1, ' *' if is_best else '')) # Final test print('Test with best model:') checkpoint = load_checkpoint(osp.join(args.logs_dir, 'model_best.pth.tar')) model.load_state_dict(checkpoint['state_dict']) best_rank1, mAP = evaluator.evaluate( test_loader, dataset.query, dataset.gallery, metric, return_mAP=True)