code
stringlengths
17
6.64M
def is_tuple_of(seq, expected_type): 'Check whether it is a tuple of some type.\n\n A partial method of :func:`is_seq_of`.\n ' return is_seq_of(seq, expected_type, seq_type=tuple)
def slice_list(in_list, lens): 'Slice a list into several sub lists by a list of given length.\n\n Args:\n in_list (list): The list to be sliced.\n lens(int or list): The expected length of each out list.\n\n Returns:\n list: A list of sliced list.\n ' if isinstance(lens, int): ...
def concat_list(in_list): 'Concatenate a list of list into a single list.\n\n Args:\n in_list (list): The list of list to be merged.\n\n Returns:\n list: The concatenated flat list.\n ' return list(itertools.chain(*in_list))
def check_prerequisites(prerequisites, checker, msg_tmpl='Prerequisites "{}" are required in method "{}" but not found, please install them first.'): 'A decorator factory to check if prerequisites are satisfied.\n\n Args:\n prerequisites (str of list[str]): Prerequisites to be checked.\n checker ...
def _check_py_package(package): try: import_module(package) except ImportError: return False else: return True
def _check_executable(cmd): if (subprocess.call('which {}'.format(cmd), shell=True) != 0): return False else: return True
def requires_package(prerequisites): "A decorator to check if some python packages are installed.\n\n Example:\n >>> @requires_package('numpy')\n >>> func(arg1, args):\n >>> return numpy.zeros(1)\n array([0.])\n >>> @requires_package(['numpy', 'non_package'])\n >>>...
def requires_executable(prerequisites): "A decorator to check if some executable files are installed.\n\n Example:\n >>> @requires_executable('ffmpeg')\n >>> func(arg1, args):\n >>> print(1)\n 1\n " return check_prerequisites(prerequisites, checker=_check_executable)
def is_filepath(x): if (is_str(x) or isinstance(x, Path)): return True else: return False
def fopen(filepath, *args, **kwargs): if is_str(filepath): return open(filepath, *args, **kwargs) elif isinstance(filepath, Path): return filepath.open(*args, **kwargs)
def check_file_exist(filename, msg_tmpl='file "{}" does not exist'): if (not osp.isfile(filename)): raise FileNotFoundError(msg_tmpl.format(filename))
def mkdir_or_exist(dir_name, mode=511): if (dir_name == ''): return dir_name = osp.expanduser(dir_name) os.makedirs(dir_name, mode=mode, exist_ok=True)
def symlink(src, dst, overwrite=True, **kwargs): if (os.path.lexists(dst) and overwrite): os.remove(dst) os.symlink(src, dst, **kwargs)
def scandir(dir_path, suffix=None, recursive=False): 'Scan a directory to find the interested files.\n\n Args:\n dir_path (str | obj:`Path`): Path of the directory.\n suffix (str | tuple(str), optional): File suffix that we are\n interested in. Default: None.\n recursive (bool, ...
def find_vcs_root(path, markers=('.git',)): 'Finds the root directory (including itself) of specified markers.\n\n Args:\n path (str): Path of directory or file.\n markers (list[str], optional): List of file or directory names.\n\n Returns:\n The directory contained one of the markers o...
class ProgressBar(object): 'A progress bar which can print the progress' def __init__(self, task_num=0, bar_width=50, start=True, file=sys.stdout): self.task_num = task_num self.bar_width = bar_width self.completed = 0 self.file = file if start: self.start(...
def track_progress(func, tasks, bar_width=50, file=sys.stdout, **kwargs): 'Track the progress of tasks execution with a progress bar.\n\n Tasks are done with a simple for-loop.\n\n Args:\n func (callable): The function to be applied to each task.\n tasks (list or tuple[Iterable, int]): A list ...
def init_pool(process_num, initializer=None, initargs=None): if (initializer is None): return Pool(process_num) elif (initargs is None): return Pool(process_num, initializer) else: if (not isinstance(initargs, tuple)): raise TypeError('"initargs" must be a tuple') ...
def track_parallel_progress(func, tasks, nproc, initializer=None, initargs=None, bar_width=50, chunksize=1, skip_first=False, keep_order=True, file=sys.stdout): 'Track the progress of parallel task execution with a progress bar.\n\n The built-in :mod:`multiprocessing` module is used for process pools and\n ...
def track_iter_progress(tasks, bar_width=50, file=sys.stdout, **kwargs): 'Track the progress of tasks iteration or enumeration with a progress bar.\n\n Tasks are yielded with a simple for-loop.\n\n Args:\n tasks (list or tuple[Iterable, int]): A list of tasks or\n (tasks, total num).\n ...
class Registry(object): 'A registry to map strings to classes.\n\n Args:\n name (str): Registry name.\n ' def __init__(self, name): self._name = name self._module_dict = dict() def __len__(self): return len(self._module_dict) def __repr__(self): format_s...
def build_from_cfg(cfg, registry, default_args=None): 'Build a module from config dict.\n\n Args:\n cfg (dict): Config dict. It should at least contain the key "type".\n registry (:obj:`Registry`): The registry to search the type from.\n default_args (dict, optional): Default initializatio...
class TimerError(Exception): def __init__(self, message): self.message = message super(TimerError, self).__init__(message)
class Timer(object): "A flexible Timer class.\n\n :Example:\n\n >>> import time\n >>> import mmcv\n >>> with mmcv.Timer():\n >>> # simulate a code block that will run for 1s\n >>> time.sleep(1)\n 1.000\n >>> with mmcv.Timer(print_tmpl='it takes {:.1f} seconds'):\n >>> # simu...
def check_time(timer_id): "Add check points in a single line.\n\n This method is suitable for running a task on a list of items. A timer will\n be registered when the method is called for the first time.\n\n :Example:\n\n >>> import time\n >>> import mmcv\n >>> for i in range(1, 6):\n >>> ...
class Cache(object): def __init__(self, capacity): self._cache = OrderedDict() self._capacity = int(capacity) if (capacity <= 0): raise ValueError('capacity must be a positive integer') @property def capacity(self): return self._capacity @property def...
class VideoReader(object): "Video class with similar usage to a list object.\n\n This video warpper class provides convenient apis to access frames.\n There exists an issue of OpenCV's VideoCapture class that jumping to a\n certain frame may be inaccurate. It is fixed in this class by checking\n the p...
def frames2video(frame_dir, video_file, fps=30, fourcc='XVID', filename_tmpl='{:06d}.jpg', start=0, end=0, show_progress=True): 'Read the frame images from a directory and join them as a video\n\n Args:\n frame_dir (str): The directory containing video frames.\n video_file (str): Output filename....
def flowread(flow_or_path, quantize=False, concat_axis=0, *args, **kwargs): 'Read an optical flow map.\n\n Args:\n flow_or_path (ndarray or str): A flow map or filepath.\n quantize (bool): whether to read quantized pair, if set to True,\n remaining args will be passed to :func:`dequant...
def flowwrite(flow, filename, quantize=False, concat_axis=0, *args, **kwargs): 'Write optical flow to file.\n\n If the flow is not quantized, it will be saved as a .flo file losslessly,\n otherwise a jpeg image which is lossy but of much smaller size. (dx and dy\n will be concatenated horizontally into a...
def quantize_flow(flow, max_val=0.02, norm=True): 'Quantize flow to [0, 255].\n\n After this step, the size of flow will be much smaller, and can be\n dumped as jpeg images.\n\n Args:\n flow (ndarray): (h, w, 2) array of optical flow.\n max_val (float): Maximum value of flow, values beyond\...
def dequantize_flow(dx, dy, max_val=0.02, denorm=True): 'Recover from quantized flow.\n\n Args:\n dx (ndarray): Quantized dx.\n dy (ndarray): Quantized dy.\n max_val (float): Maximum value used when quantizing.\n denorm (bool): Whether to multiply flow values with width/height.\n\n ...
def flow_warp(img, flow, filling_value=0, interpolate_mode='nearest'): 'Use flow to warp img\n\n Args:\n img (ndarray, float or uint8): Image to be warped.\n flow (ndarray, float): Optical Flow.\n filling_value (int): The missing pixels will be set with filling_value.\n interpolate_...
@requires_executable('ffmpeg') def convert_video(in_file, out_file, print_cmd=False, pre_options='', **kwargs): 'Convert a video with ffmpeg.\n\n This provides a general api to ffmpeg, the executed command is::\n\n `ffmpeg -y <pre_options> -i <in_file> <options> <out_file>`\n\n Options(kwargs) are ma...
@requires_executable('ffmpeg') def resize_video(in_file, out_file, size=None, ratio=None, keep_ar=False, log_level='info', print_cmd=False, **kwargs): 'Resize a video.\n\n Args:\n in_file (str): Input video filename.\n out_file (str): Output video filename.\n size (tuple): Expected size (w...
@requires_executable('ffmpeg') def cut_video(in_file, out_file, start=None, end=None, vcodec=None, acodec=None, log_level='info', print_cmd=False, **kwargs): 'Cut a clip from a video.\n\n Args:\n in_file (str): Input video filename.\n out_file (str): Output video filename.\n start (None or...
@requires_executable('ffmpeg') def concat_video(video_list, out_file, vcodec=None, acodec=None, log_level='info', print_cmd=False, **kwargs): 'Concatenate multiple videos into a single one.\n\n Args:\n video_list (list): A list of video filenames\n out_file (str): Output video filename\n v...
class Color(Enum): 'An enum that defines common colors.\n\n Contains red, green, blue, cyan, yellow, magenta, white and black.\n ' red = (0, 0, 255) green = (0, 255, 0) blue = (255, 0, 0) cyan = (255, 255, 0) yellow = (0, 255, 255) magenta = (255, 0, 255) white = (255, 255, 255) ...
def color_val(color): 'Convert various input to color tuples.\n\n Args:\n color (:obj:`Color`/str/tuple/int/ndarray): Color inputs\n\n Returns:\n tuple[int]: A tuple of 3 integers indicating BGR channels.\n ' if is_str(color): return Color[color].value elif isinstance(color,...
def init_dist(launcher, backend='nccl', **kwargs): if (mp.get_start_method(allow_none=True) is None): mp.set_start_method('spawn') if (launcher == 'pytorch'): _init_dist_pytorch(backend, **kwargs) elif (launcher == 'mpi'): _init_dist_mpi(backend, **kwargs) elif (launcher == 'sl...
def _init_dist_pytorch(backend, **kwargs): rank = int(os.environ['RANK']) num_gpus = torch.cuda.device_count() torch.cuda.set_device((rank % num_gpus)) dist.init_process_group(backend=backend, **kwargs)
def _init_dist_mpi(backend, **kwargs): raise NotImplementedError
def _init_dist_slurm(backend, **kwargs): raise NotImplementedError
def set_random_seed(seed): random.seed(seed) np.random.seed(seed) torch.manual_seed(seed) torch.cuda.manual_seed_all(seed)
def get_root_logger(log_level=logging.INFO): logger = logging.getLogger() if (not logger.hasHandlers()): logging.basicConfig(format='%(asctime)s - %(levelname)s - %(message)s', level=log_level) (rank, _) = get_dist_info() if (rank != 0): logger.setLevel('ERROR') return logger
def _prepare_data(img, img_transform, cfg, device): ori_shape = img.shape (img, img_shape, pad_shape, scale_factor) = img_transform(img, scale=cfg.data.test.img_scale) img = to_tensor(img).to(device).unsqueeze(0) img_meta = [dict(ori_shape=ori_shape, img_shape=img_shape, pad_shape=pad_shape, scale_fac...
def _inference_single(model, img, img_transform, cfg, device): img = mmcv.imread(img) data = _prepare_data(img, img_transform, cfg, device) with torch.no_grad(): result = model(return_loss=False, rescale=True, **data) return result
def _inference_generator(model, imgs, img_transform, cfg, device): for img in imgs: (yield _inference_single(model, img, img_transform, cfg, device))
def inference_detector(model, imgs, cfg, device='cuda:0'): img_transform = ImageTransform(size_divisor=cfg.data.test.size_divisor, **cfg.img_norm_cfg) model = model.to(device) model.eval() if (not isinstance(imgs, list)): return _inference_single(model, imgs, img_transform, cfg, device) el...
def show_result(img, result, dataset='coco', score_thr=0.3): class_names = get_classes(dataset) labels = [np.full(bbox.shape[0], i, dtype=np.int32) for (i, bbox) in enumerate(result)] labels = np.concatenate(labels) bboxes = np.vstack(result) img = mmcv.imread(img) mmcv.imshow_det_bboxes(img.c...
def parse_losses(losses): log_vars = OrderedDict() for (loss_name, loss_value) in losses.items(): if isinstance(loss_value, torch.Tensor): log_vars[loss_name] = loss_value.mean() elif isinstance(loss_value, list): log_vars[loss_name] = sum((_loss.mean() for _loss in los...
def batch_processor(model, data, train_mode): losses = model(**data) (loss, log_vars) = parse_losses(losses) outputs = dict(loss=loss, log_vars=log_vars, num_samples=len(data['img'].data)) return outputs
def train_detector(model, dataset, cfg, distributed=False, validate=False, logger=None): if (logger is None): logger = get_root_logger(cfg.log_level) if distributed: _dist_train(model, dataset, cfg, validate=validate) else: _non_dist_train(model, dataset, cfg, validate=validate)
def _dist_train(model, dataset, cfg, validate=False): data_loaders = [build_dataloader(dataset, cfg.data.imgs_per_gpu, cfg.data.workers_per_gpu, dist=True)] model = MMDistributedDataParallel(model.cuda()) runner = Runner(model, batch_processor, cfg.optimizer, cfg.work_dir, cfg.log_level) optimizer_con...
def _non_dist_train(model, dataset, cfg, validate=False): data_loaders = [build_dataloader(dataset, cfg.data.imgs_per_gpu, cfg.data.workers_per_gpu, cfg.gpus, dist=False)] model = MMDataParallel(model, device_ids=range(cfg.gpus)).cuda() runner = Runner(model, batch_processor, cfg.optimizer, cfg.work_dir, ...
class TargetEncoder(): def __init__(self, box_coders, region_similarity): self._similarity_fn = getattr(regionSimilarity, region_similarity)() self._box_coder = getattr(boxCoders, box_coders)() @property def box_coder(self): return self._box_coder def assign(self, anchors, g...
def voc_classes(): return ['aeroplane', 'bicycle', 'bird', 'boat', 'bottle', 'bus', 'car', 'cat', 'chair', 'cow', 'diningtable', 'dog', 'horse', 'motorbike', 'person', 'pottedplant', 'sheep', 'sofa', 'train', 'tvmonitor']
def imagenet_det_classes(): return ['accordion', 'airplane', 'ant', 'antelope', 'apple', 'armadillo', 'artichoke', 'axe', 'baby_bed', 'backpack', 'bagel', 'balance_beam', 'banana', 'band_aid', 'banjo', 'baseball', 'basketball', 'bathing_cap', 'beaker', 'bear', 'bee', 'bell_pepper', 'bench', 'bicycle', 'binder', '...
def imagenet_vid_classes(): return ['airplane', 'antelope', 'bear', 'bicycle', 'bird', 'bus', 'car', 'cattle', 'dog', 'domestic_cat', 'elephant', 'fox', 'giant_panda', 'hamster', 'horse', 'lion', 'lizard', 'monkey', 'motorcycle', 'rabbit', 'red_panda', 'sheep', 'snake', 'squirrel', 'tiger', 'train', 'turtle', 'wa...
def coco_classes(): return ['person', 'bicycle', 'car', 'motorcycle', 'airplane', 'bus', 'train', 'truck', 'boat', 'traffic light', 'fire hydrant', 'stop sign', 'parking meter', 'bench', 'bird', 'cat', 'dog', 'horse', 'sheep', 'cow', 'elephant', 'bear', 'zebra', 'giraffe', 'backpack', 'umbrella', 'handbag', 'tie'...
def kitti_classes(): return ['car', 'pedestrians', 'cyclists']
def get_classes(dataset): 'Get class names of a dataset.' alias2name = {} for (name, aliases) in dataset_aliases.items(): for alias in aliases: alias2name[alias] = name if mmcv.is_str(dataset): if (dataset in alias2name): labels = eval((alias2name[dataset] + '_c...
def coco_eval(result_file, result_types, coco, max_dets=(100, 300, 1000)): for res_type in result_types: assert (res_type in ['proposal', 'proposal_fast', 'bbox', 'segm', 'keypoints']) if mmcv.is_str(coco): coco = COCO(coco) assert isinstance(coco, COCO) if (result_types == ['proposal_...
def fast_eval_recall(results, coco, max_dets, iou_thrs=np.arange(0.5, 0.96, 0.05)): if mmcv.is_str(results): assert results.endswith('.pkl') results = mmcv.load(results) elif (not isinstance(results, list)): raise TypeError('results must be a list of numpy arrays or a filename, not {}'...
def xyxy2xywh(bbox): _bbox = bbox.tolist() return [_bbox[0], _bbox[1], ((_bbox[2] - _bbox[0]) + 1), ((_bbox[3] - _bbox[1]) + 1)]
def proposal2json(dataset, results): json_results = [] for idx in range(len(dataset)): img_id = dataset.img_ids[idx] bboxes = results[idx] for i in range(bboxes.shape[0]): data = dict() data['image_id'] = img_id data['bbox'] = xyxy2xywh(bboxes[i]) ...
def det2json(dataset, results): json_results = [] for idx in range(len(dataset)): img_id = dataset.img_ids[idx] result = results[idx] for label in range(len(result)): bboxes = result[label] for i in range(bboxes.shape[0]): data = dict() ...
def segm2json(dataset, results): json_results = [] for idx in range(len(dataset)): img_id = dataset.img_ids[idx] (det, seg) = results[idx] for label in range(len(det)): bboxes = det[label] segms = seg[label] for i in range(bboxes.shape[0]): ...
def results2json(dataset, results, out_file): if isinstance(results[0], list): json_results = det2json(dataset, results) elif isinstance(results[0], tuple): json_results = segm2json(dataset, results) elif isinstance(results[0], np.ndarray): json_results = proposal2json(dataset, res...
class DistEvalHook(Hook): def __init__(self, dataset, interval=1): if isinstance(dataset, Dataset): self.dataset = dataset elif isinstance(dataset, dict): self.dataset = obj_from_dict(dataset, datasets, {'test_mode': True}) else: raise TypeError('datase...
class CocoDistEvalRecallHook(DistEvalHook): def __init__(self, dataset, proposal_nums=(100, 300, 1000), iou_thrs=np.arange(0.5, 0.96, 0.05)): super(CocoDistEvalRecallHook, self).__init__(dataset) self.proposal_nums = np.array(proposal_nums, dtype=np.int32) self.iou_thrs = np.array(iou_thr...
class CocoDistEvalmAPHook(DistEvalHook): def evaluate(self, runner, results): tmp_file = osp.join(runner.work_dir, 'temp_0.json') results2json(self.dataset, results, tmp_file) res_types = (['bbox', 'segm'] if runner.model.module.with_mask else ['bbox']) cocoGt = self.dataset.coco ...
class DistEvalmAPHook(DistEvalHook): def evaluate(self, runner, results): gt_bboxes = [] gt_labels = [] gt_ignore = ([] if self.dataset.with_crowd else None) for i in range(len(self.dataset)): ann = self.dataset.get_ann_info(i) bboxes = ann['bboxes'] ...
class KittiEvalmAPHook(Hook): def __init__(self, dataset, interval=5): if isinstance(dataset, Dataset): self.dataset = dataset elif isinstance(dataset, dict): self.dataset = utils.get_dataset(dataset) else: raise TypeError('dataset must be a Dataset obj...
def weighted_nll_loss(pred, label, weight, avg_factor=None): if (avg_factor is None): avg_factor = max(torch.sum((weight > 0)).float().item(), 1.0) raw = F.nll_loss(pred, label, reduction='none') return (torch.sum((raw * weight))[None] / avg_factor)
def weighted_cross_entropy(pred, label, weight, avg_factor=None, reduce=True): if (avg_factor is None): avg_factor = max(torch.sum((weight > 0)).float().item(), 1.0) raw = F.cross_entropy(pred, label, reduction='none') if reduce: return (torch.sum((raw * weight))[None] / avg_factor) el...
def weighted_binary_cross_entropy(pred, label, weight, avg_factor=None): if (avg_factor is None): avg_factor = max(torch.sum((weight > 0)).float().item(), 1.0) return (F.binary_cross_entropy_with_logits(pred, label.float(), weight.float(), reduction='sum')[None] / avg_factor)
def sigmoid_focal_loss(pred, target, weight, gamma=2.0, alpha=0.25, reduction='mean'): pred_sigmoid = pred.sigmoid() target = target.type_as(pred) pt = (((1 - pred_sigmoid) * target) + (pred_sigmoid * (1 - target))) weight = (((alpha * target) + ((1 - alpha) * (1 - target))) * weight) weight = (we...
def weighted_sigmoid_focal_loss(pred, target, weight, gamma=2.0, alpha=0.25, avg_factor=None, num_classes=80): if (avg_factor is None): avg_factor = ((torch.sum((weight > 0)).float().item() / num_classes) + 1e-06) return (sigmoid_focal_loss(pred, target, weight, gamma=gamma, alpha=alpha, reduction='su...
def mask_cross_entropy(pred, target, label): num_rois = pred.size()[0] inds = torch.arange(0, num_rois, dtype=torch.long, device=pred.device) pred_slice = pred[(inds, label)].squeeze(1) return F.binary_cross_entropy_with_logits(pred_slice, target, reduction='mean')[None]
def smooth_l1_loss(pred, target, beta=1.0, reduction='mean'): assert (beta > 0) assert ((pred.size() == target.size()) and (target.numel() > 0)) diff = torch.abs((pred - target)) loss = torch.where((diff < beta), (((0.5 * diff) * diff) / beta), (diff - (0.5 * beta))) reduction_enum = F._Reduction....
def weighted_smoothl1(pred, target, weight, beta=1.0, avg_factor=None): if (avg_factor is None): avg_factor = ((torch.sum((weight > 0)).float().item() / 4) + 1e-06) loss = smooth_l1_loss(pred, target, beta, reduction='none') return (torch.sum((loss * weight))[None] / avg_factor)
def l1_loss(pred, target, reduction='mean'): assert ((pred.size() == target.size()) and (target.numel() > 0)) loss = torch.abs((pred - target)) reduction_enum = F._Reduction.get_enum(reduction) if (reduction_enum == 0): return loss elif (reduction_enum == 1): return (loss.sum() / p...
def weighted_l1(pred, target, weight, avg_factor=None): if (avg_factor is None): avg_factor = ((torch.sum((weight > 0)).float().item() / 4) + 1e-06) loss = l1_loss(pred, target, reduction='none') return (torch.sum((loss * weight))[None] / avg_factor)
def accuracy(pred, target, topk=1): if isinstance(topk, int): topk = (topk,) return_single = True else: return_single = False maxk = max(topk) (_, pred_label) = pred.topk(maxk, 1, True, True) pred_label = pred_label.t() correct = pred_label.eq(target.view(1, (- 1)).expa...
def huber_loss(error, delta): abs_error = torch.abs(error) quadratic = torch.min(abs_error, torch.full_like(abs_error, fill_value=delta)) losses = ((0.5 * (quadratic ** 2)) + (delta * (abs_error - quadratic))) return torch.mean(losses)
def split_combined_polys(polys, poly_lens, polys_per_mask): 'Split the combined 1-D polys into masks.\n\n A mask is represented as a list of polys, and a poly is represented as\n a 1-D array. In dataset, all masks are concatenated into a single 1-D\n tensor. Here we need to split the tensor into original...
class VoxelGenerator(): def __init__(self, voxel_size, point_cloud_range, max_num_points, max_voxels=20000): point_cloud_range = np.array(point_cloud_range, dtype=np.float32) voxel_size = np.array(voxel_size, dtype=np.float32) grid_size = ((point_cloud_range[3:] - point_cloud_range[:3]) /...
def rotate_nms_torch(rbboxes, scores, pre_max_size=None, post_max_size=None, iou_threshold=0.5): if (pre_max_size is not None): num_keeped_scores = scores.shape[0] pre_max_size = min(num_keeped_scores, pre_max_size) (scores, indices) = torch.topk(scores, k=pre_max_size) rbboxes = r...
def _allreduce_coalesced(tensors, world_size, bucket_size_mb=(- 1)): if (bucket_size_mb > 0): bucket_size_bytes = ((bucket_size_mb * 1024) * 1024) buckets = _take_tensors(tensors, bucket_size_bytes) else: buckets = OrderedDict() for tensor in tensors: tp = tensor.ty...
def allreduce_grads(model, coalesce=True, bucket_size_mb=(- 1)): grads = [param.grad.data for param in model.parameters() if (param.requires_grad and (param.grad is not None))] world_size = dist.get_world_size() if coalesce: _allreduce_coalesced(grads, world_size, bucket_size_mb) else: ...
class DistOptimizerHook(OptimizerHook): def __init__(self, grad_clip=None, coalesce=True, bucket_size_mb=(- 1)): self.grad_clip = grad_clip self.coalesce = coalesce self.bucket_size_mb = bucket_size_mb def after_train_iter(self, runner): runner.optimizer.zero_grad() r...
class CocoDataset(CustomDataset): def load_annotations(self, ann_file): self.coco = COCO(ann_file) self.cat_ids = self.coco.getCatIds() self.cat2label = {cat_id: (i + 1) for (i, cat_id) in enumerate(self.cat_ids)} self.img_ids = self.coco.getImgIds() img_infos = [] ...
class ConcatDataset(_ConcatDataset): '\n Same as torch.utils.data.dataset.ConcatDataset, but\n concat the group flag for image aspect ratio.\n ' def __init__(self, datasets): '\n flag: Images with aspect ratio greater than 1 will be set as group 1,\n otherwise group 0.\n ...
def build_dataloader(dataset, imgs_per_gpu, workers_per_gpu, num_gpus=1, dist=True, **kwargs): if dist: (rank, world_size) = get_dist_info() sampler = DistributedGroupSampler(dataset, imgs_per_gpu, world_size, rank) batch_size = imgs_per_gpu num_workers = workers_per_gpu else: ...
class GroupSampler(Sampler): def __init__(self, dataset, samples_per_gpu=1): assert hasattr(dataset, 'flag') self.dataset = dataset self.samples_per_gpu = samples_per_gpu self.flag = dataset.flag.astype(np.int64) self.group_sizes = np.bincount(self.flag) self.num_s...
class DistributedGroupSampler(Sampler): 'Sampler that restricts data loading to a subset of the dataset.\n It is especially useful in conjunction with\n :class:`torch.nn.parallel.DistributedDataParallel`. In such case, each\n process can pass a DistributedSampler instance as a DataLoader sampler,\n an...
def to_tensor(data): 'Convert objects of various python types to :obj:`torch.Tensor`.\n\n Supported types are: :class:`numpy.ndarray`, :class:`torch.Tensor`,\n :class:`Sequence`, :class:`int` and :class:`float`.\n ' if isinstance(data, torch.Tensor): return data elif isinstance(data, np.n...
def random_scale(img_scales, mode='range'): 'Randomly select a scale from a list of scales or scale ranges.\n\n Args:\n img_scales (list[tuple]): Image scale or scale range.\n mode (str): "range" or "value".\n\n Returns:\n tuple: Sampled image scale.\n ' num_scales = len(img_scal...
def show_ann(coco, img, ann_info): plt.imshow(mmcv.bgr2rgb(img)) plt.axis('off') coco.showAnns(ann_info) plt.show()