code stringlengths 17 6.64M |
|---|
def resnet18(in_channels=3, pretrained=False, progress=True, **kwargs):
'ResNet-18 model from\n `"Deep Residual Learning for Image Recognition" <https://arxiv.org/pdf/1512.03385.pdf>`_\n\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n progress (bool): If True, d... |
def resnet34(in_channels=3, pretrained=False, progress=True, **kwargs):
'ResNet-34 model from\n `"Deep Residual Learning for Image Recognition" <https://arxiv.org/pdf/1512.03385.pdf>`_\n\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n progress (bool): If True, d... |
def resnet50(in_channels=3, pretrained=False, progress=True, **kwargs):
'ResNet-50 model from\n `"Deep Residual Learning for Image Recognition" <https://arxiv.org/pdf/1512.03385.pdf>`_\n\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n progress (bool): If True, d... |
def resnet101(in_channels=3, pretrained=False, progress=True, **kwargs):
'ResNet-101 model from\n `"Deep Residual Learning for Image Recognition" <https://arxiv.org/pdf/1512.03385.pdf>`_\n\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n progress (bool): If True,... |
def resnet152(in_channels=3, pretrained=False, progress=True, **kwargs):
'ResNet-152 model from\n `"Deep Residual Learning for Image Recognition" <https://arxiv.org/pdf/1512.03385.pdf>`_\n\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n progress (bool): If True,... |
def resnext50_32x4d(in_channels=3, pretrained=False, progress=True, **kwargs):
'ResNeXt-50 32x4d model from\n `"Aggregated Residual Transformation for Deep Neural Networks" <https://arxiv.org/pdf/1611.05431.pdf>`_\n\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n ... |
def resnext101_32x8d(in_channels=3, pretrained=False, progress=True, **kwargs):
'ResNeXt-101 32x8d model from\n `"Aggregated Residual Transformation for Deep Neural Networks" <https://arxiv.org/pdf/1611.05431.pdf>`_\n\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n ... |
def wide_resnet50_2(in_channels=3, pretrained=False, progress=True, **kwargs):
'Wide ResNet-50-2 model from\n `"Wide Residual Networks" <https://arxiv.org/pdf/1605.07146.pdf>`_\n\n The model is the same as ResNet except for the bottleneck number of channels\n which is twice larger in every block. The num... |
def wide_resnet101_2(in_channels=3, pretrained=False, progress=True, **kwargs):
'Wide ResNet-101-2 model from\n `"Wide Residual Networks" <https://arxiv.org/pdf/1605.07146.pdf>`_\n\n The model is the same as ResNet except for the bottleneck number of channels\n which is twice larger in every block. The n... |
class ImageEncoder(nn.Module):
def __init__(self):
super(ImageEncoder, self).__init__()
self.backbone = resnet34(in_channels=3, pretrained=False, progress=True)
'input_mesh_np = np.meshgrid(np.linspace(start=0, stop=self.opt.img_W - 1, num=self.opt.img_W),\n ... |
class ResidualConv(nn.Module):
def __init__(self, inplanes, planes, stride=1, kernel_1=False):
super(ResidualConv, self).__init__()
self.conv1 = conv3x3(inplanes, planes, stride)
self.bn1 = nn.BatchNorm2d(planes)
self.relu = nn.ReLU(inplace=True)
self.conv2 = conv3x3(plane... |
class attention_pc2img(nn.Module):
def __init__(self, in_channel, output_channel):
super(attention_pc2img, self).__init__()
'self.conv=nn.Sequential(nn.Conv2d(in_channel,in_channel,1),nn.BatchNorm2d(in_channel),nn.ReLU(),\n nn.Conv2d(in_channel,in_channel,1),nn.Batc... |
class ImageUpSample(nn.Module):
def __init__(self, in_channel, output_channel):
super(ImageUpSample, self).__init__()
self.up = nn.Upsample(scale_factor=2, mode='bilinear', align_corners=False)
self.conv = nn.Sequential(ResidualConv(in_channel, output_channel), ResidualConv(output_channel... |
def desc_loss(img_features, pc_features, mask, pos_margin=0.1, neg_margin=1.4, log_scale=10, num_kpt=512):
pos_mask = mask
neg_mask = (1 - mask)
dists = (1 - torch.sum((img_features.unsqueeze((- 1)) * pc_features.unsqueeze((- 2))), dim=1))
pos = (dists - (100000.0 * neg_mask))
pos_weight = (pos - ... |
def desc_loss2(img_features, pc_features, mask, pos_margin=0.1, neg_margin=1.4, log_scale=10, num_kpt=512):
pos_mask = mask
neg_mask = (1 - mask)
dists = (1 - torch.sum((img_features.unsqueeze((- 1)) * pc_features.unsqueeze((- 2))), dim=1))
pos = (dists - (100000.0 * neg_mask))
pos_weight = (pos -... |
def det_loss(img_score_inline, img_score_outline, pc_score_inline, pc_score_outline, dists, mask):
pids = torch.FloatTensor(np.arange(mask.size((- 1)))).to(mask.device)
diag_mask = torch.eq(torch.unsqueeze(pids, dim=1), torch.unsqueeze(pids, dim=0)).unsqueeze(0).expand(mask.size()).float()
(furthest_posit... |
def det_loss2(img_score_inline, img_score_outline, pc_score_inline, pc_score_outline, dists, mask):
pids = torch.FloatTensor(np.arange(mask.size((- 1)))).to(mask.device)
diag_mask = torch.eq(torch.unsqueeze(pids, dim=1), torch.unsqueeze(pids, dim=0)).unsqueeze(0).expand(mask.size()).float()
(furthest_posi... |
def cal_acc(img_features, pc_features, mask):
dist = torch.sum(((img_features.unsqueeze((- 1)) - pc_features.unsqueeze((- 2))) ** 2), dim=1)
(furthest_positive, _) = torch.max((dist * mask), dim=1)
(closest_negative, _) = torch.min((dist + (100000.0 * mask)), dim=1)
'print(furthest_positive)\n prin... |
class CorrI2P(nn.Module):
def __init__(self, opt: Options):
super(CorrI2P, self).__init__()
self.opt = opt
self.pc_encoder = pointnet2.PCEncoder(opt, Ca=64, Cb=256, Cg=512)
self.img_encoder = imagenet.ImageEncoder()
self.H_fine_res = int(round((self.opt.img_H / self.opt.im... |
class Options():
def __init__(self):
self.dataroot = '/extssd/jiaxin/nuscenes'
self.checkpoints_dir = 'checkpoints'
self.version = '3.3'
self.is_debug = False
self.is_fine_resolution = True
self.is_remove_ground = False
self.accumulation_frame_num = 3
... |
def config_factory(configuration_name: str) -> Union[(DetectionConfig, TrackingConfig)]:
'\n Creates a *Config instance that can be used to initialize a *Eval instance, where * stands for Detection/Tracking.\n Note that this only works if the config file is located in the nuscenes/eval/common/configs folder... |
class EvalBox(abc.ABC):
' Abstract base class for data classes used during detection evaluation. Can be a prediction or ground truth.'
def __init__(self, sample_token: str='', translation: Tuple[(float, float, float)]=(0, 0, 0), size: Tuple[(float, float, float)]=(0, 0, 0), rotation: Tuple[(float, float, flo... |
class EvalBoxes():
' Data class that groups EvalBox instances by sample. '
def __init__(self):
'\n Initializes the EvalBoxes for GT or predictions.\n '
self.boxes = defaultdict(list)
def __repr__(self):
return 'EvalBoxes with {} boxes across {} samples'.format(len(s... |
class MetricData(abc.ABC):
' Abstract base class for the *MetricData classes specific to each task. '
@abc.abstractmethod
def serialize(self):
' Serialize instance into json-friendly format. '
pass
@classmethod
@abc.abstractmethod
def deserialize(cls, content: dict):
... |
def load_prediction(result_path: str, max_boxes_per_sample: int, box_cls, verbose: bool=False) -> Tuple[(EvalBoxes, Dict)]:
'\n Loads object predictions from file.\n :param result_path: Path to the .json result file provided by the user.\n :param max_boxes_per_sample: Maximim number of boxes allowed per ... |
def load_gt(nusc: NuScenes, eval_split: str, box_cls, verbose: bool=False) -> EvalBoxes:
'\n Loads ground truth boxes from DB.\n :param nusc: A NuScenes instance.\n :param eval_split: The evaluation split for which we load GT boxes.\n :param box_cls: Type of box to load, e.g. DetectionBox or TrackingB... |
def add_center_dist(nusc: NuScenes, eval_boxes: EvalBoxes):
'\n Adds the cylindrical (xy) center distance from ego vehicle to each box.\n :param nusc: The NuScenes instance.\n :param eval_boxes: A set of boxes, either GT or predictions.\n :return: eval_boxes augmented with center distances.\n '
... |
def filter_eval_boxes(nusc: NuScenes, eval_boxes: EvalBoxes, max_dist: Dict[(str, float)], verbose: bool=False) -> EvalBoxes:
'\n Applies filtering to boxes. Distance, bike-racks and points per box.\n :param nusc: An instance of the NuScenes class.\n :param eval_boxes: An instance of the EvalBoxes class.... |
def _get_box_class_field(eval_boxes: EvalBoxes) -> str:
'\n Retrieve the name of the class field in the boxes.\n This parses through all boxes until it finds a valid box.\n If there are no valid boxes, this function throws an exception.\n :param eval_boxes: The EvalBoxes used for evaluation.\n :ret... |
def setup_axis(xlabel: str=None, ylabel: str=None, xlim: int=None, ylim: int=None, title: str=None, min_precision: float=None, min_recall: float=None, ax: Axis=None, show_spines: str='none'):
"\n Helper method that sets up the axis for a plot.\n :param xlabel: x label text.\n :param ylabel: y label text.... |
def center_distance(gt_box: EvalBox, pred_box: EvalBox) -> float:
'\n L2 distance between the box centers (xy only).\n :param gt_box: GT annotation sample.\n :param pred_box: Predicted sample.\n :return: L2 distance.\n '
return np.linalg.norm((np.array(pred_box.translation[:2]) - np.array(gt_bo... |
def velocity_l2(gt_box: EvalBox, pred_box: EvalBox) -> float:
'\n L2 distance between the velocity vectors (xy only).\n If the predicted velocities are nan, we return inf, which is subsequently clipped to 1.\n :param gt_box: GT annotation sample.\n :param pred_box: Predicted sample.\n :return: L2 d... |
def yaw_diff(gt_box: EvalBox, eval_box: EvalBox, period: float=(2 * np.pi)) -> float:
'\n Returns the yaw angle difference between the orientation of two boxes.\n :param gt_box: Ground truth box.\n :param eval_box: Predicted box.\n :param period: Periodicity in radians for assessing angle difference.\... |
def angle_diff(x: float, y: float, period: float) -> float:
'\n Get the smallest angle difference between 2 angles: the angle from y to x.\n :param x: To angle.\n :param y: From angle.\n :param period: Periodicity in radians for assessing angle difference.\n :return: <float>. Signed smallest betwee... |
def attr_acc(gt_box: DetectionBox, pred_box: DetectionBox) -> float:
'\n Computes the classification accuracy for the attribute of this class (if any).\n If the GT class has no attributes or the annotation is missing attributes, we assign an accuracy of nan, which is\n ignored later on.\n :param gt_bo... |
def scale_iou(sample_annotation: EvalBox, sample_result: EvalBox) -> float:
'\n This method compares predictions to the ground truth in terms of scale.\n It is equivalent to intersection over union (IOU) between the two boxes in 3D,\n if we assume that the boxes are aligned, i.e. translation and rotation... |
def quaternion_yaw(q: Quaternion) -> float:
'\n Calculate the yaw angle from a quaternion.\n Note that this only works for a quaternion that represents a box in lidar or global coordinate frame.\n It does not work for a box in the camera frame.\n :param q: Quaternion of interest.\n :return: Yaw ang... |
def boxes_to_sensor(boxes: List[EvalBox], pose_record: Dict, cs_record: Dict):
"\n Map boxes from global coordinates to the vehicle's sensor coordinate system.\n :param boxes: The boxes in global coordinates.\n :param pose_record: The pose record of the vehicle at the current timestamp.\n :param cs_re... |
def cummean(x: np.array) -> np.array:
'\n Computes the cumulative mean up to each position in a NaN sensitive way\n - If all values are NaN return an array of ones.\n - If some values are NaN, accumulate arrays discording those entries.\n '
if (sum(np.isnan(x)) == len(x)):
return np.ones(l... |
def accumulate(gt_boxes: EvalBoxes, pred_boxes: EvalBoxes, class_name: str, dist_fcn: Callable, dist_th: float, verbose: bool=False) -> DetectionMetricData:
'\n Average Precision over predefined different recall thresholds for a single distance threshold.\n The recall/conf thresholds and other raw metrics w... |
def calc_ap(md: DetectionMetricData, min_recall: float, min_precision: float) -> float:
' Calculated average precision. '
assert (0 <= min_precision < 1)
assert (0 <= min_recall <= 1)
prec = np.copy(md.precision)
prec = prec[(round((100 * min_recall)) + 1):]
prec -= min_precision
prec[(pre... |
def calc_tp(md: DetectionMetricData, min_recall: float, metric_name: str) -> float:
' Calculates true positive errors. '
first_ind = (round((100 * min_recall)) + 1)
last_ind = md.max_recall_ind
if (last_ind < first_ind):
return 1.0
else:
return float(np.mean(getattr(md, metric_name... |
def config_factory(configuration_name: str) -> DetectionConfig:
'\n Creates a DetectionConfig instance that can be used to initialize a NuScenesEval instance.\n Note that this only works if the config file is located in the nuscenes/eval/detection/configs folder.\n :param configuration_name: Name of desi... |
class DetectionConfig():
' Data class that specifies the detection evaluation settings. '
def __init__(self, class_range: Dict[(str, int)], dist_fcn: str, dist_ths: List[float], dist_th_tp: float, min_recall: float, min_precision: float, max_boxes_per_sample: int, mean_ap_weight: int):
assert (set(cl... |
class DetectionMetricData(MetricData):
' This class holds accumulated and interpolated data required to calculate the detection metrics. '
nelem = 101
def __init__(self, recall: np.array, precision: np.array, confidence: np.array, trans_err: np.array, vel_err: np.array, scale_err: np.array, orient_err: n... |
class DetectionMetrics():
' Stores average precision and true positive metric results. Provides properties to summarize. '
def __init__(self, cfg: DetectionConfig):
self.cfg = cfg
self._label_aps = defaultdict((lambda : defaultdict(float)))
self._label_tp_errors = defaultdict((lambda ... |
class DetectionBox(EvalBox):
' Data class used during detection evaluation. Can be a prediction or ground truth.'
def __init__(self, sample_token: str='', translation: Tuple[(float, float, float)]=(0, 0, 0), size: Tuple[(float, float, float)]=(0, 0, 0), rotation: Tuple[(float, float, float, float)]=(0, 0, 0,... |
class DetectionMetricDataList():
' This stores a set of MetricData in a dict indexed by (name, match-distance). '
def __init__(self):
self.md = {}
def __getitem__(self, key):
return self.md[key]
def __eq__(self, other):
eq = True
for key in self.md.keys():
... |
class DetectionEval():
'\n This is the official nuScenes detection evaluation code.\n Results are written to the provided output_dir.\n\n nuScenes uses the following detection metrics:\n - Mean Average Precision (mAP): Uses center-distance as matching criterion; averaged over distance thresholds.\n ... |
class NuScenesEval(DetectionEval):
'\n Dummy class for backward-compatibility. Same as DetectionEval.\n '
|
class TestAlgo(unittest.TestCase):
cfg = config_factory('detection_cvpr_2019')
@staticmethod
def _mock_results(nsamples, ngt, npred, detection_name):
def random_attr():
'\n This is the most straight-forward way to generate a random attribute.\n Not currently use... |
def get_metric_data(gts: Dict[(str, List[Dict])], preds: Dict[(str, List[Dict])], detection_name: str, dist_th: float) -> DetectionMetricData:
'\n Calculate and check the AP value.\n :param gts: Ground truth data.\n :param preds: Predictions.\n :param detection_name: Name of the class ... |
class TestAPSimple(unittest.TestCase):
' Tests the correctness of AP calculation for simple cases. '
def setUp(self):
self.car1 = {'trans': (1, 1, 1), 'name': 'car', 'score': 1.0}
self.car2 = {'trans': (3, 3, 1), 'name': 'car', 'score': 0.7}
self.bicycle1 = {'trans': (5, 5, 1), 'name'... |
class TestTPSimple(unittest.TestCase):
' Tests the correctness of true positives metrics calculation for simple cases. '
def setUp(self):
self.car3 = {'trans': (3, 3, 1), 'size': (2, 4, 2), 'rot': Quaternion(axis=(0, 0, 1), angle=0), 'score': 1.0}
self.car4 = {'trans': (3, 3, 1), 'size': (2, ... |
class TestDetectionConfig(unittest.TestCase):
def test_serialization(self):
' test that instance serialization protocol works with json encoding '
this_dir = os.path.dirname(os.path.abspath(__file__))
cfg_name = 'detection_cvpr_2019'
config_path = os.path.join(this_dir, '..', 'con... |
class TestDetectionBox(unittest.TestCase):
def test_serialization(self):
' Test that instance serialization protocol works with json encoding. '
box = DetectionBox()
recovered = DetectionBox.deserialize(json.loads(json.dumps(box.serialize())))
self.assertEqual(box, recovered)
|
class TestEvalBoxes(unittest.TestCase):
def test_serialization(self):
' Test that instance serialization protocol works with json encoding. '
boxes = EvalBoxes()
for i in range(10):
boxes.add_boxes(str(i), [DetectionBox(), DetectionBox(), DetectionBox()])
recovered = E... |
class TestMetricData(unittest.TestCase):
def test_serialization(self):
' Test that instance serialization protocol works with json encoding. '
md = DetectionMetricData.random_md()
recovered = DetectionMetricData.deserialize(json.loads(json.dumps(md.serialize())))
self.assertEqual(... |
class TestDetectionMetricDataList(unittest.TestCase):
def test_serialization(self):
' Test that instance serialization protocol works with json encoding. '
mdl = DetectionMetricDataList()
for i in range(10):
mdl.set('name', 0.1, DetectionMetricData.random_md())
recover... |
class TestDetectionMetrics(unittest.TestCase):
def test_serialization(self):
' Test that instance serialization protocol works with json encoding. '
cfg = {'class_range': {'car': 1.0, 'truck': 1.0, 'bus': 1.0, 'trailer': 1.0, 'construction_vehicle': 1.0, 'pedestrian': 1.0, 'motorcycle': 1.0, 'bic... |
class TestMain(unittest.TestCase):
res_mockup = 'nusc_eval.json'
res_eval_folder = 'tmp'
def tearDown(self):
if os.path.exists(self.res_mockup):
os.remove(self.res_mockup)
if os.path.exists(self.res_eval_folder):
shutil.rmtree(self.res_eval_folder)
@staticmeth... |
class TestLoader(unittest.TestCase):
def test_filter_eval_boxes(self):
'\n This tests runs the evaluation for an arbitrary random set of predictions.\n This score is then captured in this very test such that if we change the eval code,\n this test will trigger if the results changed.... |
class TestEval(unittest.TestCase):
def test_scale_iou(self):
'Test valid and invalid inputs for scale_iou().'
sa = DetectionBox(size=(4, 4, 4))
sr = DetectionBox(size=(4, 4, 4))
res = scale_iou(sa, sr)
self.assertEqual(res, 1)
sa = DetectionBox(size=(2, 2, 2))
... |
def category_to_detection_name(category_name: str) -> Optional[str]:
'\n Default label mapping from nuScenes to nuScenes detection classes.\n Note that pedestrian does not include personal_mobility, stroller and wheelchair.\n :param category_name: Generic nuScenes class.\n :return: nuScenes detection ... |
def detection_name_to_rel_attributes(detection_name: str) -> List[str]:
'\n Returns a list of relevant attributes for a given detection class.\n :param detection_name: The detection class.\n :return: List of relevant attributes.\n '
if (detection_name in ['pedestrian']):
rel_attributes = [... |
class LidarSegEval():
'\n This is the official nuScenes-lidarseg evaluation code.\n Results are written to the provided output_dir.\n\n nuScenes-lidarseg uses the following metrics:\n - Mean Intersection-over-Union (mIOU): We use the well-known IOU metric, which is defined as TP / (TP + FP + FN).\n ... |
def validate_submission(nusc: NuScenes, results_folder: str, eval_set: str, verbose: bool=False, zip_out: str=None) -> None:
'\n Checks if a results folder is valid. The following checks are performed:\n - Check that the submission folder is according to that described in\n https://github.com/nutonomy/... |
def prepare_files(method_names: List[str], root_dir: str) -> None:
'\n Prepare the files containing the predictions of the various method names.\n :param method_names: A list of method names.\n :param root_dir: The directory where the predictions of the various methods are stored at.\n '
for metho... |
def get_prediction_json_path(prediction_dir: str) -> str:
'\n Get the name of the json file in a directory (abort if there is more than one).\n :param prediction_dir: Path to the directory to check for the json file.\n :return: Absolute path to the json file.\n '
files_in_dir = os.listdir(predicti... |
def panop_baselines_from_lidarseg_detect_track(out_dir: str, lidarseg_preds_dir: str, lidarseg_method_names: List[str], det_or_track_preds_dir: str, det_or_track_method_names: List[str], task: str='tracking', version: str='v1.0-test', dataroot: str='/data/sets/nuscenes', n_jobs: int=(- 1), verbose: bool=False) -> Non... |
def generate_and_evaluate_baseline(out_dir: str, lidarseg_preds_dir: str, lidarseg_method_name: str, det_or_track_preds_dir: str, det_or_track_method_name: str, task: str='tracking', version: str='v1.0-test', dataroot: str='/data/sets/nuscenes', verbose: bool=False) -> None:
'\n Generate panoptic predictions b... |
class NuScenesPanopticEval():
'\n This is the official Panoptic nuScenes evaluation code. Results are written to the provided output_dir.\n Panoptic nuScenes uses the following metrics:\n - Panoptic Segmentation: we use the PQ (Panoptic Quality) metric: which is defined as:\n PQ = IOU/(TP + 0.5*FP +... |
def main():
parser = argparse.ArgumentParser(description='Evaluate Panoptic nuScenes results.')
parser.add_argument('--result_path', type=str, help='The path to the results folder.')
parser.add_argument('--eval_set', type=str, default='val', help='Which dataset split to evaluate on, train, val or test.')
... |
class PanopticTrackingEval(PanopticEval):
' Panoptic tracking evaluator'
def __init__(self, n_classes: int, min_stuff_cls_id: int, ignore: List[int]=None, offset: int=(2 ** 32), min_points: int=30, iou_thr: float=0.5):
'\n :param n_classes: Number of classes.\n :param min_stuff_cls_id: ... |
class PanopticClassMapper(LidarsegClassMapper):
"\n Maps the general (fine) classes to the challenge (coarse) classes in the Panoptic nuScenes challenge.\n\n Example usage::\n nusc_ = NuScenes(version='v1.0-mini', dataroot='/data/sets/nuscenes', verbose=True)\n mapper_ = PanopticClassMapper(nu... |
def main(version: str, data_root: str, split_name: str, output_dir: str, config_name: str='predict_2020_icra.json') -> None:
'\n Performs inference for all of the baseline models defined in the physics model module.\n :param version: nuScenes dataset version.\n :param data_root: Directory where the NuSce... |
def compute_metrics(predictions: List[Dict[(str, Any)]], helper: PredictHelper, config: PredictionConfig) -> Dict[(str, Any)]:
'\n Computes metrics from a set of predictions.\n :param predictions: List of prediction JSON objects.\n :param helper: Instance of PredictHelper that wraps the nuScenes val set.... |
def main(version: str, data_root: str, submission_path: str, config_name: str='predict_2020_icra.json') -> None:
'\n Computes metrics for a submission stored in submission_path with a given submission_name with the metrics\n specified by the config_name.\n :param version: nuScenes dataset version.\n :... |
class PredictionConfig():
def __init__(self, metrics: List[Metric], seconds: int=6, frequency: int=2):
'\n Data class that specifies the prediction evaluation settings.\n Initialized with:\n metrics: List of nuscenes.eval.prediction.metric.Metric objects.\n seconds: Number of ... |
def load_prediction_config(helper: PredictHelper, config_name: str='predict_2020_icra.json') -> PredictionConfig:
'\n Loads a PredictionConfig from json file stored in eval/prediction/configs.\n :param helper: Instance of PredictHelper. Needed for OffRoadRate metric.\n :param config_name: Name of json co... |
class Prediction(MetricData):
'\n Stores predictions of Models.\n Metrics are calculated from Predictions.\n\n Attributes:\n instance: Instance token for prediction.\n sample: Sample token for prediction.\n prediction: Prediction of model [num_modes, n_timesteps, state_dim].\n ... |
def get_prediction_challenge_split(split: str, dataroot: str='/data/sets/nuscenes') -> List[str]:
"\n Gets a list of {instance_token}_{sample_token} strings for each split.\n :param split: One of 'mini_train', 'mini_val', 'train', 'val'.\n :param dataroot: Path to the nuScenes dataset.\n :return: List... |
def load_model(helper: PredictHelper, config: PredictionConfig, path_to_model_weights: str) -> Any:
' Loads model with desired weights. '
return ConstantVelocityHeading(config.seconds, helper)
|
def do_inference_for_submission(helper: PredictHelper, config: PredictionConfig, dataset_tokens: List[str]) -> List[Prediction]:
'\n Currently, this will make a submission with a constant velocity and heading model.\n Fill in all the code needed to run your model on the test set here. You do not need to wor... |
def main(version: str, data_root: str, split_name: str, output_dir: str, submission_name: str, config_name: str) -> None:
'\n Makes predictions for a submission to the nuScenes prediction challenge.\n :param version: NuScenes version.\n :param data_root: Directory storing NuScenes data.\n :param split... |
class TestPrediction(unittest.TestCase):
def test(self):
prediction = Prediction('instance', 'sample', np.ones((2, 2, 2)), np.zeros(2))
self.assertEqual(prediction.number_of_modes, 2)
self.assertDictEqual(prediction.serialize(), {'instance': 'instance', 'sample': 'sample', 'prediction': [... |
class TrackingEvaluation(object):
def __init__(self, tracks_gt: Dict[(str, Dict[(int, List[TrackingBox])])], tracks_pred: Dict[(str, Dict[(int, List[TrackingBox])])], class_name: str, dist_fcn: Callable, dist_th_tp: float, min_recall: float, num_thresholds: int, metric_worst: Dict[(str, float)], verbose: bool=Tr... |
class TrackingConfig():
' Data class that specifies the tracking evaluation settings. '
def __init__(self, tracking_names: List[str], pretty_tracking_names: Dict[(str, str)], tracking_colors: Dict[(str, str)], class_range: Dict[(str, int)], dist_fcn: str, dist_th_tp: float, min_recall: float, max_boxes_per_s... |
class TrackingMetricData(MetricData):
' This class holds accumulated and interpolated data required to calculate the tracking metrics. '
nelem = None
metrics = [m for m in list((set(TRACKING_METRICS) - set(AMOT_METRICS)))]
def __init__(self):
assert (TrackingMetricData.nelem is not None)
... |
class TrackingMetrics():
' Stores tracking metric results. Provides properties to summarize. '
def __init__(self, cfg: TrackingConfig):
self.cfg = cfg
self.eval_time = None
self.label_metrics: Dict[(str, Dict[(str, float)])] = {}
self.class_names = self.cfg.class_names
... |
class TrackingBox(EvalBox):
' Data class used during tracking evaluation. Can be a prediction or ground truth.'
def __init__(self, sample_token: str='', translation: Tuple[(float, float, float)]=(0, 0, 0), size: Tuple[(float, float, float)]=(0, 0, 0), rotation: Tuple[(float, float, float, float)]=(0, 0, 0, 0... |
class TrackingMetricDataList():
' This stores a set of MetricData in a dict indexed by name. '
def __init__(self):
self.md: Dict[(str, TrackingMetricData)] = {}
def __getitem__(self, key) -> TrackingMetricData:
return self.md[key]
def __eq__(self, other):
eq = True
f... |
class TrackingEval():
'\n This is the official nuScenes tracking evaluation code.\n Results are written to the provided output_dir.\n\n Here is an overview of the functions in this method:\n - init: Loads GT annotations and predictions stored in JSON format and filters the boxes.\n - run: Performs ... |
def interpolate_tracking_boxes(left_box: TrackingBox, right_box: TrackingBox, right_ratio: float) -> TrackingBox:
'\n Linearly interpolate box parameters between two boxes.\n :param left_box: A Trackingbox.\n :param right_box: Another TrackingBox\n :param right_ratio: Weight given to the right box.\n ... |
def interpolate_tracks(tracks_by_timestamp: DefaultDict[(int, List[TrackingBox])]) -> DefaultDict[(int, List[TrackingBox])]:
'\n Interpolate the tracks to fill in holes, especially since GT boxes with 0 lidar points are removed.\n This interpolation does not take into account visibility. It interpolates des... |
def create_tracks(all_boxes: EvalBoxes, nusc: NuScenes, eval_split: str, gt: bool) -> Dict[(str, Dict[(int, List[TrackingBox])])]:
'\n Returns all tracks for all scenes. Samples within a track are sorted in chronological order.\n This can be applied either to GT or predictions.\n :param all_boxes: Holds ... |
def track_initialization_duration(df: DataFrame, obj_frequencies: DataFrame) -> float:
"\n Computes the track initialization duration, which is the duration from the first occurrence of an object to\n it's first correct detection (TP).\n Note that this True Positive metric is undefined if there are no ma... |
def longest_gap_duration(df: DataFrame, obj_frequencies: DataFrame) -> float:
'\n Computes the longest gap duration, which is the longest duration of any gaps in the detection of an object.\n Note that this True Positive metric is undefined if there are no matched tracks.\n :param df: Motmetrics datafram... |
def motar(df: DataFrame, num_matches: int, num_misses: int, num_switches: int, num_false_positives: int, num_objects: int, alpha: float=1.0) -> float:
'\n Initializes a MOTAR class which refers to the modified MOTA metric at https://www.nuscenes.org/tracking.\n Note that we use the measured recall, which is... |
def mota_custom(df: DataFrame, num_misses: int, num_switches: int, num_false_positives: int, num_objects: int) -> float:
"\n Multiple object tracker accuracy.\n Based on py-motmetric's mota function.\n Compared to the original MOTA definition, we clip values below 0.\n :param df: Motmetrics dataframe ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.