code
stringlengths
17
6.64M
def convert_cityscapes_instance_only(data_dir, out_dir): 'Convert from cityscapes format to COCO instance seg format - polygons' sets = ['gtFine_val'] ann_dirs = ['gtFine_trainvaltest/gtFine/val'] json_name = 'instancesonly_filtered_%s.json' ends_in = '%s_polygons.json' img_id = 0 ann_id =...
def parse_args(): parser = argparse.ArgumentParser(description='Convert a COCO pre-trained model for use with Cityscapes') parser.add_argument('--coco_model', dest='coco_model_file_name', help='Pretrained network weights file path', default=None, type=str) parser.add_argument('--convert_func', dest='conve...
def convert_coco_blobs_to_cityscape_blobs(model_dict): for (k, v) in model_dict['blobs'].items(): if ((v.shape[0] == NUM_COCO_CLS) or (v.shape[0] == (4 * NUM_COCO_CLS))): coco_blob = model_dict['blobs'][k] print('Converting COCO blob {} with shape {}'.format(k, coco_blob.shape)) ...
def convert_coco_blob_to_cityscapes_blob(coco_blob, convert_func): coco_shape = coco_blob.shape leading_factor = int((coco_shape[0] / NUM_COCO_CLS)) tail_shape = list(coco_shape[1:]) assert ((leading_factor == 1) or (leading_factor == 4)) coco_blob = coco_blob.reshape(([NUM_COCO_CLS, (- 1)] + tail...
def remove_momentum(model_dict): for k in model_dict['blobs'].keys(): if k.endswith('_momentum'): del model_dict['blobs'][k]
def load_and_convert_coco_model(args): with open(args.coco_model_file_name, 'r') as f: model_dict = pickle.load(f) remove_momentum(model_dict) convert_coco_blobs_to_cityscape_blobs(model_dict) return model_dict
def factory(k): if k.startswith('vg'): ds_name = k[:k.find('_')] return {IM_DIR: (_DATA_DIR + '/vg/images/'), ANN_FN: (_DATA_DIR + ('/%s/instances_%s.json' % (ds_name, k)))} else: return None
def get_coco_dataset(): "A dummy COCO dataset that includes only the 'classes' field." ds = AttrDict() classes = ['__background__', 'person', 'bicycle', 'car', 'motorcycle', 'airplane', 'bus', 'train', 'truck', 'boat', 'traffic light', 'fire hydrant', 'stop sign', 'parking meter', 'bench', 'bird', 'cat', ...
def evaluate_all(dataset, all_boxes, all_segms, all_keyps, output_dir, use_matlab=False): 'Evaluate "all" tasks, where "all" includes box detection, instance\n segmentation, and keypoint detection.\n ' all_results = evaluate_boxes(dataset, all_boxes, output_dir, use_matlab=use_matlab) logger.info('E...
def evaluate_boxes(dataset, all_boxes, output_dir, use_matlab=False): 'Evaluate bounding box detection.' logger.info('Evaluating detections') not_comp = (not cfg.TEST.COMPETITION_MODE) if _use_json_dataset_evaluator(dataset): coco_eval = json_dataset_evaluator.evaluate_boxes(dataset, all_boxes...
def evaluate_masks(dataset, all_boxes, all_segms, output_dir): 'Evaluate instance segmentation.' logger.info('Evaluating segmentations') not_comp = (not cfg.TEST.COMPETITION_MODE) if _use_json_dataset_evaluator(dataset): coco_eval = json_dataset_evaluator.evaluate_masks(dataset, all_boxes, all...
def evaluate_keypoints(dataset, all_boxes, all_keyps, output_dir): 'Evaluate human keypoint detection (i.e., 2D pose estimation).' logger.info('Evaluating detections') not_comp = (not cfg.TEST.COMPETITION_MODE) assert dataset.name.startswith('keypoints_coco_'), 'Only COCO keypoints are currently suppo...
def evaluate_box_proposals(dataset, roidb): 'Evaluate bounding box object proposals.' res = _empty_box_proposal_results() areas = {'all': '', 'small': 's', 'medium': 'm', 'large': 'l'} for limit in [100, 1000]: for (area, suffix) in areas.items(): stats = json_dataset_evaluator.eva...
def log_box_proposal_results(results): 'Log bounding box proposal results.' for dataset in results.keys(): keys = results[dataset]['box_proposal'].keys() pad = max([len(k) for k in keys]) logger.info(dataset) for (k, v) in results[dataset]['box_proposal'].items(): l...
def log_copy_paste_friendly_results(results): "Log results in a format that makes it easy to copy-and-paste in a\n spreadsheet. Lines are prefixed with 'copypaste: ' to make grepping easy.\n " for dataset in results.keys(): logger.info('copypaste: Dataset: {}'.format(dataset)) for (task,...
def check_expected_results(results, atol=0.005, rtol=0.1): "Check actual results against expected results stored in\n cfg.EXPECTED_RESULTS. Optionally email if the match exceeds the specified\n tolerance.\n\n Expected results should take the form of a list of expectations, each\n specified by four ele...
def _use_json_dataset_evaluator(dataset): 'Check if the dataset uses the general json dataset evaluator.' return (dataset.name.startswith('coco') or cfg.TEST.FORCE_JSON_DATASET_EVAL)
def _use_cityscapes_evaluator(dataset): 'Check if the dataset uses the Cityscapes dataset evaluator.' return (dataset.name.find('cityscapes_') > (- 1))
def _use_vg_evaluator(dataset): 'Check if the dataset uses the Cityscapes dataset evaluator.' return dataset.name.startswith('vg')
def _use_voc_evaluator(dataset): 'Check if the dataset uses the PASCAL VOC dataset evaluator.' return (dataset.name[:4] == 'voc_')
def _coco_eval_to_box_results(coco_eval): res = _empty_box_results() if (coco_eval is not None): s = coco_eval.stats res['box']['AP'] = s[COCO_AP] res['box']['AP50'] = s[COCO_AP50] res['box']['AP75'] = s[COCO_AP75] res['box']['APs'] = s[COCO_APS] res['box']['APm...
def _coco_eval_to_mask_results(coco_eval): res = _empty_mask_results() if (coco_eval is not None): s = coco_eval.stats res['mask']['AP'] = s[COCO_AP] res['mask']['AP50'] = s[COCO_AP50] res['mask']['AP75'] = s[COCO_AP75] res['mask']['APs'] = s[COCO_APS] res['mask...
def _coco_eval_to_keypoint_results(coco_eval): res = _empty_keypoint_results() if (coco_eval is not None): s = coco_eval.stats res['keypoint']['AP'] = s[COCO_AP] res['keypoint']['AP50'] = s[COCO_AP50] res['keypoint']['AP75'] = s[COCO_AP75] res['keypoint']['APm'] = s[COC...
def _voc_eval_to_box_results(voc_eval): return _empty_box_results()
def _cs_eval_to_mask_results(cs_eval): return _empty_mask_results()
def _empty_box_results(): return OrderedDict({'box': OrderedDict([('AP', (- 1)), ('AP50', (- 1)), ('AP75', (- 1)), ('APs', (- 1)), ('APm', (- 1)), ('APl', (- 1))])})
def _empty_mask_results(): return OrderedDict({'mask': OrderedDict([('AP', (- 1)), ('AP50', (- 1)), ('AP75', (- 1)), ('APs', (- 1)), ('APm', (- 1)), ('APl', (- 1))])})
def _empty_keypoint_results(): return OrderedDict({'keypoint': OrderedDict([('AP', (- 1)), ('AP50', (- 1)), ('AP75', (- 1)), ('APm', (- 1)), ('APl', (- 1))])})
def _empty_box_proposal_results(): return OrderedDict({'box_proposal': OrderedDict([('AR@100', (- 1)), ('ARs@100', (- 1)), ('ARm@100', (- 1)), ('ARl@100', (- 1)), ('AR@1000', (- 1)), ('ARs@1000', (- 1)), ('ARm@1000', (- 1)), ('ARl@1000', (- 1))])})
def clean_string(string): predicate = sentence_preprocess(string) if (predicate in rel_alias_dict): predicate = rel_alias_dict[predicate] return predicate
def sentence_preprocess(phrase): ' preprocess a sentence: lowercase, clean up weird chars, remove punctuation ' replacements = {'½': 'half', '—': '-', '™': '', '¢': 'cent', 'ç': 'c', 'û': 'u', 'é': 'e', '°': ' degree', 'è': 'e', '…': ''} phrase = phrase.encode('utf-8') phrase = phrase.lstrip(' ').rstr...
def preprocess_predicates(data, alias_dict={}): for img in data: for relation in img['relationships']: predicate = sentence_preprocess(relation['predicate']) if (predicate in alias_dict): predicate = alias_dict[predicate] relation['predicate'] = predicat...
def make_alias_dict(dict_file): 'create an alias dictionary from a file' out_dict = {} vocab = [] for line in open(dict_file, 'r'): alias = line.strip('\n').strip('\r').split(',') alias_target = (alias[0] if (alias[0] not in out_dict) else out_dict[alias[0]]) for a in alias: ...
def clean_relations(string): string = clean_string(string) if (len(string) > 0): return [string] else: return []
def get_synset_embedding(synset, word_vectors, get_vector): class_name = wn.synset(synset).lemma_names() class_name = ', '.join([_.replace('_', ' ') for _ in class_name]) class_name = class_name.lower() feat = np.zeros(feat_len) options = class_name.split(',') cnt_word = 0 for j in range(l...
def get_embedding(entity_str, word_vectors, get_vector): try: feat = get_vector(word_vectors, entity_str) return feat except: feat = np.zeros(feat_len) str_set = list(filter(None, re.split('[ \\-_]+', entity_str))) cnt_word = 0 for i in range(len(str_set)): temp_str...
def get_vector(word_vectors, word): if (word in word_vectors.stoi): return word_vectors[word].numpy() else: raise NotImplementedError
def filter_annotations(ds, func): ds = copy.deepcopy(ds) ds.update({'annotations': func(ds['annotations'])}) return ds
def clean_string(string): string = string.lower().strip() if ((len(string) >= 1) and (string[(- 1)] == '.')): return string[:(- 1)].strip() return string
def clean_relations(string): string = clean_string(string) if (len(string) > 0): return [string] else: return []
def get_synset_embedding(synset, word_vectors, get_vector): class_name = wn.synset(synset).lemma_names() class_name = ', '.join([_.replace('_', ' ') for _ in class_name]) class_name = class_name.lower() feat = np.zeros(feat_len) options = class_name.split(',') cnt_word = 0 for j in range(l...
def get_embedding(entity_str, word_vectors, get_vector): try: feat = get_vector(word_vectors, entity_str) return feat except: feat = np.zeros(feat_len) str_set = list(filter(None, re.split('[ \\-_]+', entity_str))) cnt_word = 0 for i in range(len(str_set)): temp_str...
def get_vector(word_vectors, word): if (word in word_vectors.stoi): return word_vectors[word].numpy() else: raise NotImplementedError
def filter_annotations(ds, func): ds = copy.deepcopy(ds) ds.update({'annotations': func(ds['annotations'])}) return ds
def evaluate_boxes(json_dataset, all_boxes, output_dir, use_salt=True, cleanup=True, use_matlab=False): salt = ('_{}'.format(str(uuid.uuid4())) if use_salt else '') filenames = _write_voc_results_files(json_dataset, all_boxes, salt) _do_python_eval(json_dataset, salt, output_dir) if use_matlab: ...
def _write_voc_results_files(json_dataset, all_boxes, salt): filenames = [] image_set_path = voc_info(json_dataset)['image_set_path'] assert os.path.exists(image_set_path), 'Image set path does not exist: {}'.format(image_set_path) with open(image_set_path, 'r') as f: image_index = [x.strip() ...
def _get_voc_results_file_template(json_dataset, salt): info = voc_info(json_dataset) year = info['year'] image_set = info['image_set'] devkit_path = info['devkit_path'] filename = (((('comp4' + salt) + '_det_') + image_set) + '_{:s}.txt') return os.path.join(devkit_path, 'results', ('VOC' + y...
def _do_python_eval(json_dataset, salt, output_dir='output'): info = voc_info(json_dataset) year = info['year'] anno_path = info['anno_path'] image_set_path = info['image_set_path'] devkit_path = info['devkit_path'] cachedir = os.path.join(devkit_path, 'annotations_cache') aps = [] use...
def _do_matlab_eval(json_dataset, salt, output_dir='output'): import subprocess logger.info('-----------------------------------------------------') logger.info('Computing results with the official MATLAB eval code.') logger.info('-----------------------------------------------------') info = voc_...
def voc_info(json_dataset): year = json_dataset.name[4:8] image_set = json_dataset.name[9:] devkit_path = DATASETS[json_dataset.name][DEVKIT_DIR] assert os.path.exists(devkit_path), 'Devkit directory {} not found'.format(devkit_path) anno_path = os.path.join(devkit_path, ('VOC' + year), 'Annotatio...
class _ROIAlign(Function): @staticmethod def forward(ctx, input, roi, output_size, spatial_scale, sampling_ratio): ctx.save_for_backward(roi) ctx.output_size = _pair(output_size) ctx.spatial_scale = spatial_scale ctx.sampling_ratio = sampling_ratio ctx.input_shape = in...
class ROIAlign(nn.Module): def __init__(self, output_size, spatial_scale, sampling_ratio): super(ROIAlign, self).__init__() self.output_size = output_size self.spatial_scale = spatial_scale self.sampling_ratio = sampling_ratio def forward(self, input, rois): return ro...
class _ROIPool(Function): @staticmethod def forward(ctx, input, roi, output_size, spatial_scale): ctx.output_size = _pair(output_size) ctx.spatial_scale = spatial_scale ctx.input_shape = input.size() (output, argmax) = _C.roi_pool_forward(input, roi, spatial_scale, output_size...
class ROIPool(nn.Module): def __init__(self, output_size, spatial_scale): super(ROIPool, self).__init__() self.output_size = output_size self.spatial_scale = spatial_scale def forward(self, input, rois): return roi_pool(input, rois, self.output_size, self.spatial_scale) ...
class MobileNet_v1_conv12_body(nn.Module): def __init__(self): super().__init__() (self.conv, self.dim_out) = mobilenet_base(V1_CONV_DEFS[:12]) self.conv = nn.Sequential(*self.conv) self.spatial_scale = (1 / 16) self._init_modules() def _init_modules(self): as...
class MobileNet_v2_conv14_body(nn.Module): def __init__(self): super().__init__() (self.conv, self.dim_out) = mobilenet_base(V2_CONV_DEFS[:6]) self.conv = nn.Sequential(*self.conv) self.spatial_scale = (1 / 16) self._init_modules() def _init_modules(self): ass...
class MobileNet_roi_conv_head(nn.Module): def __init__(self, dim_in, roi_xform_func, spatial_scale): super().__init__() self.roi_xform = roi_xform_func self.spatial_scale = spatial_scale self.stride_init = (cfg.FAST_RCNN.ROI_XFORM_RESOLUTION // 7) self.avgpool = nn.AvgPool...
class MobileNet_v1_roi_conv_head(MobileNet_roi_conv_head): def __init__(self, dim_in, roi_xform_func, spatial_scale): super().__init__(dim_in, roi_xform_func, spatial_scale) tmp_conv_def = V1_CONV_DEFS[12:] tmp_conv_def[0] = tmp_conv_def[0]._replace(stride=self.stride_init) (self....
class MobileNet_v2_roi_conv_head(MobileNet_roi_conv_head): def __init__(self, dim_in, roi_xform_func, spatial_scale): super().__init__(dim_in, roi_xform_func, spatial_scale) tmp_conv_def = V2_CONV_DEFS[6:] tmp_conv_def[0] = tmp_conv_def[0]._replace(stride=self.stride_init) (self.c...
def freeze_bn(m): classname = m.__class__.__name__ if (classname.find('BatchNorm') != (- 1)): m.eval() freeze_params(m)
class Conv2d_tf(nn.Conv2d): def __init__(self, *args, **kwargs): super(Conv2d_tf, self).__init__(*args, **kwargs) self.padding = kwargs.get('padding', 'SAME') kwargs['padding'] = 0 if (not isinstance(self.stride, Iterable)): self.stride = (self.stride, self.stride) ...
def _make_divisible(v, divisor, min_value=None): if (min_value is None): min_value = divisor new_v = max(min_value, ((int((v + (divisor / 2))) // divisor) * divisor)) if (new_v < (0.9 * v)): new_v += divisor return new_v
def depth_multiplier_v2(depth, multiplier, divisible_by=8, min_depth=8): d = depth return _make_divisible((d * multiplier), divisible_by, min_depth)
class _conv_bn(nn.Module): def __init__(self, inp, oup, kernel, stride): super(_conv_bn, self).__init__() self.conv = nn.Sequential(Conv2d(inp, oup, kernel, stride, 1, bias=False), nn.BatchNorm2d(oup), nn.ReLU6(inplace=True)) self.depth = oup def forward(self, x): return self...
class _conv_dw(nn.Module): def __init__(self, inp, oup, stride): super(_conv_dw, self).__init__() self.conv = nn.Sequential(nn.Sequential(Conv2d(inp, inp, 3, stride, 1, groups=inp, bias=False), nn.BatchNorm2d(inp), nn.ReLU6(inplace=True)), nn.Sequential(Conv2d(inp, oup, 1, 1, 0, bias=False), nn.B...
class _inverted_residual_bottleneck(nn.Module): def __init__(self, inp, oup, stride, expand_ratio): super(_inverted_residual_bottleneck, self).__init__() self.use_res_connect = ((stride == 1) and (inp == oup)) self.conv = nn.Sequential((nn.Sequential(Conv2d(inp, (inp * expand_ratio), 1, 1...
def mobilenet_base(conv_defs=V1_CONV_DEFS, depth=(lambda x: x), in_channels=3): layers = [] for conv_def in conv_defs: if isinstance(conv_def, Conv): layers += [_conv_bn(in_channels, depth(conv_def.depth), conv_def.kernel, conv_def.stride)] in_channels = depth(conv_def.depth) ...
class MobileNet(nn.Module): def __init__(self, version='1', depth_multiplier=1.0, min_depth=8, num_classes=1001, dropout=0.2): super(MobileNet, self).__init__() self.dropout = dropout conv_defs = (V1_CONV_DEFS if (version == '1') else V2_CONV_DEFS) if (version == '1'): ...
def ResNet50_conv4_body(): return ResNet_convX_body((3, 4, 6))
def ResNet50_conv5_body(): return ResNet_convX_body((3, 4, 6, 3))
def ResNet101_conv4_body(): return ResNet_convX_body((3, 4, 23))
def ResNet101_conv5_body(): return ResNet_convX_body((3, 4, 23, 3))
def ResNet152_conv5_body(): return ResNet_convX_body((3, 8, 36, 3))
class ResNet_convX_body(nn.Module): def __init__(self, block_counts): super().__init__() self.block_counts = block_counts self.convX = (len(block_counts) + 1) self.num_layers = (((sum(block_counts) + (3 * (self.convX == 4))) * 3) + 2) self.res1 = globals()[cfg.RESNETS.STEM...
class ResNet_roi_conv5_head(nn.Module): def __init__(self, dim_in, roi_xform_func, spatial_scale): super().__init__() self.roi_xform = roi_xform_func self.spatial_scale = spatial_scale dim_bottleneck = (cfg.RESNETS.NUM_GROUPS * cfg.RESNETS.WIDTH_PER_GROUP) stride_init = (c...
def add_stage(inplanes, outplanes, innerplanes, nblocks, dilation=1, stride_init=2): 'Make a stage consist of `nblocks` residual blocks.\n Returns:\n - stage module: an nn.Sequentail module of residual blocks\n - final output dimension\n ' res_blocks = [] stride = stride_init for _...
def add_residual_block(inplanes, outplanes, innerplanes, dilation, stride): 'Return a residual block module, including residual connection, ' if ((stride != 1) or (inplanes != outplanes)): shortcut_func = globals()[cfg.RESNETS.SHORTCUT_FUNC] downsample = shortcut_func(inplanes, outplanes, stri...
def basic_bn_shortcut(inplanes, outplanes, stride): return nn.Sequential(nn.Conv2d(inplanes, outplanes, kernel_size=1, stride=stride, bias=False), mynn.AffineChannel2d(outplanes))
def basic_gn_shortcut(inplanes, outplanes, stride): return nn.Sequential(nn.Conv2d(inplanes, outplanes, kernel_size=1, stride=stride, bias=False), nn.GroupNorm(net_utils.get_group_gn(outplanes), outplanes, eps=cfg.GROUP_NORM.EPSILON))
def basic_bn_stem(): return nn.Sequential(OrderedDict([('conv1', nn.Conv2d(3, 64, 7, stride=2, padding=3, bias=False)), ('bn1', mynn.AffineChannel2d(64)), ('relu', nn.ReLU(inplace=True)), ('maxpool', nn.MaxPool2d(kernel_size=3, stride=2, padding=1))]))
def basic_gn_stem(): return nn.Sequential(OrderedDict([('conv1', nn.Conv2d(3, 64, 7, stride=2, padding=3, bias=False)), ('gn1', nn.GroupNorm(net_utils.get_group_gn(64), 64, eps=cfg.GROUP_NORM.EPSILON)), ('relu', nn.ReLU(inplace=True)), ('maxpool', nn.MaxPool2d(kernel_size=3, stride=2, padding=1))]))
class bottleneck_transformation(nn.Module): ' Bottleneck Residual Block ' def __init__(self, inplanes, outplanes, innerplanes, stride=1, dilation=1, group=1, downsample=None): super().__init__() (str1x1, str3x3) = ((stride, 1) if cfg.RESNETS.STRIDE_1X1 else (1, stride)) self.stride = ...
class bottleneck_gn_transformation(nn.Module): expansion = 4 def __init__(self, inplanes, outplanes, innerplanes, stride=1, dilation=1, group=1, downsample=None): super().__init__() (str1x1, str3x3) = ((stride, 1) if cfg.RESNETS.STRIDE_1X1 else (1, stride)) self.stride = stride ...
def residual_stage_detectron_mapping(module_ref, module_name, num_blocks, res_id): 'Construct weight mapping relation for a residual stage with `num_blocks` of\n residual blocks given the stage id: `res_id`\n ' if cfg.RESNETS.USE_GN: norm_suffix = '_gn' else: norm_suffix = '_bn' ...
def freeze_params(m): 'Freeze all the weights by setting requires_grad to False\n ' for p in m.parameters(): p.requires_grad = False
def vgg_detectron_weight_mapping(model): mapping_to_detectron = {} for k in model.state_dict(): if ('.weight' in k): mapping_to_detectron.update({k: k.replace('.weight', '_w')}) if ('.bias' in k): mapping_to_detectron.update({k: k.replace('.bias', '_b')}) orphan_in_...
class VGG16_conv5_body(nn.Module): def __init__(self): super().__init__() cfg = [[64, 64, 'M'], [128, 128, 'M'], [256, 256, 256, 'M'], [512, 512, 512, 'M'], [512, 512, 512]] dim_in = 3 for i in range(len(cfg)): for j in range(len(cfg[i])): if (cfg[i][j]...
class VGG16_roi_fc_head(nn.Module): def __init__(self, dim_in, roi_xform_func, spatial_scale): super().__init__() self.roi_xform = roi_xform_func self.spatial_scale = spatial_scale self.fc6 = nn.Linear(((dim_in * 7) * 7), 4096) self.fc7 = nn.Linear(4096, 4096) self...
class SpatialCrossMapLRN(nn.Module): def __init__(self, local_size=1, alpha=1.0, beta=0.75, k=1, ACROSS_CHANNELS=True): super(SpatialCrossMapLRN, self).__init__() self.ACROSS_CHANNELS = ACROSS_CHANNELS if ACROSS_CHANNELS: self.average = nn.AvgPool3d(kernel_size=(local_size, 1,...
class LambdaBase(nn.Sequential): def __init__(self, fn, *args): super(LambdaBase, self).__init__(*args) self.lambda_func = fn def forward_prepare(self, input): output = [] for module in self._modules.values(): output.append(module(input)) return (output if...
class Lambda(LambdaBase): def forward(self, input): return self.lambda_func(self.forward_prepare(input))
class VGGM_conv5_body(nn.Module): def __init__(self): super().__init__() self.conv1 = nn.Conv2d(3, 96, (7, 7), (2, 2)) self.relu1 = nn.ReLU(True) self.norm1 = SpatialCrossMapLRN(5, 0.0005, 0.75, 2) self.pool1 = nn.MaxPool2d((3, 3), (2, 2), (0, 0), ceil_mode=True) s...
class VGGM_roi_fc_head(nn.Module): def __init__(self, dim_in, roi_xform_func, spatial_scale): super().__init__() self.roi_xform = roi_xform_func self.spatial_scale = spatial_scale self.fc6 = nn.Linear(((dim_in * 6) * 6), 4096) self.fc7 = nn.Linear(4096, 4096) self....
class keypoint_outputs(nn.Module): 'Mask R-CNN keypoint specific outputs: keypoint heatmaps.' def __init__(self, dim_in): super().__init__() self.upsample_heatmap = (cfg.KRCNN.UP_SCALE > 1) if cfg.KRCNN.USE_DECONV: self.deconv = nn.ConvTranspose2d(dim_in, cfg.KRCNN.DECONV_...
def keypoint_losses(kps_pred, keypoint_locations_int32, keypoint_weights, keypoint_loss_normalizer=None): 'Mask R-CNN keypoint specific losses.' device_id = kps_pred.get_device() kps_target = Variable(torch.from_numpy(keypoint_locations_int32.astype('int64'))).cuda(device_id) keypoint_weights = Variab...
class roi_pose_head_v1convX(nn.Module): 'Mask R-CNN keypoint head. v1convX design: X * (conv).' def __init__(self, dim_in, roi_xform_func, spatial_scale): super().__init__() self.dim_in = dim_in self.roi_xform = roi_xform_func self.spatial_scale = spatial_scale hidden_...
class mask_rcnn_outputs(nn.Module): 'Mask R-CNN specific outputs: either mask logits or probs.' def __init__(self, dim_in): super().__init__() self.dim_in = dim_in n_classes = (cfg.MODEL.NUM_CLASSES if cfg.MRCNN.CLS_SPECIFIC_MASK else 1) if cfg.MRCNN.USE_FC_OUTPUT: ...
def mask_rcnn_losses(masks_pred, masks_int32): 'Mask R-CNN specific losses.' (n_rois, n_classes, _, _) = masks_pred.size() device_id = masks_pred.get_device() masks_gt = Variable(torch.from_numpy(masks_int32.astype('float32'))).cuda(device_id) weight = (masks_gt > (- 1)).float() loss = F.binar...
def mask_rcnn_fcn_head_v1up4convs(dim_in, roi_xform_func, spatial_scale): 'v1up design: 4 * (conv 3x3), convT 2x2.' return mask_rcnn_fcn_head_v1upXconvs(dim_in, roi_xform_func, spatial_scale, 4)
def mask_rcnn_fcn_head_v1up4convs_gn(dim_in, roi_xform_func, spatial_scale): 'v1up design: 4 * (conv 3x3), convT 2x2, with GroupNorm' return mask_rcnn_fcn_head_v1upXconvs_gn(dim_in, roi_xform_func, spatial_scale, 4)