### Install Torchreid via Bash Source: https://github.com/kaiyangzhou/deep-person-reid/blob/master/README.rst Instructions for cloning the repository, setting up a Conda environment, and installing necessary dependencies including PyTorch and the library itself. ```bash git clone https://github.com/KaiyangZhou/deep-person-reid.git cd deep-person-reid/ conda create --name torchreid python=3.7 conda activate torchreid pip install -r requirements.txt conda install pytorch torchvision cudatoolkit=9.0 -c pytorch python setup.py develop ``` -------------------------------- ### Train and Evaluate Models via CLI Source: https://github.com/kaiyangzhou/deep-person-reid/blob/master/README.rst Provides command-line examples for training OSNet models on different datasets and performing cross-domain evaluation. These scripts utilize configuration files to manage model architecture, transforms, and data paths. ```bash # Train on Market1501 python scripts/main.py \ --config-file configs/im_osnet_x1_0_softmax_256x128_amsgrad_cosine.yaml \ --transforms random_flip random_erase \ --root $PATH_TO_DATA # Train on DukeMTMC-reID python scripts/main.py \ --config-file configs/im_osnet_x1_0_softmax_256x128_amsgrad_cosine.yaml \ -s dukemtmcreid \ -t dukemtmcreid \ --transforms random_flip random_erase \ --root $PATH_TO_DATA \ data.save_dir log/osnet_x1_0_dukemtmcreid_softmax_cosinelr # Evaluate existing model python scripts/main.py \ --config-file configs/im_osnet_x1_0_softmax_256x128_amsgrad_cosine.yaml \ --root $PATH_TO_DATA \ model.load_weights log/osnet_x1_0_market1501_softmax_cosinelr/model.pth.tar-250 \ test.evaluate True # Cross-domain training (Source: Duke, Target: Market) python scripts/main.py \ --config-file configs/im_osnet_x1_0_softmax_256x128_amsgrad.yaml \ -s dukemtmcreid \ -t market1501 \ --transforms random_flip color_jitter \ --root $PATH_TO_DATA ``` -------------------------------- ### Initialize and Run Training Engine Source: https://github.com/kaiyangzhou/deep-person-reid/blob/master/README.rst Demonstrates how to instantiate a PyTorch engine for image-based softmax training and execute the training loop with specific hyperparameters. ```python engine = torchreid.engine.ImageSoftmaxEngine( datamanager, model, optimizer=optimizer, scheduler=scheduler, label_smooth=True ) engine.run( save_dir="log/resnet50", max_epoch=60, eval_freq=10, print_freq=10, test_only=False ) ``` -------------------------------- ### Initialize Torchreid Data Manager and Model Source: https://github.com/kaiyangzhou/deep-person-reid/blob/master/README.rst Basic workflow to import the library, configure the ImageDataManager for training, and build a ResNet50 model with an Adam optimizer. ```python import torchreid datamanager = torchreid.data.ImageDataManager( root="reid-data", sources="market1501", targets="market1501", height=256, width=128, batch_size_train=32, batch_size_test=100, transforms=["random_flip", "random_crop"] ) model = torchreid.models.build_model( name="resnet50", num_classes=datamanager.num_train_pids, loss="softmax", pretrained=True ) model = model.cuda() optimizer = torchreid.optim.build_optimizer( model, optim="adam", lr=0.0003 ) scheduler = torchreid.optim.build_lr_scheduler(optimizer, lr_scheduler="single_step", stepsize=20) ``` -------------------------------- ### Configure Staged Learning Rates in PyTorch Source: https://github.com/kaiyangzhou/deep-person-reid/blob/master/docs/user_guide.rst Demonstrates how to apply different learning rates to base layers and newly initialized layers in a model using torchreid.optim.build_optimizer. ```python optimizer = torchreid.optim.build_optimizer( model, optim='sgd', lr=0.01, staged_lr=True, new_layers='classifier', base_lr_mult=0.1 ) ``` -------------------------------- ### Run GNN Re-Ranking Demo Source: https://github.com/kaiyangzhou/deep-person-reid/blob/master/torchreid/utils/GPU-Re-Ranking/README.md This snippet demonstrates how to run the GNN re-ranking method using the 'main.py' script. It requires specifying the path to the data and setting re-ranking parameters k1 and k2. This script facilitates real-time post-processing for image retrieval. ```shell python main.py --data_path PATH_TO_DATA --k1 26 --k2 7 ``` -------------------------------- ### Visualize Activation Maps via CLI Source: https://github.com/kaiyangzhou/deep-person-reid/blob/master/docs/user_guide.rst Runs the activation map visualization tool to inspect CNN feature focus areas for a specific model and dataset. ```shell python tools/visualize_actmap.py \ --root $DATA/reid \ -d market1501 \ -m osnet_x1_0 \ --weights PATH_TO_PRETRAINED_WEIGHTS \ --save-dir log/visactmap_osnet_x1_0_market1501 ``` -------------------------------- ### Register and Initialize Custom Datasets Source: https://github.com/kaiyangzhou/deep-person-reid/blob/master/docs/user_guide.rst Instructions for registering a custom dataset class with the torchreid registry and initializing the ImageDataManager to handle data loading and cross-dataset evaluation. ```python import torchreid # Register the dataset torchreid.data.register_image_dataset('new_dataset', NewDataset) # Initialize data manager datamanager = torchreid.data.ImageDataManager( root='reid-data', sources=['new_dataset', 'dukemtmcreid'], targets='market1501' ) ``` -------------------------------- ### Configure and Run Model Training in Torchreid Source: https://context7.com/kaiyangzhou/deep-person-reid/llms.txt This snippet demonstrates how to initialize the training engine with specific hyperparameters. It includes settings for epoch duration, evaluation frequency, and layer-specific training configurations. ```python engine.run( save_dir='log/resnet50-twostep', max_epoch=60, eval_freq=10, fixbase_epoch=5, open_layers='classifier' ) ``` -------------------------------- ### Instantiate Models with build_model Source: https://context7.com/kaiyangzhou/deep-person-reid/llms.txt Provides utility functions to list available architectures and build specific models with pretrained weights and custom loss configurations. ```python import torchreid # List all available models torchreid.models.show_avai_models() # Build OSNet model for softmax classification model = torchreid.models.build_model( name='osnet_x1_0', num_classes=751, loss='softmax', pretrained=True, use_gpu=True ) model = model.cuda() ``` -------------------------------- ### Compile Extension Code Source: https://github.com/kaiyangzhou/deep-person-reid/blob/master/torchreid/utils/GPU-Re-Ranking/README.md This snippet shows how to compile the extension code for the GNN re-ranking method. It requires navigating to the 'extension' directory and executing the 'make.sh' script. This is a prerequisite for running the demo. ```shell cd extension sh make.sh ``` -------------------------------- ### Execute End-to-End Training Pipeline Source: https://context7.com/kaiyangzhou/deep-person-reid/llms.txt Demonstrates the 5-step workflow to train a re-ID model. This includes initializing the data manager, building the model architecture, configuring the optimizer and scheduler, and running the training engine. ```python import torchreid # Step 1: Load data manager with source and target datasets datamanager = torchreid.data.ImageDataManager( root="reid-data", sources="market1501", targets="market1501", height=256, width=128, batch_size_train=32, batch_size_test=100, transforms=["random_flip", "random_crop"] ) # Step 2: Build the model (OSNet, ResNet, etc.) model = torchreid.models.build_model( name="osnet_x1_0", num_classes=datamanager.num_train_pids, loss="softmax", pretrained=True ) model = model.cuda() # Step 3: Build optimizer with optional staged learning rates optimizer = torchreid.optim.build_optimizer( model, optim="adam", lr=0.0003 ) # Step 4: Build learning rate scheduler scheduler = torchreid.optim.build_lr_scheduler( optimizer, lr_scheduler="single_step", stepsize=20 ) # Step 5: Create engine and run training engine = torchreid.engine.ImageSoftmaxEngine( datamanager, model, optimizer=optimizer, scheduler=scheduler, label_smooth=True ) engine.run( save_dir="log/osnet_x1_0", max_epoch=60, eval_freq=10, print_freq=10, test_only=False ) ``` -------------------------------- ### Build Learning Rate Scheduler (PyTorch) Source: https://context7.com/kaiyangzhou/deep-person-reid/llms.txt Creates learning rate schedulers for training, supporting step decay and cosine annealing strategies. Integrates with optimizers to adjust learning rates over epochs. ```python import torchreid model = torchreid.models.build_model(name='resnet50', num_classes=751) optimizer = torchreid.optim.build_optimizer(model, optim='adam', lr=0.0003) # Single step decay: reduce LR by gamma every stepsize epochs scheduler = torchreid.optim.build_lr_scheduler( optimizer, lr_scheduler='single_step', stepsize=20, gamma=0.1 ) # Multi-step decay: reduce LR at specific epochs scheduler = torchreid.optim.build_lr_scheduler( optimizer, lr_scheduler='multi_step', stepsize=[30, 50, 55], gamma=0.1 ) # Cosine annealing schedule scheduler = torchreid.optim.build_lr_scheduler( optimizer, lr_scheduler='cosine', max_epoch=60 ) ``` -------------------------------- ### Command-Line Training and Evaluation with PyTorchReID Source: https://context7.com/kaiyangzhou/deep-person-reid/llms.txt Utilizes the `scripts/main.py` script for training and evaluating person re-identification models. Supports various configurations, data sources, transformations, and testing scenarios, including cross-domain training. Requires specifying a config file, data root, and optionally source/target datasets and save directories. ```bash # Train OSNet on Market1501 with default config python scripts/main.py \ --config-file configs/im_osnet_x1_0_softmax_256x128_amsgrad_cosine.yaml \ --transforms random_flip random_erase \ --root $PATH_TO_DATA # Train on DukeMTMC-reID python scripts/main.py \ --config-file configs/im_osnet_x1_0_softmax_256x128_amsgrad_cosine.yaml \ -s dukemtmcreid \ -t dukemtmcreid \ --transforms random_flip random_erase \ --root $PATH_TO_DATA \ data.save_dir log/osnet_x1_0_dukemtmcreid # Cross-domain training: train on Duke, test on Market python scripts/main.py \ --config-file configs/im_osnet_x1_0_softmax_256x128_amsgrad.yaml \ -s dukemtmcreid \ -t market1501 \ --transforms random_flip color_jitter \ --root $PATH_TO_DATA # Test only with pretrained weights python scripts/main.py \ --config-file configs/im_osnet_x1_0_softmax_256x128_amsgrad_cosine.yaml \ --root $PATH_TO_DATA \ model.load_weights log/osnet_x1_0/model.pth.tar-250 \ test.evaluate True # Visualize with TensorBoard after training tensorboard --logdir=log/osnet_x1_0 ``` -------------------------------- ### Build Optimizer with Staged Learning Rates (PyTorch) Source: https://context7.com/kaiyangzhou/deep-person-reid/llms.txt Creates optimizers with support for staged learning rates, allowing different learning rates for pretrained and newly initialized layers. Supports Adam, SGD, and other optimizers. ```python import torchreid model = torchreid.models.build_model( name='resnet50', num_classes=751, loss='softmax' ) # Basic Adam optimizer optimizer = torchreid.optim.build_optimizer( model, optim='adam', lr=0.0003, weight_decay=5e-04 ) # SGD with momentum optimizer = torchreid.optim.build_optimizer( model, optim='sgd', lr=0.01, momentum=0.9, weight_decay=5e-04 ) # Staged learning rates: smaller LR for pretrained layers optimizer = torchreid.optim.build_optimizer( model, optim='adam', lr=0.01, staged_lr=True, new_layers='classifier', # New layer uses lr=0.01 base_lr_mult=0.1 # Base layers use lr=0.001 ) ``` -------------------------------- ### Create Custom Dataset Class for Torchreid Source: https://github.com/kaiyangzhou/deep-person-reid/blob/master/docs/user_guide.rst Template for implementing a custom dataset class by inheriting from ImageDataset. Requires defining train, query, and gallery lists containing tuples of (image_path, pid, camid). ```python from __future__ import absolute_import from __future__ import print_function from __future__ import division import sys import os import os.path as osp from torchreid.data import ImageDataset class NewDataset(ImageDataset): dataset_dir = 'new_dataset' def __init__(self, root='', **kwargs): self.root = osp.abspath(osp.expanduser(root)) self.dataset_dir = osp.join(self.root, self.dataset_dir) train = [] query = [] gallery = [] super(NewDataset, self).__init__(train, query, gallery, **kwargs) ``` -------------------------------- ### ImageTripletEngine for Person Re-ID Training (PyTorch) Source: https://context7.com/kaiyangzhou/deep-person-reid/llms.txt Trains person re-identification models using triplet loss combined with cross-entropy loss. Requires identity-based sampling for effective hard mining. ```python import torchreid datamanager = torchreid.data.ImageDataManager( root='path/to/reid-data', sources='market1501', height=256, width=128, batch_size_train=32, batch_size_test=100, num_instances=4, # Images per identity in batch train_sampler='RandomIdentitySampler' # Required for triplet loss ) model = torchreid.models.build_model( name='resnet50', num_classes=datamanager.num_train_pids, loss='triplet' # Model returns (logits, features) ) model = model.cuda() optimizer = torchreid.optim.build_optimizer(model, optim='adam', lr=0.0003) scheduler = torchreid.optim.build_lr_scheduler(optimizer, lr_scheduler='single_step', stepsize=20) engine = torchreid.engine.ImageTripletEngine( datamanager, model, optimizer=optimizer, scheduler=scheduler, margin=0.3, # Triplet loss margin weight_t=0.7, # Weight for triplet loss weight_x=1.0, # Weight for cross-entropy loss label_smooth=True ) engine.run( save_dir='log/resnet50-triplet-market1501', max_epoch=60, print_freq=10, eval_freq=10 ) ``` -------------------------------- ### Register and Use Custom Datasets in PyTorchReID Source: https://context7.com/kaiyangzhou/deep-person-reid/llms.txt Demonstrates how to create a custom dataset by extending `ImageDataset` and registering it with the PyTorchReID data module. This allows for the use of custom datasets in training and evaluation pipelines. The dataset should provide training, query, and gallery splits, with each entry formatted as (image_path, person_id, camera_id). ```python from torchreid.data import ImageDataset import torchreid import os.path as osp class MyCustomDataset(ImageDataset): dataset_dir = 'my_custom_dataset' def __init__(self, root='', **kwargs): self.root = osp.abspath(osp.expanduser(root)) self.dataset_dir = osp.join(self.root, self.dataset_dir) # Each tuple: (image_path, person_id, camera_id) # PIDs and CAMIDs should be 0-based integers train = [ ('path/to/img1.jpg', 0, 0), ('path/to/img2.jpg', 0, 1), ('path/to/img3.jpg', 1, 0), ] query = [ ('path/to/query1.jpg', 0, 0), ('path/to/query2.jpg', 1, 1), ] gallery = [ ('path/to/gallery1.jpg', 0, 1), ('path/to/gallery2.jpg', 1, 0), ] super(MyCustomDataset, self).__init__(train, query, gallery, **kwargs) # Register the custom dataset torchreid.data.register_image_dataset('my_custom_dataset', MyCustomDataset) # Use the custom dataset datamanager = torchreid.data.ImageDataManager( root='reid-data', sources='my_custom_dataset', targets='my_custom_dataset', height=256, width=128, batch_size_train=32 ) ``` -------------------------------- ### Execute Two-Stepped Transfer Learning Source: https://github.com/kaiyangzhou/deep-person-reid/blob/master/docs/user_guide.rst Configures the engine to freeze base layers for a specified number of epochs while training new layers, preventing damage from initial gradients. ```python engine.run( save_dir='log/resnet50', max_epoch=60, eval_freq=10, print_freq=10, test_only=False, fixbase_epoch=5, open_layers='classifier' ) ``` -------------------------------- ### torchreid.data.sampler Source: https://github.com/kaiyangzhou/deep-person-reid/blob/master/docs/pkg/data.rst Contains various sampling strategies for creating batches of data, crucial for effective training of person re-identification models. ```APIDOC ## torchreid.data.sampler ### Description Implements different samplers to control how data is sampled and batched during training. This includes strategies like random sampling, identity-based sampling, and hard-negative mining. ### Method N/A (This is a module description, not an endpoint) ### Endpoint N/A ### Parameters N/A ### Request Example N/A ### Response N/A ``` -------------------------------- ### ImageSoftmaxEngine for Person Re-ID Training (PyTorch) Source: https://context7.com/kaiyangzhou/deep-person-reid/llms.txt Trains person re-identification models using softmax loss with optional label smoothing. Handles data loading, model training, and evaluation. ```python import torchreid datamanager = torchreid.data.ImageDataManager( root='path/to/reid-data', sources='market1501', height=256, width=128, batch_size_train=32, batch_size_test=100 ) model = torchreid.models.build_model( name='resnet50', num_classes=datamanager.num_train_pids, loss='softmax' ) model = model.cuda() optimizer = torchreid.optim.build_optimizer(model, optim='adam', lr=0.0003) scheduler = torchreid.optim.build_lr_scheduler(optimizer, lr_scheduler='single_step', stepsize=20) engine = torchreid.engine.ImageSoftmaxEngine( datamanager, model, optimizer=optimizer, scheduler=scheduler, use_gpu=True, label_smooth=True ) # Run training with periodic evaluation engine.run( save_dir='log/resnet50-softmax-market1501', max_epoch=60, start_epoch=0, print_freq=10, eval_freq=10, test_only=False, dist_metric='euclidean', normalize_feature=False, visrank=False, ranks=[1, 5, 10, 20] ) ``` -------------------------------- ### Manage Model Checkpoints Source: https://context7.com/kaiyangzhou/deep-person-reid/llms.txt Utility functions to save, load, and resume model training states. Includes support for loading pre-trained weights into model architectures. ```python from torchreid.utils import save_checkpoint, load_checkpoint, load_pretrained_weights, resume_from_checkpoint import torchreid # Save save_checkpoint({'state_dict': model.state_dict()}, 'log/my_model', is_best=True) # Load model = torchreid.models.build_model(name='osnet_x1_0', num_classes=751) load_pretrained_weights(model, 'path/to/pretrained_model.pth.tar') # Resume start_epoch = resume_from_checkpoint('log/my_model/model.pth.tar-30', model) ``` -------------------------------- ### Build ResNet50 for Triplet Loss (PyTorch) Source: https://context7.com/kaiyangzhou/deep-person-reid/llms.txt Builds a ResNet50 model configured for triplet loss, outputting both features and logits. Supports various model architectures and loss functions. ```python import torchreid model = torchreid.models.build_model( name='resnet50', num_classes=751, loss='triplet', pretrained=True ) ``` -------------------------------- ### Video Datasets Source: https://github.com/kaiyangzhou/deep-person-reid/blob/master/docs/pkg/data.rst Provides implementations for various standard video-based person re-identification datasets. ```APIDOC ## Video Datasets ### Description This section details the specific implementations for several widely used video-based person re-identification datasets. Each dataset module provides the necessary classes and functions to load and process the respective dataset. ### Supported Datasets - MARS - iLIDS-VID - PRID 2011 - DukeMTMC-vidreid ### Method N/A (These are dataset modules, not endpoints) ### Endpoint N/A ### Parameters N/A ### Request Example N/A ### Response N/A ``` -------------------------------- ### Export PyTorchReID Models to ONNX, OpenVINO, TFLite Source: https://context7.com/kaiyangzhou/deep-person-reid/llms.txt Provides a script `tools/export.py` to convert trained PyTorchReID models into formats suitable for deployment on various inference frameworks. Supports ONNX, OpenVINO, and TFLite formats, with options for dynamic input shapes and image resizing. Requires specifying the path to the trained weights. ```bash # Export model to ONNX format python tools/export.py \ --weights path/to/osnet_x1_0_model.pth.tar \ --include onnx \ --dynamic \ --imgsz 256 128 # Export to OpenVINO format python tools/export.py \ --weights path/to/model.pth.tar \ --include openvino \ --dynamic # Export to TFLite format python tools/export.py \ --weights path/to/model.pth.tar \ --include tflite # Export to all formats python tools/export.py \ --weights path/to/mobilenetv2_x1_0_model.pth.tar \ --include onnx openvino tflite \ --dynamic \ --imgsz 256 128 ``` -------------------------------- ### Image Datasets Source: https://github.com/kaiyangzhou/deep-person-reid/blob/master/docs/pkg/data.rst Provides implementations for various standard image-based person re-identification datasets. ```APIDOC ## Image Datasets ### Description This section details the specific implementations for several widely used image-based person re-identification datasets. Each dataset module provides the necessary classes and functions to load and process the respective dataset. ### Supported Datasets - Market-1501 - CUHK03 - DukeMTMC-reID - MSMT17 - VIPeR - GRID - CUHK01 - iLIDS - SenseReID - PRID ### Method N/A (These are dataset modules, not endpoints) ### Endpoint N/A ### Parameters N/A ### Request Example N/A ### Response N/A ``` -------------------------------- ### torchreid.data.datamanager Source: https://github.com/kaiyangzhou/deep-person-reid/blob/master/docs/pkg/data.rst Provides the DataManager class for handling dataset loading, batching, and distribution for person re-identification tasks. ```APIDOC ## torchreid.data.datamanager ### Description Manages the loading, preprocessing, and batching of data for person re-identification models. It supports various dataset types and sampling strategies. ### Method N/A (This is a module description, not an endpoint) ### Endpoint N/A ### Parameters N/A ### Request Example N/A ### Response N/A ``` -------------------------------- ### Train DML Model for Person Re-ID (Bash) Source: https://github.com/kaiyangzhou/deep-person-reid/blob/master/projects/DML/README.md This command initiates the training process for a person re-identification model using Deep Mutual Learning (DML) with the OSNet architecture. It requires a configuration file and the path to the dataset. ```bash python main.py \ --config-file im_osnet_x1_0_dml_256x128_amsgrad_cosine.yaml \ --root $DATA ``` -------------------------------- ### Extract Features using FeatureExtractor API Source: https://github.com/kaiyangzhou/deep-person-reid/blob/master/docs/user_guide.rst Demonstrates how to use the FeatureExtractor class to generate embeddings from a list of image paths using a pre-trained model. ```python from torchreid.utils import FeatureExtractor extractor = FeatureExtractor( model_name='osnet_x1_0', model_path='a/b/c/model.pth.tar', device='cuda' ) image_list = ['a/b/c/image001.jpg', 'a/b/c/image002.jpg'] features = extractor(image_list) print(features.shape) ``` -------------------------------- ### Manage Video Datasets with VideoDataManager Source: https://context7.com/kaiyangzhou/deep-person-reid/llms.txt Handles loading and temporal sampling for video-based re-ID datasets. Allows configuration of sequence length and frame sampling methods. ```python import torchreid datamanager = torchreid.data.VideoDataManager( root='path/to/reid-data', sources='mars', targets='mars', height=256, width=128, batch_size_train=3, batch_size_test=3, seq_len=15, sample_method='evenly', transforms=['random_flip'] ) # Access train and test loaders train_loader = datamanager.train_loader test_loader = datamanager.test_loader ``` -------------------------------- ### Manage Image Datasets with ImageDataManager Source: https://context7.com/kaiyangzhou/deep-person-reid/llms.txt Configures data loading, preprocessing, and augmentation for image-based re-ID. Supports single or multi-dataset training and cross-domain evaluation. ```python import torchreid # Basic usage with single dataset datamanager = torchreid.data.ImageDataManager( root='path/to/reid-data', sources='market1501', height=256, width=128, batch_size_train=32, batch_size_test=100 ) # Multi-dataset training with cross-domain evaluation datamanager = torchreid.data.ImageDataManager( root='reid-data', sources=['market1501', 'dukemtmcreid', 'cuhk03'], targets=['msmt17'], height=256, width=128, batch_size_train=32, batch_size_test=100, transforms=['random_flip', 'random_erase', 'color_jitter'], combineall=True ) # Access data loaders train_loader = datamanager.train_loader test_loader = datamanager.test_loader print(f"Number of training identities: {datamanager.num_train_pids}") # Fetch query and gallery loaders for specific dataset query_loader, gallery_loader = datamanager.fetch_test_loaders('market1501') ``` -------------------------------- ### torchreid.data.datasets.dataset Source: https://github.com/kaiyangzhou/deep-person-reid/blob/master/docs/pkg/data.rst Base dataset class providing a common interface for all dataset implementations within the library. ```APIDOC ## torchreid.data.datasets.dataset ### Description Defines the abstract base class for all datasets. It outlines the expected methods and structure for custom dataset implementations, ensuring consistency across different data sources. ### Method N/A (This is a module description, not an endpoint) ### Endpoint N/A ### Parameters N/A ### Request Example N/A ### Response N/A ``` -------------------------------- ### Two-Stepped Transfer Learning in PyTorchReID Source: https://context7.com/kaiyangzhou/deep-person-reid/llms.txt Implements a two-stepped transfer learning approach for training person re-identification models. This method involves first training only the classification layer while keeping the base model frozen, followed by fine-tuning all layers. It requires setting up a `ImageDataManager`, building a model, optimizer, and learning rate scheduler, then using an `ImageSoftmaxEngine`. ```python import torchreid datamanager = torchreid.data.ImageDataManager( root='reid-data', sources='market1501', height=256, width=128, batch_size_train=32 ) model = torchreid.models.build_model( name='resnet50', num_classes=datamanager.num_train_pids, loss='softmax', pretrained=True ) model = model.cuda() optimizer = torchreid.optim.build_optimizer(model, optim='sgd', lr=0.01) scheduler = torchreid.optim.build_lr_scheduler(optimizer, lr_scheduler='single_step', stepsize=20) engine = torchreid.engine.ImageSoftmaxEngine( datamanager, model, optimizer=optimizer, scheduler=scheduler ) # Two-stepped training: # - First 5 epochs: only train 'classifier' layer (base frozen) ``` -------------------------------- ### Compute Distance Matrix Source: https://context7.com/kaiyangzhou/deep-person-reid/llms.txt Calculates pairwise distances between query and gallery feature tensors. Supports euclidean and cosine metrics to determine similarity between image embeddings. ```python import torch from torchreid import metrics query_features = torch.rand(10, 512) gallery_features = torch.rand(100, 512) distmat = metrics.compute_distance_matrix( query_features, gallery_features, metric='euclidean' ) top_k_indices = distmat.argsort(dim=1)[:, :10] ``` -------------------------------- ### Evaluate Rank Metrics Source: https://context7.com/kaiyangzhou/deep-person-reid/llms.txt Computes Cumulative Matching Characteristics (CMC) and mean Average Precision (mAP) for re-identification model evaluation. Requires distance matrices and ground truth identity/camera labels. ```python from torchreid.metrics import evaluate_rank import numpy as np distmat = np.random.rand(100, 500) q_pids = np.array([0, 0, 1, 1, 2]) g_pids = np.array([0, 1, 2, 3, 4]) q_camids = np.array([0, 1, 0, 1, 0]) g_camids = np.array([0, 0, 1, 1, 1]) cmc, mAP = evaluate_rank(distmat, q_pids, g_pids, q_camids, g_camids) ``` -------------------------------- ### Extract Features with FeatureExtractor Source: https://context7.com/kaiyangzhou/deep-person-reid/llms.txt The FeatureExtractor class provides a unified interface to generate embeddings from images. It supports inputs as file paths or numpy arrays and requires a pre-trained model configuration. ```python from torchreid.utils import FeatureExtractor import numpy as np extractor = FeatureExtractor( model_name='osnet_x1_0', model_path='path/to/model.pth.tar', image_size=(256, 128), pixel_mean=[0.485, 0.456, 0.406], pixel_std=[0.229, 0.224, 0.225], device='cuda' ) features = extractor('images/person001.jpg') image_np = np.random.rand(256, 128, 3).astype(np.uint8) features_np = extractor(image_np) ``` -------------------------------- ### torchreid.data.transforms Source: https://github.com/kaiyangzhou/deep-person-reid/blob/master/docs/pkg/data.rst Defines image transformation operations used for data augmentation and preprocessing in person re-identification. ```APIDOC ## torchreid.data.transforms ### Description Contains a collection of image transformations such as resizing, cropping, flipping, and color jittering. These are applied to images to augment the training data and prepare it for the model. ### Method N/A (This is a module description, not an endpoint) ### Endpoint N/A ### Parameters N/A ### Request Example N/A ### Response N/A ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.