project_name stringlengths 6 104 | file_name stringlengths 4 89 | full_name stringlengths 1 102 | func_name stringlengths 1 85 | docstring stringlengths 13 836 | docstring_tokens listlengths 4 122 | code stringlengths 23 39.7k | code_tokens stringlengths 29 44.6k | url int64 3 986k |
|---|---|---|---|---|---|---|---|---|
sek788432/Waymo-2D-Object-Detection | eval_util.py | top_k_by_class | top_k_by_class | Extracts the top k predictions for each video, sorted by class. | [
"Extracts",
"the",
"top",
"k",
"predictions",
"for",
"each",
"video,",
"sorted",
"by",
"class."
] | def top_k_by_class(predictions, labels, k=20):
if k <= 0:
raise ValueError('k must be a positive integer.')
k = min(k, predictions.shape[1])
num_classes = predictions.shape[1]
prediction_triplets = []
for video_index in range(predictions.shape[0]):
prediction_triplets.extend(top_k_tr... | ['def', 'top_k_by_class(predictions,', 'labels,', 'k=20):', 'if', 'k', '<=', '0:', 'raise', "ValueError('k", 'must', 'be', 'a', 'positive', "integer.')", 'k', '=', 'min(k,', 'predictions.shape[1])', 'num_classes', '=', 'predictions.shape[1]', 'prediction_triplets', '=', '[]', 'for', 'video_index', 'in', 'range(predicti... | 973,429 |
sek788432/Waymo-2D-Object-Detection | eval_util.py | EvaluationMetrics.accumulate | accumulate | Accumulate the metrics calculated locally for this mini-batch. | [
"Accumulate",
"the",
"metrics",
"calculated",
"locally",
"for",
"this",
"mini-batch."
] | def accumulate(self, predictions, labels):
(predictions, labels) = self._convert_to_numpy(predictions=predictions[0], groundtruths=labels[0])
batch_size = labels.shape[0]
mean_hit_at_one = calculate_hit_at_one(predictions, labels)
mean_perr = calculate_precision_at_equal_recall_rate(predictions, labels)... | ['def', 'accumulate(self,', 'predictions,', 'labels):', '(predictions,', 'labels)', '=', 'self._convert_to_numpy(predictions=predictions[0],', 'groundtruths=labels[0])', 'batch_size', '=', 'labels.shape[0]', 'mean_hit_at_one', '=', 'calculate_hit_at_one(predictions,', 'labels)', 'mean_perr', '=', 'calculate_precision_a... | 973,431 |
sek788432/Waymo-2D-Object-Detection | eval_util.py | EvaluationMetrics.clear | clear | Clear the evaluation metrics and reset the EvaluationMetrics object. | [
"Clear",
"the",
"evaluation",
"metrics",
"and",
"reset",
"the",
"EvaluationMetrics",
"object."
] | def clear(self):
self.sum_hit_at_one = 0.0
self.sum_perr = 0.0
self.map_calculator.clear()
self.global_ap_calculator.clear()
self.num_examples = 0 | ['def', 'clear(self):', 'self.sum_hit_at_one', '=', '0.0', 'self.sum_perr', '=', '0.0', 'self.map_calculator.clear()', 'self.global_ap_calculator.clear()', 'self.num_examples', '=', '0'] | 973,433 |
sek788432/Waymo-2D-Object-Detection | yt8m_agg_models.py | LogisticModel.create_model | create_model | Creates a logistic model. | [
"Creates",
"a",
"logistic",
"model."
] | def create_model(self, model_input, vocab_size, l2_penalty=1e-08):
output = layers.Dense(vocab_size, activation=tf.nn.sigmoid, kernel_regularizer=regularizers.l2(l2_penalty))(model_input)
return {'predictions': output} | ['def', 'create_model(self,', 'model_input,', 'vocab_size,', 'l2_penalty=1e-08):', 'output', '=', 'layers.Dense(vocab_size,', 'activation=tf.nn.sigmoid,', 'kernel_regularizer=regularizers.l2(l2_penalty))(model_input)', 'return', "{'predictions':", 'output}'] | 973,436 |
sek788432/Waymo-2D-Object-Detection | yt8m_model_test.py | YT8MNetworkTest.test_yt8m_network_creation | test_yt8m_network_creation | Test for creation of a YT8M Model. | [
"Test",
"for",
"creation",
"of",
"a",
"YT8M",
"Model."
] | def test_yt8m_network_creation(self, num_frames, feature_dims):
input_specs = tf.keras.layers.InputSpec(shape=[num_frames, feature_dims])
num_classes = 3862
model = yt8m_model.YT8MModel(input_params=yt8m_cfg.YT8MTask.model, num_frames=num_frames, num_classes=num_classes, input_specs=input_specs)
inputs ... | ['def', 'test_yt8m_network_creation(self,', 'num_frames,', 'feature_dims):', 'input_specs', '=', 'tf.keras.layers.InputSpec(shape=[num_frames,', 'feature_dims])', 'num_classes', '=', '3862', 'model', '=', 'yt8m_model.YT8MModel(input_params=yt8m_cfg.YT8MTask.model,', 'num_frames=num_frames,', 'num_classes=num_classes,',... | 973,439 |
sek788432/Waymo-2D-Object-Detection | yt8m_model_utils.py | SampleRandomSequence | SampleRandomSequence | Samples a random sequence of frames of size num_samples. | [
"Samples",
"a",
"random",
"sequence",
"of",
"frames",
"of",
"size",
"num_samples."
] | def SampleRandomSequence(model_input, num_frames, num_samples):
batch_size = tf.shape(model_input)[0]
frame_index_offset = tf.tile(tf.expand_dims(tf.range(num_samples), 0), [batch_size, 1])
max_start_frame_index = tf.maximum(num_frames - num_samples, 0)
start_frame_index = tf.cast(tf.multiply(tf.random_... | ['def', 'SampleRandomSequence(model_input,', 'num_frames,', 'num_samples):', 'batch_size', '=', 'tf.shape(model_input)[0]', 'frame_index_offset', '=', 'tf.tile(tf.expand_dims(tf.range(num_samples),', '0),', '[batch_size,', '1])', 'max_start_frame_index', '=', 'tf.maximum(num_frames', '-', 'num_samples,', '0)', 'start_f... | 973,440 |
sek788432/Waymo-2D-Object-Detection | yt8m_model_utils.py | SampleRandomFrames | SampleRandomFrames | Samples a random set of frames of size num_samples. | [
"Samples",
"a",
"random",
"set",
"of",
"frames",
"of",
"size",
"num_samples."
] | def SampleRandomFrames(model_input, num_frames, num_samples):
batch_size = tf.shape(model_input)[0]
frame_index = tf.cast(tf.multiply(tf.random.uniform([batch_size, num_samples]), tf.tile(tf.cast(num_frames, tf.float32), [1, num_samples])), tf.int32)
batch_index = tf.tile(tf.expand_dims(tf.range(batch_size)... | ['def', 'SampleRandomFrames(model_input,', 'num_frames,', 'num_samples):', 'batch_size', '=', 'tf.shape(model_input)[0]', 'frame_index', '=', 'tf.cast(tf.multiply(tf.random.uniform([batch_size,', 'num_samples]),', 'tf.tile(tf.cast(num_frames,', 'tf.float32),', '[1,', 'num_samples])),', 'tf.int32)', 'batch_index', '=', ... | 973,441 |
sek788432/Waymo-2D-Object-Detection | yt8m_model_utils.py | FramePooling | FramePooling | Pools over the frames of a video. | [
"Pools",
"over",
"the",
"frames",
"of",
"a",
"video."
] | def FramePooling(frames, method):
if method == 'average':
reduced = tf.reduce_mean(frames, 1)
elif method == 'max':
reduced = tf.reduce_max(frames, 1)
elif method == 'none':
feature_size = frames.shape_as_list()[2]
reduced = tf.reshape(frames, [-1, feature_size])
else:
... | ['def', 'FramePooling(frames,', 'method):', 'if', 'method', '==', "'average':", 'reduced', '=', 'tf.reduce_mean(frames,', '1)', 'elif', 'method', '==', "'max':", 'reduced', '=', 'tf.reduce_max(frames,', '1)', 'elif', 'method', '==', "'none':", 'feature_size', '=', 'frames.shape_as_list()[2]', 'reduced', '=', 'tf.reshap... | 973,442 |
sek788432/Waymo-2D-Object-Detection | yt8m_task.py | YT8MTask.build_model | build_model | Builds model for YT8M Task. | [
"Builds",
"model",
"for",
"YT8M",
"Task."
] | def build_model(self):
train_cfg = self.task_config.train_data
common_input_shape = [None, sum(train_cfg.feature_sizes)]
input_specs = tf.keras.layers.InputSpec(shape=[None] + common_input_shape)
logging.info('Build model input %r', common_input_shape)
model_config = self.task_config.model
model... | ['def', 'build_model(self):', 'train_cfg', '=', 'self.task_config.train_data', 'common_input_shape', '=', '[None,', 'sum(train_cfg.feature_sizes)]', 'input_specs', '=', 'tf.keras.layers.InputSpec(shape=[None]', '+', 'common_input_shape)', "logging.info('Build", 'model', 'input', "%r',", 'common_input_shape)', 'model_co... | 973,443 |
sek788432/Waymo-2D-Object-Detection | detection.py | DetectionModule.serve | serve | Cast image to float and run inference. | [
"Cast",
"image",
"to",
"float",
"and",
"run",
"inference."
] | def serve(self, images: tf.Tensor):
model_params = self.params.task.model
with tf.device('cpu:0'):
images = tf.cast(images, dtype=tf.float32)
images_spec = tf.TensorSpec(shape=self._input_image_size + [3], dtype=tf.float32)
num_anchors = model_params.anchor.num_scales * len(model_params.... | ['def', 'serve(self,', 'images:', 'tf.Tensor):', 'model_params', '=', 'self.params.task.model', 'with', "tf.device('cpu:0'):", 'images', '=', 'tf.cast(images,', 'dtype=tf.float32)', 'images_spec', '=', 'tf.TensorSpec(shape=self._input_image_size', '+', '[3],', 'dtype=tf.float32)', 'num_anchors', '=', 'model_params.anch... | 973,447 |
sek788432/Waymo-2D-Object-Detection | export_base.py | ExportModule.get_inference_signatures | get_inference_signatures | Gets defined function signatures. | [
"Gets",
"defined",
"function",
"signatures."
] | def get_inference_signatures(self, function_keys: Dict[Text, Text]):
signatures = {}
for (key, def_name) in function_keys.items():
if key == 'image_tensor':
input_signature = tf.TensorSpec(shape=[self._batch_size] + [None] * len(self._input_image_size) + [self._num_channels], dtype=tf.uint8)... | ['def', 'get_inference_signatures(self,', 'function_keys:', 'Dict[Text,', 'Text]):', 'signatures', '=', '{}', 'for', '(key,', 'def_name)', 'in', 'function_keys.items():', 'if', 'key', '==', "'image_tensor':", 'input_signature', '=', 'tf.TensorSpec(shape=[self._batch_size]', '+', '[None]', '*', 'len(self._input_image_si... | 973,448 |
sek788432/Waymo-2D-Object-Detection | export_tfhub.py | export_model_to_tfhub | export_model_to_tfhub | Export an image classification model to TF-Hub. | [
"Export",
"an",
"image",
"classification",
"model",
"to",
"TF-Hub."
] | def export_model_to_tfhub(params, batch_size, input_image_size, skip_logits_layer, checkpoint_path, export_path):
input_specs = tf.keras.layers.InputSpec(shape=[batch_size] + input_image_size + [3])
model = factory.build_classification_model(input_specs=input_specs, model_config=params.task.model, l2_regularize... | ['def', 'export_model_to_tfhub(params,', 'batch_size,', 'input_image_size,', 'skip_logits_layer,', 'checkpoint_path,', 'export_path):', 'input_specs', '=', 'tf.keras.layers.InputSpec(shape=[batch_size]', '+', 'input_image_size', '+', '[3])', 'model', '=', 'factory.build_classification_model(input_specs=input_specs,', '... | 973,450 |
sek788432/Waymo-2D-Object-Detection | video_classification.py | VideoClassificationTask.build_model | build_model | Builds video classification model. | [
"Builds",
"video",
"classification",
"model."
] | def build_model(self):
common_input_shape = self._get_feature_shape()
input_specs = tf.keras.layers.InputSpec(shape=[None] + common_input_shape)
logging.info('Build model input %r', common_input_shape)
l2_weight_decay = self.task_config.losses.l2_weight_decay
l2_regularizer = tf.keras.regularizers.l... | ['def', 'build_model(self):', 'common_input_shape', '=', 'self._get_feature_shape()', 'input_specs', '=', 'tf.keras.layers.InputSpec(shape=[None]', '+', 'common_input_shape)', "logging.info('Build", 'model', 'input', "%r',", 'common_input_shape)', 'l2_weight_decay', '=', 'self.task_config.losses.l2_weight_decay', 'l2_r... | 973,465 |
sek788432/Waymo-2D-Object-Detection | main.py | run_executor | run_executor | Runs the object detection model on distribution strategy defined by the user. | [
"Runs",
"the",
"object",
"detection",
"model",
"on",
"distribution",
"strategy",
"defined",
"by",
"the",
"user."
] | def run_executor(params, mode, checkpoint_path=None, train_input_fn=None, eval_input_fn=None, callbacks=None, prebuilt_strategy=None):
if params.architecture.use_bfloat16:
tf.compat.v2.keras.mixed_precision.set_global_policy('mixed_bfloat16')
model_builder = model_factory.model_generator(params)
if ... | ['def', 'run_executor(params,', 'mode,', 'checkpoint_path=None,', 'train_input_fn=None,', 'eval_input_fn=None,', 'callbacks=None,', 'prebuilt_strategy=None):', 'if', 'params.architecture.use_bfloat16:', "tf.compat.v2.keras.mixed_precision.set_global_policy('mixed_bfloat16')", 'model_builder', '=', 'model_factory.model_... | 973,471 |
sek788432/Waymo-2D-Object-Detection | base_model.py | Model.model_outputs | model_outputs | Build the model outputs. | [
"Build",
"the",
"model",
"outputs."
] | def model_outputs(self, inputs, mode):
return self.build_outputs(inputs, mode) | ['def', 'model_outputs(self,', 'inputs,', 'mode):', 'return', 'self.build_outputs(inputs,', 'mode)'] | 973,506 |
sek788432/Waymo-2D-Object-Detection | learning_rates.py | learning_rate_generator | learning_rate_generator | The learning rate function generator. | [
"The",
"learning",
"rate",
"function",
"generator."
] | def learning_rate_generator(total_steps, params):
if params.type == 'step':
return StepLearningRateWithLinearWarmup(total_steps, params)
elif params.type == 'cosine':
return CosineLearningRateWithLinearWarmup(total_steps, params)
else:
raise ValueError('Unsupported learning rate type... | ['def', 'learning_rate_generator(total_steps,', 'params):', 'if', 'params.type', '==', "'step':", 'return', 'StepLearningRateWithLinearWarmup(total_steps,', 'params)', 'elif', 'params.type', '==', "'cosine':", 'return', 'CosineLearningRateWithLinearWarmup(total_steps,', 'params)', 'else:', 'raise', "ValueError('Unsuppo... | 973,512 |
sek788432/Waymo-2D-Object-Detection | factory.py | oln_rpn_head_generator | oln_rpn_head_generator | Generator function for OLN-proposal (OLN-RPN) head architecture. | [
"Generator",
"function",
"for",
"OLN-proposal",
"(OLN-RPN)",
"head",
"architecture."
] | def oln_rpn_head_generator(params):
head_params = params.rpn_head
anchors_per_location = params.anchor.num_scales * len(params.anchor.aspect_ratios)
return heads.OlnRpnHead(params.architecture.min_level, params.architecture.max_level, anchors_per_location, head_params.num_convs, head_params.num_filters, hea... | ['def', 'oln_rpn_head_generator(params):', 'head_params', '=', 'params.rpn_head', 'anchors_per_location', '=', 'params.anchor.num_scales', '*', 'len(params.anchor.aspect_ratios)', 'return', 'heads.OlnRpnHead(params.architecture.min_level,', 'params.architecture.max_level,', 'anchors_per_location,', 'head_params.num_con... | 973,520 |
sek788432/Waymo-2D-Object-Detection | factory.py | oln_box_score_head_generator | oln_box_score_head_generator | Generator function for Scoring Fast R-CNN head architecture. | [
"Generator",
"function",
"for",
"Scoring",
"Fast",
"R-CNN",
"head",
"architecture."
] | def oln_box_score_head_generator(params):
head_params = params.frcnn_head
return heads.OlnBoxScoreHead(params.architecture.num_classes, head_params.num_convs, head_params.num_filters, head_params.use_separable_conv, head_params.num_fcs, head_params.fc_dims, params.norm_activation.activation, head_params.use_bat... | ['def', 'oln_box_score_head_generator(params):', 'head_params', '=', 'params.frcnn_head', 'return', 'heads.OlnBoxScoreHead(params.architecture.num_classes,', 'head_params.num_convs,', 'head_params.num_filters,', 'head_params.use_separable_conv,', 'head_params.num_fcs,', 'head_params.fc_dims,', 'params.norm_activation.a... | 973,522 |
sek788432/Waymo-2D-Object-Detection | factory.py | shapeprior_head_generator | shapeprior_head_generator | Generator function for shape prior head architecture. | [
"Generator",
"function",
"for",
"shape",
"prior",
"head",
"architecture."
] | def shapeprior_head_generator(params):
head_params = params.shapemask_head
return heads.ShapemaskPriorHead(params.architecture.num_classes, head_params.num_downsample_channels, head_params.mask_crop_size, head_params.use_category_for_mask, head_params.shape_prior_path) | ['def', 'shapeprior_head_generator(params):', 'head_params', '=', 'params.shapemask_head', 'return', 'heads.ShapemaskPriorHead(params.architecture.num_classes,', 'head_params.num_downsample_channels,', 'head_params.mask_crop_size,', 'head_params.use_category_for_mask,', 'head_params.shape_prior_path)'] | 973,525 |
sek788432/Waymo-2D-Object-Detection | heads.py | FastrcnnHead.call | call | Box and class branches for the Mask-RCNN model. | [
"Box",
"and",
"class",
"branches",
"for",
"the",
"Mask-RCNN",
"model."
] | def call(self, roi_features, is_training=None):
with tf.name_scope('fast_rcnn_head'):
(_, num_rois, height, width, filters) = roi_features.get_shape().as_list()
net = tf.reshape(roi_features, [-1, height, width, filters])
for i in range(self._num_convs):
net = self._conv_ops[i](n... | ['def', 'call(self,', 'roi_features,', 'is_training=None):', 'with', "tf.name_scope('fast_rcnn_head'):", '(_,', 'num_rois,', 'height,', 'width,', 'filters)', '=', 'roi_features.get_shape().as_list()', 'net', '=', 'tf.reshape(roi_features,', '[-1,', 'height,', 'width,', 'filters])', 'for', 'i', 'in', 'range(self._num_co... | 973,528 |
sek788432/Waymo-2D-Object-Detection | heads.py | MaskrcnnHead.call | call | Mask branch for the Mask-RCNN model. | [
"Mask",
"branch",
"for",
"the",
"Mask-RCNN",
"model."
] | def call(self, roi_features, class_indices, is_training=None):
with tf.name_scope('mask_head'):
(_, num_rois, height, width, filters) = roi_features.get_shape().as_list()
net = tf.reshape(roi_features, [-1, height, width, filters])
for i in range(self._num_convs):
net = self._con... | ['def', 'call(self,', 'roi_features,', 'class_indices,', 'is_training=None):', 'with', "tf.name_scope('mask_head'):", '(_,', 'num_rois,', 'height,', 'width,', 'filters)', '=', 'roi_features.get_shape().as_list()', 'net', '=', 'tf.reshape(roi_features,', '[-1,', 'height,', 'width,', 'filters])', 'for', 'i', 'in', 'range... | 973,529 |
sek788432/Waymo-2D-Object-Detection | heads.py | ShapemaskFinemaskHead.decoder_net | decoder_net | Fine mask decoder network architecture. | [
"Fine",
"mask",
"decoder",
"network",
"architecture."
] | def decoder_net(self, features, is_training=False):
(batch_size, num_instances, height, width, num_channels) = features.get_shape().as_list()
features = tf.reshape(features, [batch_size * num_instances, height, width, num_channels])
for i in range(self._num_convs):
features = self._fine_class_conv[i... | ['def', 'decoder_net(self,', 'features,', 'is_training=False):', '(batch_size,', 'num_instances,', 'height,', 'width,', 'num_channels)', '=', 'features.get_shape().as_list()', 'features', '=', 'tf.reshape(features,', '[batch_size', '*', 'num_instances,', 'height,', 'width,', 'num_channels])', 'for', 'i', 'in', 'range(s... | 973,533 |
sek788432/Waymo-2D-Object-Detection | target_ops.py | ROISampler.call | call | Sample and assign RoIs for training. | [
"Sample",
"and",
"assign",
"RoIs",
"for",
"training."
] | def call(self, rois, gt_boxes, gt_classes):
(sampled_rois, sampled_gt_boxes, sampled_gt_classes, sampled_gt_indices) = assign_and_sample_proposals(rois, gt_boxes, gt_classes, num_samples_per_image=self._num_samples_per_image, mix_gt_boxes=self._mix_gt_boxes, fg_fraction=self._fg_fraction, fg_iou_thresh=self._fg_iou... | ['def', 'call(self,', 'rois,', 'gt_boxes,', 'gt_classes):', '(sampled_rois,', 'sampled_gt_boxes,', 'sampled_gt_classes,', 'sampled_gt_indices)', '=', 'assign_and_sample_proposals(rois,', 'gt_boxes,', 'gt_classes,', 'num_samples_per_image=self._num_samples_per_image,', 'mix_gt_boxes=self._mix_gt_boxes,', 'fg_fraction=se... | 973,554 |
sek788432/Waymo-2D-Object-Detection | class_utils.py | coco_split_class_ids | coco_split_class_ids | Return the COCO class split ids based on split name and training mode. | [
"Return",
"the",
"COCO",
"class",
"split",
"ids",
"based",
"on",
"split",
"name",
"and",
"training",
"mode."
] | def coco_split_class_ids(split_name):
if split_name == 'all':
return []
elif split_name == 'voc':
return [1, 2, 3, 4, 5, 6, 7, 9, 16, 17, 18, 19, 20, 21, 44, 62, 63, 64, 67, 72]
elif split_name == 'nonvoc':
return [8, 10, 11, 13, 14, 15, 22, 23, 24, 25, 27, 28, 31, 32, 33, 34, 35, 36... | ['def', 'coco_split_class_ids(split_name):', 'if', 'split_name', '==', "'all':", 'return', '[]', 'elif', 'split_name', '==', "'voc':", 'return', '[1,', '2,', '3,', '4,', '5,', '6,', '7,', '9,', '16,', '17,', '18,', '19,', '20,', '21,', '44,', '62,', '63,', '64,', '67,', '72]', 'elif', 'split_name', '==', "'nonvoc':", '... | 973,571 |
sek788432/Waymo-2D-Object-Detection | classifier_trainer.py | get_dtype_map | get_dtype_map | Returns the mapping from dtype string representations to TF dtypes. | [
"Returns",
"the",
"mapping",
"from",
"dtype",
"string",
"representations",
"to",
"TF",
"dtypes."
] | def get_dtype_map() -> Mapping[str, tf.dtypes.DType]:
return {'float32': tf.float32, 'bfloat16': tf.bfloat16, 'float16': tf.float16, 'fp32': tf.float32, 'bf16': tf.bfloat16} | ['def', 'get_dtype_map()', '->', 'Mapping[str,', 'tf.dtypes.DType]:', 'return', "{'float32':", 'tf.float32,', "'bfloat16':", 'tf.bfloat16,', "'float16':", 'tf.float16,', "'fp32':", 'tf.float32,', "'bf16':", 'tf.bfloat16}'] | 973,714 |
sek788432/Waymo-2D-Object-Detection | classifier_trainer.py | get_image_size_from_model | get_image_size_from_model | If the given model has a preferred image size, return it. | [
"If",
"the",
"given",
"model",
"has",
"a",
"preferred",
"image",
"size,",
"return",
"it."
] | def get_image_size_from_model(params: base_configs.ExperimentConfig) -> Optional[int]:
if params.model_name == 'efficientnet':
efficientnet_name = params.model.model_params.model_name
if efficientnet_name in efficientnet_model.MODEL_CONFIGS:
return efficientnet_model.MODEL_CONFIGS[effici... | ['def', 'get_image_size_from_model(params:', 'base_configs.ExperimentConfig)', '->', 'Optional[int]:', 'if', 'params.model_name', '==', "'efficientnet':", 'efficientnet_name', '=', 'params.model.model_params.model_name', 'if', 'efficientnet_name', 'in', 'efficientnet_model.MODEL_CONFIGS:', 'return', 'efficientnet_model... | 973,715 |
sek788432/Waymo-2D-Object-Detection | classifier_trainer.py | run | run | Runs Image Classification model using native Keras APIs. | [
"Runs",
"Image",
"Classification",
"model",
"using",
"native",
"Keras",
"APIs."
] | def run(flags_obj: flags.FlagValues, strategy_override: tf.distribute.Strategy=None) -> Mapping[str, Any]:
params = _get_params_from_flags(flags_obj)
if params.mode == 'train_and_eval':
return train_and_eval(params, strategy_override)
elif params.mode == 'export_only':
export(params)
els... | ['def', 'run(flags_obj:', 'flags.FlagValues,', 'strategy_override:', 'tf.distribute.Strategy=None)', '->', 'Mapping[str,', 'Any]:', 'params', '=', '_get_params_from_flags(flags_obj)', 'if', 'params.mode', '==', "'train_and_eval':", 'return', 'train_and_eval(params,', 'strategy_override)', 'elif', 'params.mode', '==', "... | 973,723 |
sek788432/Waymo-2D-Object-Detection | classifier_trainer_test.py | get_params_override | get_params_override | Converts params_override dict to string command. | [
"Converts",
"params_override",
"dict",
"to",
"string",
"command."
] | def get_params_override(params_override: Mapping[str, Any]) -> str:
return '--params_override=' + json.dumps(params_override) | ['def', 'get_params_override(params_override:', 'Mapping[str,', 'Any])', '->', 'str:', 'return', "'--params_override='", '+', 'json.dumps(params_override)'] | 973,725 |
sek788432/Waymo-2D-Object-Detection | dataset_factory.py | DatasetConfig.has_data | has_data | Whether this dataset is has any data associated with it. | [
"Whether",
"this",
"dataset",
"is",
"has",
"any",
"data",
"associated",
"with",
"it."
] | def has_data(self):
return self.name or self.data_dir or self.filenames | ['def', 'has_data(self):', 'return', 'self.name', 'or', 'self.data_dir', 'or', 'self.filenames'] | 973,737 |
sek788432/Waymo-2D-Object-Detection | dataset_factory.py | DatasetBuilder.image_size | image_size | The size of each image (can be inferred from the dataset). | [
"The",
"size",
"of",
"each",
"image",
"(can",
"be",
"inferred",
"from",
"the",
"dataset)."
] | def image_size(self) -> int:
if self.config.image_size == 'infer':
return self.info.features['image'].shape[0]
else:
return int(self.config.image_size) | ['def', 'image_size(self)', '->', 'int:', 'if', 'self.config.image_size', '==', "'infer':", 'return', "self.info.features['image'].shape[0]", 'else:', 'return', 'int(self.config.image_size)'] | 973,744 |
sek788432/Waymo-2D-Object-Detection | dataset_factory.py | DatasetBuilder.num_examples | num_examples | The number of examples (can be inferred from the dataset). | [
"The",
"number",
"of",
"examples",
"(can",
"be",
"inferred",
"from",
"the",
"dataset)."
] | def num_examples(self) -> int:
if self.config.num_examples == 'infer':
return self.info.splits[self.config.split].num_examples
else:
return int(self.config.num_examples) | ['def', 'num_examples(self)', '->', 'int:', 'if', 'self.config.num_examples', '==', "'infer':", 'return', 'self.info.splits[self.config.split].num_examples', 'else:', 'return', 'int(self.config.num_examples)'] | 973,746 |
sek788432/Waymo-2D-Object-Detection | mnist_main.py | build_model | build_model | Constructs the ML model used to predict handwritten digits. | [
"Constructs",
"the",
"ML",
"model",
"used",
"to",
"predict",
"handwritten",
"digits."
] | def build_model():
image = tf.keras.layers.Input(shape=(28, 28, 1))
y = tf.keras.layers.Conv2D(filters=32, kernel_size=5, padding='same', activation='relu')(image)
y = tf.keras.layers.MaxPooling2D(pool_size=(2, 2), strides=(2, 2), padding='same')(y)
y = tf.keras.layers.Conv2D(filters=32, kernel_size=5, ... | ['def', 'build_model():', 'image', '=', 'tf.keras.layers.Input(shape=(28,', '28,', '1))', 'y', '=', 'tf.keras.layers.Conv2D(filters=32,', 'kernel_size=5,', "padding='same',", "activation='relu')(image)", 'y', '=', 'tf.keras.layers.MaxPooling2D(pool_size=(2,', '2),', 'strides=(2,', '2),', "padding='same')(y)", 'y', '=',... | 973,759 |
sek788432/Waymo-2D-Object-Detection | mnist_test.py | KerasMnistTest.test_end_to_end | test_end_to_end | Test Keras MNIST model with `strategy`. | [
"Test",
"Keras",
"MNIST",
"model",
"with",
"`strategy`."
] | def test_end_to_end(self, distribution):
extra_flags = ['-train_epochs', '1', '--data_dir=']
dummy_data = (tf.ones(shape=(10, 28, 28, 1), dtype=tf.int32), tf.range(10))
datasets = (tf.data.Dataset.from_tensor_slices(dummy_data), tf.data.Dataset.from_tensor_slices(dummy_data))
run = functools.partial(mni... | ['def', 'test_end_to_end(self,', 'distribution):', 'extra_flags', '=', "['-train_epochs',", "'1',", "'--data_dir=']", 'dummy_data', '=', '(tf.ones(shape=(10,', '28,', '28,', '1),', 'dtype=tf.int32),', 'tf.range(10))', 'datasets', '=', '(tf.data.Dataset.from_tensor_slices(dummy_data),', 'tf.data.Dataset.from_tensor_slic... | 973,763 |
sek788432/Waymo-2D-Object-Detection | optimizer_factory_test.py | OptimizerFactoryTest.test_learning_rate_with_decay_and_warmup | test_learning_rate_with_decay_and_warmup | Basic smoke test for syntax. | [
"Basic",
"smoke",
"test",
"for",
"syntax."
] | def test_learning_rate_with_decay_and_warmup(self, lr_decay_type):
params = base_configs.LearningRateConfig(name=lr_decay_type, initial_lr=0.01, decay_rate=0.01, decay_epochs=1, warmup_epochs=1, scale_by_batch_size=0.01, examples_per_epoch=1, boundaries=[0], multipliers=[0, 1])
batch_size = 1
train_epochs =... | ['def', 'test_learning_rate_with_decay_and_warmup(self,', 'lr_decay_type):', 'params', '=', 'base_configs.LearningRateConfig(name=lr_decay_type,', 'initial_lr=0.01,', 'decay_rate=0.01,', 'decay_epochs=1,', 'warmup_epochs=1,', 'scale_by_batch_size=0.01,', 'examples_per_epoch=1,', 'boundaries=[0],', 'multipliers=[0,', '1... | 973,768 |
sek788432/Waymo-2D-Object-Detection | resnet_ctl_imagenet_main.py | run | run | Run ResNet ImageNet training and eval loop using custom training loops. | [
"Run",
"ResNet",
"ImageNet",
"training",
"and",
"eval",
"loop",
"using",
"custom",
"training",
"loops."
] | def run(flags_obj):
keras_utils.set_session_config()
performance.set_mixed_precision_policy(flags_core.get_tf_dtype(flags_obj))
if tf.config.list_physical_devices('GPU'):
if flags_obj.tf_gpu_thread_mode:
keras_utils.set_gpu_thread_mode_and_count(per_gpu_thread_count=flags_obj.per_gpu_thr... | ['def', 'run(flags_obj):', 'keras_utils.set_session_config()', 'performance.set_mixed_precision_policy(flags_core.get_tf_dtype(flags_obj))', 'if', "tf.config.list_physical_devices('GPU'):", 'if', 'flags_obj.tf_gpu_thread_mode:', 'keras_utils.set_gpu_thread_mode_and_count(per_gpu_thread_count=flags_obj.per_gpu_thread_co... | 973,808 |
sek788432/Waymo-2D-Object-Detection | loss_utils.py | multi_level_flatten | multi_level_flatten | Flattens a multi-level input. | [
"Flattens",
"a",
"multi-level",
"input."
] | def multi_level_flatten(multi_level_inputs, last_dim=None):
flattened_inputs = []
batch_size = None
for level in multi_level_inputs.keys():
single_input = multi_level_inputs[level]
if batch_size is None:
batch_size = single_input.shape[0] or tf.shape(single_input)[0]
if l... | ['def', 'multi_level_flatten(multi_level_inputs,', 'last_dim=None):', 'flattened_inputs', '=', '[]', 'batch_size', '=', 'None', 'for', 'level', 'in', 'multi_level_inputs.keys():', 'single_input', '=', 'multi_level_inputs[level]', 'if', 'batch_size', 'is', 'None:', 'batch_size', '=', 'single_input.shape[0]', 'or', 'tf.s... | 973,813 |
sek788432/Waymo-2D-Object-Detection | anchor_generator.py | maybe_map_structure_for_anchor | maybe_map_structure_for_anchor | broadcast the params to match anchor_sizes. | [
"broadcast",
"the",
"params",
"to",
"match",
"anchor_sizes."
] | def maybe_map_structure_for_anchor(params, anchor_sizes):
if all((isinstance(param, (int, float)) for param in params)):
if isinstance(anchor_sizes, (tuple, list)):
return [params] * len(anchor_sizes)
elif isinstance(anchor_sizes, dict):
return tf.nest.map_structure(lambda _:... | ['def', 'maybe_map_structure_for_anchor(params,', 'anchor_sizes):', 'if', 'all((isinstance(param,', '(int,', 'float))', 'for', 'param', 'in', 'params)):', 'if', 'isinstance(anchor_sizes,', '(tuple,', 'list)):', 'return', '[params]', '*', 'len(anchor_sizes)', 'elif', 'isinstance(anchor_sizes,', 'dict):', 'return', 'tf.n... | 973,816 |
sek788432/Waymo-2D-Object-Detection | new_best_metric.py | NewBestMetric.metric_value | metric_value | Computes the metric value for the given `output`. | [
"Computes",
"the",
"metric",
"value",
"for",
"the",
"given",
"`output`."
] | def metric_value(self, output: runner.Output) -> float:
if callable(self.metric):
value = self.metric(output)
else:
value = output[self.metric]
return float(utils.get_value(value)) | ['def', 'metric_value(self,', 'output:', 'runner.Output)', '->', 'float:', 'if', 'callable(self.metric):', 'value', '=', 'self.metric(output)', 'else:', 'value', '=', 'output[self.metric]', 'return', 'float(utils.get_value(value))'] | 973,847 |
sek788432/Waymo-2D-Object-Detection | new_best_metric.py | NewBestMetric.best_value | best_value | Returns the best metric value seen so far. | [
"Returns",
"the",
"best",
"metric",
"value",
"seen",
"so",
"far."
] | def best_value(self) -> float:
return self._best_value.read() | ['def', 'best_value(self)', '->', 'float:', 'return', 'self._best_value.read()'] | 973,848 |
sek788432/Waymo-2D-Object-Detection | new_best_metric.py | JSONPersistedValue.write | write | Writes the value, updating the backing store if one was provided. | [
"Writes",
"the",
"value,",
"updating",
"the",
"backing",
"store",
"if",
"one",
"was",
"provided."
] | def write(self, value):
self._value = value
if self._filename is not None and self._write_value:
tmp_filename = f'{self._filename}.tmp.{uuid.uuid4().hex}'
with tf.io.gfile.GFile(tmp_filename, 'w') as f:
json.dump(self._value, f)
tf.io.gfile.rename(tmp_filename, self._filename... | ['def', 'write(self,', 'value):', 'self._value', '=', 'value', 'if', 'self._filename', 'is', 'not', 'None', 'and', 'self._write_value:', 'tmp_filename', '=', "f'{self._filename}.tmp.{uuid.uuid4().hex}'", 'with', 'tf.io.gfile.GFile(tmp_filename,', "'w')", 'as', 'f:', 'json.dump(self._value,', 'f)', 'tf.io.gfile.rename(t... | 973,851 |
sek788432/Waymo-2D-Object-Detection | single_task_evaluator.py | SingleTaskEvaluator.eval_begin | eval_begin | Actions to take once before every eval loop. | [
"Actions",
"to",
"take",
"once",
"before",
"every",
"eval",
"loop."
] | def eval_begin(self):
for metric in self.metrics:
metric.reset_states() | ['def', 'eval_begin(self):', 'for', 'metric', 'in', 'self.metrics:', 'metric.reset_states()'] | 973,852 |
sek788432/Waymo-2D-Object-Detection | single_task_evaluator.py | SingleTaskEvaluator.eval_end | eval_end | Actions to take once after an eval loop. | [
"Actions",
"to",
"take",
"once",
"after",
"an",
"eval",
"loop."
] | def eval_end(self):
with self.strategy.scope():
metrics = {metric.name: metric.result() for metric in self.metrics}
return metrics | ['def', 'eval_end(self):', 'with', 'self.strategy.scope():', 'metrics', '=', '{metric.name:', 'metric.result()', 'for', 'metric', 'in', 'self.metrics}', 'return', 'metrics'] | 973,854 |
sek788432/Waymo-2D-Object-Detection | epoch_helper.py | EpochHelper.epoch_begin | epoch_begin | Returns whether a new epoch should begin. | [
"Returns",
"whether",
"a",
"new",
"epoch",
"should",
"begin."
] | def epoch_begin(self):
if self._in_epoch:
return False
current_step = self._global_step.numpy()
self._epoch_start_step = current_step
self._current_epoch = current_step // self._epoch_steps
self._in_epoch = True
return True | ['def', 'epoch_begin(self):', 'if', 'self._in_epoch:', 'return', 'False', 'current_step', '=', 'self._global_step.numpy()', 'self._epoch_start_step', '=', 'current_step', 'self._current_epoch', '=', 'current_step', '//', 'self._epoch_steps', 'self._in_epoch', '=', 'True', 'return', 'True'] | 973,861 |
sek788432/Waymo-2D-Object-Detection | model.py | axis_pad | axis_pad | Pad a tensor with the specified values along a single axis. | [
"Pad",
"a",
"tensor",
"with",
"the",
"specified",
"values",
"along",
"a",
"single",
"axis."
] | def axis_pad(tensor, axis, before=0, after=0, constant_values=0.0):
if before == 0 and after == 0:
return tensor
ndims = tensor.shape.ndims
padding_size = np.zeros((ndims, 2), dtype='int32')
padding_size[axis] = (before, after)
return tf.pad(tensor=tensor, paddings=tf.constant(padding_size),... | ['def', 'axis_pad(tensor,', 'axis,', 'before=0,', 'after=0,', 'constant_values=0.0):', 'if', 'before', '==', '0', 'and', 'after', '==', '0:', 'return', 'tensor', 'ndims', '=', 'tensor.shape.ndims', 'padding_size', '=', 'np.zeros((ndims,', '2),', "dtype='int32')", 'padding_size[axis]', '=', '(before,', 'after)', 'return... | 973,930 |
sek788432/Waymo-2D-Object-Detection | yamnet.py | class_names | class_names | Read the class name definition file and return a list of strings. | [
"Read",
"the",
"class",
"name",
"definition",
"file",
"and",
"return",
"a",
"list",
"of",
"strings."
] | def class_names(class_map_csv):
if tf.is_tensor(class_map_csv):
class_map_csv = class_map_csv.numpy()
with open(class_map_csv) as csv_file:
reader = csv.reader(csv_file)
next(reader)
return np.array([display_name for (_, _, display_name) in reader]) | ['def', 'class_names(class_map_csv):', 'if', 'tf.is_tensor(class_map_csv):', 'class_map_csv', '=', 'class_map_csv.numpy()', 'with', 'open(class_map_csv)', 'as', 'csv_file:', 'reader', '=', 'csv.reader(csv_file)', 'next(reader)', 'return', 'np.array([display_name', 'for', '(_,', '_,', 'display_name)', 'in', 'reader])'] | 973,995 |
sek788432/Waymo-2D-Object-Detection | tasks.py | UnrolledTask.episode_batch | episode_batch | Returns a batch of episodes. | [
"Returns",
"a",
"batch",
"of",
"episodes."
] | def episode_batch(self, batch_size):
batched_inputs = collections.OrderedDict([[mtype, []] for mtype in self.config.inputs])
batched_queries = []
batched_outputs = []
batched_masks = []
for _ in range(int(batch_size)):
with self._lock:
(inputs, query, outputs) = self.episode()
... | ['def', 'episode_batch(self,', 'batch_size):', 'batched_inputs', '=', 'collections.OrderedDict([[mtype,', '[]]', 'for', 'mtype', 'in', 'self.config.inputs])', 'batched_queries', '=', '[]', 'batched_outputs', '=', '[]', 'batched_masks', '=', '[]', 'for', '_', 'in', 'range(int(batch_size)):', 'with', 'self._lock:', '(inp... | 974,052 |
sek788432/Waymo-2D-Object-Detection | whiten.py | apply_whitening | apply_whitening | Applies the whitening to the descriptors as a post-processing step. | [
"Applies",
"the",
"whitening",
"to",
"the",
"descriptors",
"as",
"a",
"post-processing",
"step."
] | def apply_whitening(descriptors, mean_descriptor_vector, projection, output_dim=None):
eps = 1e-06
if output_dim is None:
output_dim = projection.shape[0]
descriptors = np.dot(projection[:output_dim, :], descriptors - mean_descriptor_vector)
descriptors_whitened = descriptors / (np.linalg.norm(d... | ['def', 'apply_whitening(descriptors,', 'mean_descriptor_vector,', 'projection,', 'output_dim=None):', 'eps', '=', '1e-06', 'if', 'output_dim', 'is', 'None:', 'output_dim', '=', 'projection.shape[0]', 'descriptors', '=', 'np.dot(projection[:output_dim,', ':],', 'descriptors', '-', 'mean_descriptor_vector)', 'descriptor... | 974,248 |
sek788432/Waymo-2D-Object-Detection | utils.py | pil_imagenet_loader | pil_imagenet_loader | Pillow loader for the images. | [
"Pillow",
"loader",
"for",
"the",
"images."
] | def pil_imagenet_loader(path, imsize, bounding_box=None, preprocess=True):
img = image_loading_utils.RgbLoader(path)
if bounding_box is not None:
imfullsize = max(img.size)
img = img.crop(bounding_box)
imsize = imsize * max(img.size) / imfullsize
img.thumbnail((imsize, imsize), Image... | ['def', 'pil_imagenet_loader(path,', 'imsize,', 'bounding_box=None,', 'preprocess=True):', 'img', '=', 'image_loading_utils.RgbLoader(path)', 'if', 'bounding_box', 'is', 'not', 'None:', 'imfullsize', '=', 'max(img.size)', 'img', '=', 'img.crop(bounding_box)', 'imsize', '=', 'imsize', '*', 'max(img.size)', '/', 'imfulls... | 974,251 |
sek788432/Waymo-2D-Object-Detection | dataset_file_io.py | ReadSolution | ReadSolution | Reads solution from file, for a given task. | [
"Reads",
"solution",
"from",
"file,",
"for",
"a",
"given",
"task."
] | def ReadSolution(file_path, task):
public_solution = {}
private_solution = {}
ignored_ids = []
with tf.io.gfile.GFile(file_path, 'r') as csv_file:
reader = csv.reader(csv_file)
next(reader, None)
for row in reader:
test_id = row[0]
if row[2] == 'Ignored':
... | ['def', 'ReadSolution(file_path,', 'task):', 'public_solution', '=', '{}', 'private_solution', '=', '{}', 'ignored_ids', '=', '[]', 'with', 'tf.io.gfile.GFile(file_path,', "'r')", 'as', 'csv_file:', 'reader', '=', 'csv.reader(csv_file)', 'next(reader,', 'None)', 'for', 'row', 'in', 'reader:', 'test_id', '=', 'row[0]', ... | 974,253 |
sek788432/Waymo-2D-Object-Detection | dataset.py | ReadMetricsFile | ReadMetricsFile | Reads aggregated retrieval metrics from text file. | [
"Reads",
"aggregated",
"retrieval",
"metrics",
"from",
"text",
"file."
] | def ReadMetricsFile(metrics_path):
with tf.io.gfile.GFile(metrics_path, 'r') as f:
file_contents_stripped = [l.rstrip() for l in f]
if len(file_contents_stripped) % 4:
raise ValueError('Malformed input %s: number of lines must be a multiple of 4, but it is %d' % (metrics_path, len(file_contents_... | ['def', 'ReadMetricsFile(metrics_path):', 'with', 'tf.io.gfile.GFile(metrics_path,', "'r')", 'as', 'f:', 'file_contents_stripped', '=', '[l.rstrip()', 'for', 'l', 'in', 'f]', 'if', 'len(file_contents_stripped)', '%', '4:', 'raise', "ValueError('Malformed", 'input', '%s:', 'number', 'of', 'lines', 'must', 'be', 'a', 'mu... | 974,269 |
sek788432/Waymo-2D-Object-Detection | dataset.py | CreateConfigForTestDataset | CreateConfigForTestDataset | Creates the configuration dictionary for the test dataset. | [
"Creates",
"the",
"configuration",
"dictionary",
"for",
"the",
"test",
"dataset."
] | def CreateConfigForTestDataset(dataset, dir_main):
dataset = dataset.lower()
def _ConfigImname(cfg, i):
return os.path.join(cfg['dir_images'], cfg['imlist'][i] + cfg['ext'])
def _ConfigQimname(cfg, i):
return os.path.join(cfg['dir_images'], cfg['qimlist'][i] + cfg['qext'])
if dataset n... | ['def', 'CreateConfigForTestDataset(dataset,', 'dir_main):', 'dataset', '=', 'dataset.lower()', 'def', '_ConfigImname(cfg,', 'i):', 'return', "os.path.join(cfg['dir_images'],", "cfg['imlist'][i]", '+', "cfg['ext'])", 'def', '_ConfigQimname(cfg,', 'i):', 'return', "os.path.join(cfg['dir_images'],", "cfg['qimlist'][i]", ... | 974,270 |
sek788432/Waymo-2D-Object-Detection | normalization.py | L2Normalization.call | call | Invokes the L2Normalization instance. | [
"Invokes",
"the",
"L2Normalization",
"instance."
] | def call(self, x, axis=1):
return tf.nn.l2_normalize(x, axis, epsilon=self.eps) | ['def', 'call(self,', 'x,', 'axis=1):', 'return', 'tf.nn.l2_normalize(x,', 'axis,', 'epsilon=self.eps)'] | 974,278 |
sek788432/Waymo-2D-Object-Detection | pooling.py | mac | mac | Performs global max pooling (MAC). | [
"Performs",
"global",
"max",
"pooling",
"(MAC)."
] | def mac(x, axis=None):
if axis is None:
axis = [1, 2]
return tf.reduce_max(x, axis=axis, keepdims=False) | ['def', 'mac(x,', 'axis=None):', 'if', 'axis', 'is', 'None:', 'axis', '=', '[1,', '2]', 'return', 'tf.reduce_max(x,', 'axis=axis,', 'keepdims=False)'] | 974,279 |
sek788432/Waymo-2D-Object-Detection | pooling.py | gem | gem | Performs generalized mean pooling (GeM). | [
"Performs",
"generalized",
"mean",
"pooling",
"(GeM)."
] | def gem(x, axis=None, power=3.0, eps=1e-06):
if axis is None:
axis = [1, 2]
tmp = tf.pow(tf.maximum(x, eps), power)
out = tf.pow(tf.reduce_mean(tmp, axis=axis, keepdims=False), 1.0 / power)
return out | ['def', 'gem(x,', 'axis=None,', 'power=3.0,', 'eps=1e-06):', 'if', 'axis', 'is', 'None:', 'axis', '=', '[1,', '2]', 'tmp', '=', 'tf.pow(tf.maximum(x,', 'eps),', 'power)', 'out', '=', 'tf.pow(tf.reduce_mean(tmp,', 'axis=axis,', 'keepdims=False),', '1.0', '/', 'power)', 'return', 'out'] | 974,281 |
sek788432/Waymo-2D-Object-Detection | pooling.py | MAC.call | call | Invokes the MAC pooling instance. | [
"Invokes",
"the",
"MAC",
"pooling",
"instance."
] | def call(self, x, axis=None):
if axis is None:
axis = [1, 2]
return mac(x, axis=axis) | ['def', 'call(self,', 'x,', 'axis=None):', 'if', 'axis', 'is', 'None:', 'axis', '=', '[1,', '2]', 'return', 'mac(x,', 'axis=axis)'] | 974,282 |
sek788432/Waymo-2D-Object-Detection | pooling.py | GeM.call | call | Invokes the GeM instance. | [
"Invokes",
"the",
"GeM",
"instance."
] | def call(self, x, axis=None):
if axis is None:
axis = [1, 2]
return gem(x, power=self.power, eps=self.eps, axis=axis) | ['def', 'call(self,', 'x,', 'axis=None):', 'if', 'axis', 'is', 'None:', 'axis', '=', '[1,', '2]', 'return', 'gem(x,', 'power=self.power,', 'eps=self.eps,', 'axis=axis)'] | 974,284 |
sek788432/Waymo-2D-Object-Detection | global_features_utils.py | compute_metrics_and_print | compute_metrics_and_print | Computes and logs ground-truth metrics for Revisited datasets. | [
"Computes",
"and",
"logs",
"ground-truth",
"metrics",
"for",
"Revisited",
"datasets."
] | def compute_metrics_and_print(dataset_name, sorted_index_ids, ground_truth, desired_pr_ranks=None, log=True):
if dataset not in dataset.DATASET_NAMES:
raise ValueError('Unknown dataset: {}!'.format(dataset))
if desired_pr_ranks is None:
desired_pr_ranks = [1, 5, 10]
(easy_ground_truth, mediu... | ['def', 'compute_metrics_and_print(dataset_name,', 'sorted_index_ids,', 'ground_truth,', 'desired_pr_ranks=None,', 'log=True):', 'if', 'dataset', 'not', 'in', 'dataset.DATASET_NAMES:', 'raise', "ValueError('Unknown", 'dataset:', "{}!'.format(dataset))", 'if', 'desired_pr_ranks', 'is', 'None:', 'desired_pr_ranks', '=', ... | 974,285 |
sek788432/Waymo-2D-Object-Detection | global_features_utils.py | AverageMeter.reset | reset | Resets all the values. | [
"Resets",
"all",
"the",
"values."
] | def reset(self):
self.val = 0
self.avg = 0
self.sum = 0
self.count = 0 | ['def', 'reset(self):', 'self.val', '=', '0', 'self.avg', '=', '0', 'self.sum', '=', '0', 'self.count', '=', '0'] | 974,290 |
sek788432/Waymo-2D-Object-Detection | delg_model.py | cosine_classifier_logits | cosine_classifier_logits | Compute cosine classifier logits using ArFace margin. | [
"Compute",
"cosine",
"classifier",
"logits",
"using",
"ArFace",
"margin."
] | def cosine_classifier_logits(prelogits, labels, num_classes, cosine_weights, scale_factor, arcface_margin, training=True):
normalized_prelogits = tf.math.l2_normalize(prelogits, axis=1)
normalized_weights = tf.math.l2_normalize(cosine_weights, axis=0)
cosine_sim = tf.matmul(normalized_prelogits, normalized_... | ['def', 'cosine_classifier_logits(prelogits,', 'labels,', 'num_classes,', 'cosine_weights,', 'scale_factor,', 'arcface_margin,', 'training=True):', 'normalized_prelogits', '=', 'tf.math.l2_normalize(prelogits,', 'axis=1)', 'normalized_weights', '=', 'tf.math.l2_normalize(cosine_weights,', 'axis=0)', 'cosine_sim', '=', ... | 974,297 |
sek788432/Waymo-2D-Object-Detection | resnet50.py | ResNet50.call | call | Call the ResNet50 model. | [
"Call",
"the",
"ResNet50",
"model."
] | def call(self, inputs, training=True, intermediates_dict=None):
return self.build_call(inputs, training, intermediates_dict) | ['def', 'call(self,', 'inputs,', 'training=True,', 'intermediates_dict=None):', 'return', 'self.build_call(inputs,', 'training,', 'intermediates_dict)'] | 974,304 |
sek788432/Waymo-2D-Object-Detection | agent.py | UvfAgentCore.clip_actions | clip_actions | Clip actions to spec. | [
"Clip",
"actions",
"to",
"spec."
] | def clip_actions(self, actions):
actions = tf.concat([tf.clip_by_value(actions[:, i:i + 1], self._action_spec.minimum[i], self._action_spec.maximum[i]) for i in range(self._action_spec.shape[0].value)], axis=1)
return actions | ['def', 'clip_actions(self,', 'actions):', 'actions', '=', 'tf.concat([tf.clip_by_value(actions[:,', 'i:i', '+', '1],', 'self._action_spec.minimum[i],', 'self._action_spec.maximum[i])', 'for', 'i', 'in', 'range(self._action_spec.shape[0].value)],', 'axis=1)', 'return', 'actions'] | 974,315 |
sek788432/Waymo-2D-Object-Detection | agent.py | UvfAgentCore.init_action_vars | init_action_vars | Create and return a tensorflow Variable holding an action. | [
"Create",
"and",
"return",
"a",
"tensorflow",
"Variable",
"holding",
"an",
"action."
] | def init_action_vars(self, name, i=None):
if i is not None:
name += '_%d' % i
assert name not in self._action_vars, 'Conflict! %s is already initialized.' % name
self._action_vars[name] = tf.Variable(self.sample_random_actions(1)[0], name='%s_action' % name)
self._validate_actions(tf.expand_dims... | ['def', 'init_action_vars(self,', 'name,', 'i=None):', 'if', 'i', 'is', 'not', 'None:', 'name', '+=', "'_%d'", '%', 'i', 'assert', 'name', 'not', 'in', 'self._action_vars,', "'Conflict!", '%s', 'is', 'already', "initialized.'", '%', 'name', 'self._action_vars[name]', '=', 'tf.Variable(self.sample_random_actions(1)[0],'... | 974,320 |
sek788432/Waymo-2D-Object-Detection | cond_fn.py | true_fn | true_fn | Returns an op that evaluates to true. | [
"Returns",
"an",
"op",
"that",
"evaluates",
"to",
"true."
] | def true_fn(agent, state, action, transition_type, environment_steps, num_episodes):
del agent, state, action, transition_type, environment_steps, num_episodes
cond = tf.constant(True, dtype=tf.bool)
return cond | ['def', 'true_fn(agent,', 'state,', 'action,', 'transition_type,', 'environment_steps,', 'num_episodes):', 'del', 'agent,', 'state,', 'action,', 'transition_type,', 'environment_steps,', 'num_episodes', 'cond', '=', 'tf.constant(True,', 'dtype=tf.bool)', 'return', 'cond'] | 974,329 |
sek788432/Waymo-2D-Object-Detection | eval.py | get_eval_step | get_eval_step | Get one-step policy/env stepping ops. | [
"Get",
"one-step",
"policy/env",
"stepping",
"ops."
] | def get_eval_step(uvf_agent, state_preprocess, tf_env, action_fn, meta_action_fn, environment_steps, num_episodes, mode='eval'):
tf_env.start_collect()
state = tf_env.current_obs()
action = action_fn(state, context=None)
state_repr = state_preprocess(state)
action_spec = tf_env.action_spec()
act... | ['def', 'get_eval_step(uvf_agent,', 'state_preprocess,', 'tf_env,', 'action_fn,', 'meta_action_fn,', 'environment_steps,', 'num_episodes,', "mode='eval'):", 'tf_env.start_collect()', 'state', '=', 'tf_env.current_obs()', 'action', '=', 'action_fn(state,', 'context=None)', 'state_repr', '=', 'state_preprocess(state)', '... | 974,332 |
sek788432/Waymo-2D-Object-Detection | context.py | Context.create_vars | create_vars | Create tf variables for contexts. | [
"Create",
"tf",
"variables",
"for",
"contexts."
] | def create_vars(self, name, agent=None):
if agent is not None:
meta_vars = agent.create_vars(name)
else:
meta_vars = {}
assert name not in self.context_vars, 'Conflict! %s is already initialized.' % name
self.context_vars[name] = tuple([tf.Variable(tf.zeros(shape=spec.shape, dtype=spec.d... | ['def', 'create_vars(self,', 'name,', 'agent=None):', 'if', 'agent', 'is', 'not', 'None:', 'meta_vars', '=', 'agent.create_vars(name)', 'else:', 'meta_vars', '=', '{}', 'assert', 'name', 'not', 'in', 'self.context_vars,', "'Conflict!", '%s', 'is', 'already', "initialized.'", '%', 'name', 'self.context_vars[name]', '=',... | 974,380 |
sek788432/Waymo-2D-Object-Detection | rewards_functions.py | ctrl_rewards | ctrl_rewards | Returns the negative control cost. | [
"Returns",
"the",
"negative",
"control",
"cost."
] | def ctrl_rewards(states, actions, rewards, next_states, contexts, reward_scales=1.0):
del states, rewards, contexts
if actions is None:
rewards = tf.to_float(tf.zeros(shape=next_states.shape[:1]))
else:
rewards = -tf.reduce_sum(tf.square(actions), axis=1)
rewards *= reward_scales
... | ['def', 'ctrl_rewards(states,', 'actions,', 'rewards,', 'next_states,', 'contexts,', 'reward_scales=1.0):', 'del', 'states,', 'rewards,', 'contexts', 'if', 'actions', 'is', 'None:', 'rewards', '=', 'tf.to_float(tf.zeros(shape=next_states.shape[:1]))', 'else:', 'rewards', '=', '-tf.reduce_sum(tf.square(actions),', 'axis... | 974,396 |
sek788432/Waymo-2D-Object-Detection | utils.py | get_contextual_env_base | get_contextual_env_base | Wrap env_base with additional tf ops. | [
"Wrap",
"env_base",
"with",
"additional",
"tf",
"ops."
] | def get_contextual_env_base(env_base, begin_ops=None, end_ops=None):
def init(self_, env_base):
self_._env_base = env_base
attribute_list = ['_render_mode', '_gym_env']
for attribute in attribute_list:
if hasattr(env_base, attribute):
setattr(self_, attribute, ge... | ['def', 'get_contextual_env_base(env_base,', 'begin_ops=None,', 'end_ops=None):', 'def', 'init(self_,', 'env_base):', 'self_._env_base', '=', 'env_base', 'attribute_list', '=', "['_render_mode',", "'_gym_env']", 'for', 'attribute', 'in', 'attribute_list:', 'if', 'hasattr(env_base,', 'attribute):', 'setattr(self_,', 'at... | 974,405 |
sek788432/Waymo-2D-Object-Detection | utils.py | identity_vars | identity_vars | Return the identity ops for a list of tensors. | [
"Return",
"the",
"identity",
"ops",
"for",
"a",
"list",
"of",
"tensors."
] | def identity_vars(vars_):
return [tf.identity(var) for var in vars_] | ['def', 'identity_vars(vars_):', 'return', '[tf.identity(var)', 'for', 'var', 'in', 'vars_]'] | 974,410 |
sek788432/Waymo-2D-Object-Detection | tf_sequence_example_decoder.py | TFSequenceExampleDecoderHelper.decode | decode | Decodes the given serialized TF-SequenceExample. | [
"Decodes",
"the",
"given",
"serialized",
"TF-SequenceExample."
] | def decode(self, serialized_example, items=None):
(context, feature_list) = tf.parse_single_sequence_example(serialized_example, self._keys_to_context_features, self._keys_to_sequence_features)
for k in self._keys_to_context_features:
v = self._keys_to_context_features[k]
if isinstance(v, tf.Fix... | ['def', 'decode(self,', 'serialized_example,', 'items=None):', '(context,', 'feature_list)', '=', 'tf.parse_single_sequence_example(serialized_example,', 'self._keys_to_context_features,', 'self._keys_to_sequence_features)', 'for', 'k', 'in', 'self._keys_to_context_features:', 'v', '=', 'self._keys_to_context_features[... | 974,489 |
sek788432/Waymo-2D-Object-Detection | utils.py | quantize_op | quantize_op | Inserts a fake quantization op after inputs. | [
"Inserts",
"a",
"fake",
"quantization",
"op",
"after",
"inputs."
] | def quantize_op(inputs, is_training=True, is_quantized=True, default_min=0, default_max=6, ema_decay=0.999, scope='quant'):
if not is_quantized:
return inputs
with tf.variable_scope(scope):
min_var = _quant_var('min', default_min)
max_var = _quant_var('max', default_max)
if not i... | ['def', 'quantize_op(inputs,', 'is_training=True,', 'is_quantized=True,', 'default_min=0,', 'default_max=6,', 'ema_decay=0.999,', "scope='quant'):", 'if', 'not', 'is_quantized:', 'return', 'inputs', 'with', 'tf.variable_scope(scope):', 'min_var', '=', "_quant_var('min',", 'default_min)', 'max_var', '=', "_quant_var('ma... | 974,502 |
sek788432/Waymo-2D-Object-Detection | export_tflite_graph_lib_tf2.py | CenterNetModule.inference_fn | inference_fn | Encapsulates CenterNet inference for TFLite conversion. | [
"Encapsulates",
"CenterNet",
"inference",
"for",
"TFLite",
"conversion."
] | def inference_fn(self, image):
image = tf.cast(image, tf.float32)
(image, shapes) = self._model.preprocess(image)
prediction_dict = self._model.predict(image, None)
detections = self._model.postprocess(prediction_dict, true_image_shapes=shapes)
field_names = fields.DetectionResultFields
classes_... | ['def', 'inference_fn(self,', 'image):', 'image', '=', 'tf.cast(image,', 'tf.float32)', '(image,', 'shapes)', '=', 'self._model.preprocess(image)', 'prediction_dict', '=', 'self._model.predict(image,', 'None)', 'detections', '=', 'self._model.postprocess(prediction_dict,', 'true_image_shapes=shapes)', 'field_names', '=... | 974,557 |
sek788432/Waymo-2D-Object-Detection | model_lib.py | continuous_eval | continuous_eval | Performs continuous evaluation on checkpoints written to a model directory. | [
"Performs",
"continuous",
"evaluation",
"on",
"checkpoints",
"written",
"to",
"a",
"model",
"directory."
] | def continuous_eval(estimator, model_dir, input_fn, train_steps, name, max_retries=0):
for (current_step, eval_results) in continuous_eval_generator(estimator, model_dir, input_fn, train_steps, name, max_retries):
tf.logging.info('Step %s, Eval results: %s', current_step, eval_results) | ['def', 'continuous_eval(estimator,', 'model_dir,', 'input_fn,', 'train_steps,', 'name,', 'max_retries=0):', 'for', '(current_step,', 'eval_results)', 'in', 'continuous_eval_generator(estimator,', 'model_dir,', 'input_fn,', 'train_steps,', 'name,', 'max_retries):', "tf.logging.info('Step", '%s,', 'Eval', 'results:', "%... | 974,599 |
sek788432/Waymo-2D-Object-Detection | model_lib_tf1_test.py | ModelLibTest.test_model_fn_in_keypoints_eval_mode | test_model_fn_in_keypoints_eval_mode | Tests the model function in EVAL mode with keypoints config. | [
"Tests",
"the",
"model",
"function",
"in",
"EVAL",
"mode",
"with",
"keypoints",
"config."
] | def test_model_fn_in_keypoints_eval_mode(self):
configs = _get_configs_for_model(MODEL_NAME_FOR_KEYPOINTS_TEST)
estimator_spec = self._assert_model_fn_for_train_eval(configs, 'eval')
metric_ops = estimator_spec.eval_metric_ops
self.assertIn('Keypoints_Precision/mAP ByCategory/face', metric_ops)
self... | ['def', 'test_model_fn_in_keypoints_eval_mode(self):', 'configs', '=', '_get_configs_for_model(MODEL_NAME_FOR_KEYPOINTS_TEST)', 'estimator_spec', '=', 'self._assert_model_fn_for_train_eval(configs,', "'eval')", 'metric_ops', '=', 'estimator_spec.eval_metric_ops', "self.assertIn('Keypoints_Precision/mAP", "ByCategory/fa... | 974,609 |
sek788432/Waymo-2D-Object-Detection | model_builder_tf2_test.py | ModelBuilderTF2Test.test_create_center_net_model_mobilenet | test_create_center_net_model_mobilenet | Test building a CenterNet model using bilinear interpolation. | [
"Test",
"building",
"a",
"CenterNet",
"model",
"using",
"bilinear",
"interpolation."
] | def test_create_center_net_model_mobilenet(self):
proto_txt = '\n center_net {\n num_classes: 10\n feature_extractor {\n type: "mobilenet_v2_fpn"\n depth_multiplier: 1.0\n use_separable_conv: true\n upsampling_interpolation: "bilinear"\n }\n image... | ['def', 'test_create_center_net_model_mobilenet(self):', 'proto_txt', '=', "'\\n", 'center_net', '{\\n', 'num_classes:', '10\\n', 'feature_extractor', '{\\n', 'type:', '"mobilenet_v2_fpn"\\n', 'depth_multiplier:', '1.0\\n', 'use_separable_conv:', 'true\\n', 'upsampling_interpolation:', '"bilinear"\\n', '}\\n', 'image_r... | 974,701 |
sek788432/Waymo-2D-Object-Detection | densepose_ops.py | DensePoseHorizontalFlip.flip_parts_and_coords | flip_parts_and_coords | Flips part ids and coordinates. | [
"Flips",
"part",
"ids",
"and",
"coordinates."
] | def flip_parts_and_coords(self, part_ids, vu):
(num_instances, num_points) = shape_utils.combined_static_and_dynamic_shape(part_ids)
part_ids_flattened = tf.reshape(part_ids, [-1])
new_part_ids_flattened = tf.gather(self.part_symmetries, part_ids_flattened)
new_part_ids = tf.reshape(new_part_ids_flatten... | ['def', 'flip_parts_and_coords(self,', 'part_ids,', 'vu):', '(num_instances,', 'num_points)', '=', 'shape_utils.combined_static_and_dynamic_shape(part_ids)', 'part_ids_flattened', '=', 'tf.reshape(part_ids,', '[-1])', 'new_part_ids_flattened', '=', 'tf.gather(self.part_symmetries,', 'part_ids_flattened)', 'new_part_ids... | 974,778 |
sek788432/Waymo-2D-Object-Detection | preprocessor.py | random_jitter_boxes | random_jitter_boxes | Randomly jitters boxes in image. | [
"Randomly",
"jitters",
"boxes",
"in",
"image."
] | def random_jitter_boxes(boxes, ratio=0.05, jitter_mode='default', seed=None):
with tf.name_scope('RandomJitterBoxes'):
(ymin, xmin, ymax, xmax) = (boxes[:, i] for i in range(4))
blist = box_list.BoxList(boxes)
(ycenter, xcenter, height, width) = blist.get_center_coordinates_and_sizes()
... | ['def', 'random_jitter_boxes(boxes,', 'ratio=0.05,', "jitter_mode='default',", 'seed=None):', 'with', "tf.name_scope('RandomJitterBoxes'):", '(ymin,', 'xmin,', 'ymax,', 'xmax)', '=', '(boxes[:,', 'i]', 'for', 'i', 'in', 'range(4))', 'blist', '=', 'box_list.BoxList(boxes)', '(ycenter,', 'xcenter,', 'height,', 'width)', ... | 974,839 |
sek788432/Waymo-2D-Object-Detection | target_assigner_test.py | CenterNetCenterHeatmapTargetAssignerTest.test_weights | test_weights | Test that the weights correctly ignore ground truth. | [
"Test",
"that",
"the",
"weights",
"correctly",
"ignore",
"ground",
"truth."
] | def test_weights(self):
def graph1_fn():
box_batch = [tf.constant([self._box_center, self._box_lower_left]), tf.constant([self._box_center]), tf.constant([self._box_center_small])]
classes = [tf.one_hot([0, 1], depth=4), tf.one_hot([2], depth=4), tf.one_hot([3], depth=4)]
assigner = targeta... | ['def', 'test_weights(self):', 'def', 'graph1_fn():', 'box_batch', '=', '[tf.constant([self._box_center,', 'self._box_lower_left]),', 'tf.constant([self._box_center]),', 'tf.constant([self._box_center_small])]', 'classes', '=', '[tf.one_hot([0,', '1],', 'depth=4),', 'tf.one_hot([2],', 'depth=4),', 'tf.one_hot([3],', 'd... | 974,924 |
sek788432/Waymo-2D-Object-Detection | target_assigner_test.py | CornerOffsetTargetAssignerTest.test_filter_overlap_min_area_empty | test_filter_overlap_min_area_empty | Test that empty masks work on CPU. | [
"Test",
"that",
"empty",
"masks",
"work",
"on",
"CPU."
] | def test_filter_overlap_min_area_empty(self):
def graph_fn(masks):
return targetassigner.filter_mask_overlap_min_area(masks)
masks = self.execute_cpu(graph_fn, [np.zeros((0, 5, 5), dtype=np.float32)])
self.assertEqual(masks.shape, (0, 5, 5)) | ['def', 'test_filter_overlap_min_area_empty(self):', 'def', 'graph_fn(masks):', 'return', 'targetassigner.filter_mask_overlap_min_area(masks)', 'masks', '=', 'self.execute_cpu(graph_fn,', '[np.zeros((0,', '5,', '5),', 'dtype=np.float32)])', 'self.assertEqual(masks.shape,', '(0,', '5,', '5))'] | 974,934 |
sek788432/Waymo-2D-Object-Detection | oid_hierarchical_labels_expansion.py | OIDHierarchicalLabelsExpansion.expand_labels_from_csv | expand_labels_from_csv | Expands a row containing labels from CSV file. | [
"Expands",
"a",
"row",
"containing",
"labels",
"from",
"CSV",
"file."
] | def expand_labels_from_csv(self, csv_row, labelname_column_index=1, confidence_column_index=2):
split_csv_row = six.ensure_str(csv_row).split(',')
result = [csv_row]
if int(split_csv_row[confidence_column_index]) == 1:
assert split_csv_row[labelname_column_index] in self._hierarchy_keyed_child
... | ['def', 'expand_labels_from_csv(self,', 'csv_row,', 'labelname_column_index=1,', 'confidence_column_index=2):', 'split_csv_row', '=', "six.ensure_str(csv_row).split(',')", 'result', '=', '[csv_row]', 'if', 'int(split_csv_row[confidence_column_index])', '==', '1:', 'assert', 'split_csv_row[labelname_column_index]', 'in'... | 974,954 |
sek788432/Waymo-2D-Object-Detection | seq_example_util.py | sequence_bytes_feature | sequence_bytes_feature | Converts a bytes float array to a sequence bytes feature. | [
"Converts",
"a",
"bytes",
"float",
"array",
"to",
"a",
"sequence",
"bytes",
"feature."
] | def sequence_bytes_feature(ndarray):
feature_list = tf.train.FeatureList()
for row in ndarray:
if isinstance(row, np.ndarray):
row = row.tolist()
feature = feature_list.feature.add()
if row:
row = [tf.compat.as_bytes(val) for val in row]
feature.bytes_... | ['def', 'sequence_bytes_feature(ndarray):', 'feature_list', '=', 'tf.train.FeatureList()', 'for', 'row', 'in', 'ndarray:', 'if', 'isinstance(row,', 'np.ndarray):', 'row', '=', 'row.tolist()', 'feature', '=', 'feature_list.feature.add()', 'if', 'row:', 'row', '=', '[tf.compat.as_bytes(val)', 'for', 'val', 'in', 'row]', ... | 974,961 |
sek788432/Waymo-2D-Object-Detection | center_net_meta_arch.py | argmax_feature_map_locations | argmax_feature_map_locations | Returns the peak locations in the feature map. | [
"Returns",
"the",
"peak",
"locations",
"in",
"the",
"feature",
"map."
] | def argmax_feature_map_locations(feature_map):
(batch_size, _, width, num_channels) = _get_shape(feature_map, 4)
feature_map_flattened = tf.reshape(feature_map, [batch_size, -1, num_channels])
peak_flat_indices = tf.math.argmax(feature_map_flattened, axis=1, output_type=tf.dtypes.int32)
(y_indices, x_in... | ['def', 'argmax_feature_map_locations(feature_map):', '(batch_size,', '_,', 'width,', 'num_channels)', '=', '_get_shape(feature_map,', '4)', 'feature_map_flattened', '=', 'tf.reshape(feature_map,', '[batch_size,', '-1,', 'num_channels])', 'peak_flat_indices', '=', 'tf.math.argmax(feature_map_flattened,', 'axis=1,', 'ou... | 974,995 |
sek788432/Waymo-2D-Object-Detection | center_net_meta_arch.py | row_col_indices_from_flattened_indices | row_col_indices_from_flattened_indices | Computes row and column indices from flattened indices. | [
"Computes",
"row",
"and",
"column",
"indices",
"from",
"flattened",
"indices."
] | def row_col_indices_from_flattened_indices(indices, num_cols):
row_indices = indices // num_cols
col_indices = indices - row_indices * num_cols
return (row_indices, col_indices) | ['def', 'row_col_indices_from_flattened_indices(indices,', 'num_cols):', 'row_indices', '=', 'indices', '//', 'num_cols', 'col_indices', '=', 'indices', '-', 'row_indices', '*', 'num_cols', 'return', '(row_indices,', 'col_indices)'] | 975,000 |
sek788432/Waymo-2D-Object-Detection | center_net_meta_arch_tf2_test.py | get_fake_center_params | get_fake_center_params | Returns the fake object center parameter namedtuple. | [
"Returns",
"the",
"fake",
"object",
"center",
"parameter",
"namedtuple."
] | def get_fake_center_params(max_box_predictions=5):
return cnma.ObjectCenterParams(classification_loss=losses.WeightedSigmoidClassificationLoss(), object_center_loss_weight=1.0, min_box_overlap_iou=1.0, max_box_predictions=max_box_predictions, use_labeled_classes=False, center_head_num_filters=[128], center_head_ker... | ['def', 'get_fake_center_params(max_box_predictions=5):', 'return', 'cnma.ObjectCenterParams(classification_loss=losses.WeightedSigmoidClassificationLoss(),', 'object_center_loss_weight=1.0,', 'min_box_overlap_iou=1.0,', 'max_box_predictions=max_box_predictions,', 'use_labeled_classes=False,', 'center_head_num_filters=... | 975,016 |
sek788432/Waymo-2D-Object-Detection | center_net_meta_arch_tf2_test.py | CenterNetMetaArchTest.test_loss | test_loss | Test the loss function. | [
"Test",
"the",
"loss",
"function."
] | def test_loss(self):
groundtruth_dict = get_fake_groundtruth_dict(16, 32, 4)
model = build_center_net_meta_arch()
model.provide_groundtruth(groundtruth_boxes_list=groundtruth_dict[fields.BoxListFields.boxes], groundtruth_weights_list=groundtruth_dict[fields.BoxListFields.weights], groundtruth_classes_list=g... | ['def', 'test_loss(self):', 'groundtruth_dict', '=', 'get_fake_groundtruth_dict(16,', '32,', '4)', 'model', '=', 'build_center_net_meta_arch()', 'model.provide_groundtruth(groundtruth_boxes_list=groundtruth_dict[fields.BoxListFields.boxes],', 'groundtruth_weights_list=groundtruth_dict[fields.BoxListFields.weights],', '... | 975,032 |
sek788432/Waymo-2D-Object-Detection | center_net_meta_arch_tf2_test.py | CenterNetMetaArchRestoreTest.test_retore_map_detection | test_retore_map_detection | Test that detection checkpoints can be restored. | [
"Test",
"that",
"detection",
"checkpoints",
"can",
"be",
"restored."
] | def test_retore_map_detection(self):
model = build_center_net_meta_arch(build_resnet=True)
restore_from_objects_map = model.restore_from_objects('detection')
self.assertIsInstance(restore_from_objects_map['model']._feature_extractor, tf.keras.Model) | ['def', 'test_retore_map_detection(self):', 'model', '=', 'build_center_net_meta_arch(build_resnet=True)', 'restore_from_objects_map', '=', "model.restore_from_objects('detection')", "self.assertIsInstance(restore_from_objects_map['model']._feature_extractor,", 'tf.keras.Model)'] | 975,040 |
sek788432/Waymo-2D-Object-Detection | deepmac_meta_arch.py | crop_masks_within_boxes | crop_masks_within_boxes | Crops masks to lie tightly within the boxes. | [
"Crops",
"masks",
"to",
"lie",
"tightly",
"within",
"the",
"boxes."
] | def crop_masks_within_boxes(masks, boxes, output_size):
masks = spatial_transform_ops.matmul_crop_and_resize(masks[:, :, :, tf.newaxis], boxes[:, tf.newaxis, :], [output_size, output_size])
return masks[:, 0, :, :, 0] | ['def', 'crop_masks_within_boxes(masks,', 'boxes,', 'output_size):', 'masks', '=', 'spatial_transform_ops.matmul_crop_and_resize(masks[:,', ':,', ':,', 'tf.newaxis],', 'boxes[:,', 'tf.newaxis,', ':],', '[output_size,', 'output_size])', 'return', 'masks[:,', '0,', ':,', ':,', '0]'] | 975,055 |
sek788432/Waymo-2D-Object-Detection | deepmac_meta_arch.py | deepmac_proto_to_params | deepmac_proto_to_params | Convert proto to named tuple. | [
"Convert",
"proto",
"to",
"named",
"tuple."
] | def deepmac_proto_to_params(deepmac_config):
loss = losses_pb2.Loss()
loss.localization_loss.weighted_l2.CopyFrom(losses_pb2.WeightedL2LocalizationLoss())
loss.classification_loss.CopyFrom(deepmac_config.classification_loss)
(classification_loss, _, _, _, _, _, _) = losses_builder.build(loss)
jitter... | ['def', 'deepmac_proto_to_params(deepmac_config):', 'loss', '=', 'losses_pb2.Loss()', 'loss.localization_loss.weighted_l2.CopyFrom(losses_pb2.WeightedL2LocalizationLoss())', 'loss.classification_loss.CopyFrom(deepmac_config.classification_loss)', '(classification_loss,', '_,', '_,', '_,', '_,', '_,', '_)', '=', 'losses... | 975,057 |
sek788432/Waymo-2D-Object-Detection | deepmac_meta_arch.py | DeepMACMetaArch.postprocess | postprocess | Produces boxes given a prediction dict returned by predict(). | [
"Produces",
"boxes",
"given",
"a",
"prediction",
"dict",
"returned",
"by",
"predict()."
] | def postprocess(self, prediction_dict, true_image_shapes, **params):
postprocess_dict = super(DeepMACMetaArch, self).postprocess(prediction_dict, true_image_shapes, **params)
boxes_strided = postprocess_dict['detection_boxes_strided']
if self._deepmac_params is not None:
masks = self._postprocess_ma... | ['def', 'postprocess(self,', 'prediction_dict,', 'true_image_shapes,', '**params):', 'postprocess_dict', '=', 'super(DeepMACMetaArch,', 'self).postprocess(prediction_dict,', 'true_image_shapes,', '**params)', 'boxes_strided', '=', "postprocess_dict['detection_boxes_strided']", 'if', 'self._deepmac_params', 'is', 'not',... | 975,058 |
sek788432/Waymo-2D-Object-Detection | deepmac_meta_arch.py | DeepMACMetaArch.predict_masks_from_boxes | predict_masks_from_boxes | Produces masks for the provided boxes. | [
"Produces",
"masks",
"for",
"the",
"provided",
"boxes."
] | def predict_masks_from_boxes(self, prediction_dict, true_image_shapes, provided_boxes, **params):
postprocess_dict = super(DeepMACMetaArch, self).postprocess(prediction_dict, true_image_shapes, **params)
instance_embedding = prediction_dict[INSTANCE_EMBEDDING][-1]
resized_image_shapes = shape_utils.combined... | ['def', 'predict_masks_from_boxes(self,', 'prediction_dict,', 'true_image_shapes,', 'provided_boxes,', '**params):', 'postprocess_dict', '=', 'super(DeepMACMetaArch,', 'self).postprocess(prediction_dict,', 'true_image_shapes,', '**params)', 'instance_embedding', '=', 'prediction_dict[INSTANCE_EMBEDDING][-1]', 'resized_... | 975,059 |
sek788432/Waymo-2D-Object-Detection | deepmac_meta_arch_test.py | build_meta_arch | build_meta_arch | Builds the DeepMAC meta architecture. | [
"Builds",
"the",
"DeepMAC",
"meta",
"architecture."
] | def build_meta_arch(predict_full_resolution_masks=False, use_dice_loss=False):
feature_extractor = DummyFeatureExtractor(channel_means=(1.0, 2.0, 3.0), channel_stds=(10.0, 20.0, 30.0), bgr_ordering=False, num_feature_outputs=2, stride=4)
image_resizer_fn = functools.partial(preprocessor.resize_to_range, min_dim... | ['def', 'build_meta_arch(predict_full_resolution_masks=False,', 'use_dice_loss=False):', 'feature_extractor', '=', 'DummyFeatureExtractor(channel_means=(1.0,', '2.0,', '3.0),', 'channel_stds=(10.0,', '20.0,', '30.0),', 'bgr_ordering=False,', 'num_feature_outputs=2,', 'stride=4)', 'image_resizer_fn', '=', 'functools.par... | 975,060 |
sek788432/Waymo-2D-Object-Detection | center_net_hourglass_feature_extractor.py | hourglass_10 | hourglass_10 | The Hourglass-10 backbone for CenterNet. | [
"The",
"Hourglass-10",
"backbone",
"for",
"CenterNet."
] | def hourglass_10(channel_means, channel_stds, bgr_ordering, **kwargs):
del kwargs
network = hourglass_network.hourglass_10(num_channels=32)
return CenterNetHourglassFeatureExtractor(network, channel_means=channel_means, channel_stds=channel_stds, bgr_ordering=bgr_ordering) | ['def', 'hourglass_10(channel_means,', 'channel_stds,', 'bgr_ordering,', '**kwargs):', 'del', 'kwargs', 'network', '=', 'hourglass_network.hourglass_10(num_channels=32)', 'return', 'CenterNetHourglassFeatureExtractor(network,', 'channel_means=channel_means,', 'channel_stds=channel_stds,', 'bgr_ordering=bgr_ordering)'] | 975,171 |
sek788432/Waymo-2D-Object-Detection | center_net_hourglass_feature_extractor.py | hourglass_20 | hourglass_20 | The Hourglass-20 backbone for CenterNet. | [
"The",
"Hourglass-20",
"backbone",
"for",
"CenterNet."
] | def hourglass_20(channel_means, channel_stds, bgr_ordering, **kwargs):
del kwargs
network = hourglass_network.hourglass_20(num_channels=48)
return CenterNetHourglassFeatureExtractor(network, channel_means=channel_means, channel_stds=channel_stds, bgr_ordering=bgr_ordering) | ['def', 'hourglass_20(channel_means,', 'channel_stds,', 'bgr_ordering,', '**kwargs):', 'del', 'kwargs', 'network', '=', 'hourglass_network.hourglass_20(num_channels=48)', 'return', 'CenterNetHourglassFeatureExtractor(network,', 'channel_means=channel_means,', 'channel_stds=channel_stds,', 'bgr_ordering=bgr_ordering)'] | 975,172 |
sek788432/Waymo-2D-Object-Detection | center_net_hourglass_feature_extractor.py | hourglass_32 | hourglass_32 | The Hourglass-32 backbone for CenterNet. | [
"The",
"Hourglass-32",
"backbone",
"for",
"CenterNet."
] | def hourglass_32(channel_means, channel_stds, bgr_ordering, **kwargs):
del kwargs
network = hourglass_network.hourglass_32(num_channels=48)
return CenterNetHourglassFeatureExtractor(network, channel_means=channel_means, channel_stds=channel_stds, bgr_ordering=bgr_ordering) | ['def', 'hourglass_32(channel_means,', 'channel_stds,', 'bgr_ordering,', '**kwargs):', 'del', 'kwargs', 'network', '=', 'hourglass_network.hourglass_32(num_channels=48)', 'return', 'CenterNetHourglassFeatureExtractor(network,', 'channel_means=channel_means,', 'channel_stds=channel_stds,', 'bgr_ordering=bgr_ordering)'] | 975,173 |
sek788432/Waymo-2D-Object-Detection | center_net_hourglass_feature_extractor.py | hourglass_52 | hourglass_52 | The Hourglass-52 backbone for CenterNet. | [
"The",
"Hourglass-52",
"backbone",
"for",
"CenterNet."
] | def hourglass_52(channel_means, channel_stds, bgr_ordering, **kwargs):
del kwargs
network = hourglass_network.hourglass_52(num_channels=64)
return CenterNetHourglassFeatureExtractor(network, channel_means=channel_means, channel_stds=channel_stds, bgr_ordering=bgr_ordering) | ['def', 'hourglass_52(channel_means,', 'channel_stds,', 'bgr_ordering,', '**kwargs):', 'del', 'kwargs', 'network', '=', 'hourglass_network.hourglass_52(num_channels=64)', 'return', 'CenterNetHourglassFeatureExtractor(network,', 'channel_means=channel_means,', 'channel_stds=channel_stds,', 'bgr_ordering=bgr_ordering)'] | 975,174 |
sek788432/Waymo-2D-Object-Detection | center_net_mobilenet_v2_feature_extractor.py | mobilenet_v2 | mobilenet_v2 | The MobileNetV2 backbone for CenterNet. | [
"The",
"MobileNetV2",
"backbone",
"for",
"CenterNet."
] | def mobilenet_v2(channel_means, channel_stds, bgr_ordering, depth_multiplier=1.0, **kwargs):
del kwargs
network = mobilenetv2.mobilenet_v2(batchnorm_training=True, alpha=depth_multiplier, include_top=False, weights='imagenet' if depth_multiplier == 1.0 else None)
return CenterNetMobileNetV2FeatureExtractor(... | ['def', 'mobilenet_v2(channel_means,', 'channel_stds,', 'bgr_ordering,', 'depth_multiplier=1.0,', '**kwargs):', 'del', 'kwargs', 'network', '=', 'mobilenetv2.mobilenet_v2(batchnorm_training=True,', 'alpha=depth_multiplier,', 'include_top=False,', "weights='imagenet'", 'if', 'depth_multiplier', '==', '1.0', 'else', 'Non... | 975,178 |
sek788432/Waymo-2D-Object-Detection | center_net_resnet_feature_extractor.py | resnet_v2_101 | resnet_v2_101 | The ResNet v2 101 feature extractor. | [
"The",
"ResNet",
"v2",
"101",
"feature",
"extractor."
] | def resnet_v2_101(channel_means, channel_stds, bgr_ordering, **kwargs):
del kwargs
return CenterNetResnetFeatureExtractor(resnet_type='resnet_v2_101', channel_means=channel_means, channel_stds=channel_stds, bgr_ordering=bgr_ordering) | ['def', 'resnet_v2_101(channel_means,', 'channel_stds,', 'bgr_ordering,', '**kwargs):', 'del', 'kwargs', 'return', "CenterNetResnetFeatureExtractor(resnet_type='resnet_v2_101',", 'channel_means=channel_means,', 'channel_stds=channel_stds,', 'bgr_ordering=bgr_ordering)'] | 975,184 |
sek788432/Waymo-2D-Object-Detection | ssd_mobiledet_feature_extractor.py | mobiledet_gpu_backbone | mobiledet_gpu_backbone | Build a MobileDet GPU backbone. | [
"Build",
"a",
"MobileDet",
"GPU",
"backbone."
] | def mobiledet_gpu_backbone(h, multiplier=1.0):
def _scale(filters):
return _scale_filters(filters, multiplier)
ibn = functools.partial(_inverted_bottleneck, activation_fn=tf.nn.relu6)
fused = functools.partial(_fused_conv, activation_fn=tf.nn.relu6)
tucker = functools.partial(_tucker_conv, acti... | ['def', 'mobiledet_gpu_backbone(h,', 'multiplier=1.0):', 'def', '_scale(filters):', 'return', '_scale_filters(filters,', 'multiplier)', 'ibn', '=', 'functools.partial(_inverted_bottleneck,', 'activation_fn=tf.nn.relu6)', 'fused', '=', 'functools.partial(_fused_conv,', 'activation_fn=tf.nn.relu6)', 'tucker', '=', 'funct... | 975,234 |
sek788432/Waymo-2D-Object-Detection | resnet_v1.py | block_basic | block_basic | A residual block for ResNet18/34. | [
"A",
"residual",
"block",
"for",
"ResNet18/34."
] | def block_basic(x, filters, kernel_size=3, stride=1, conv_shortcut=False, name=None):
layers = tf.keras.layers
bn_axis = 3 if tf.keras.backend.image_data_format() == 'channels_last' else 1
preact = layers.BatchNormalization(axis=bn_axis, epsilon=1.001e-05, name=name + '_preact_bn')(x)
preact = layers.Ac... | ['def', 'block_basic(x,', 'filters,', 'kernel_size=3,', 'stride=1,', 'conv_shortcut=False,', 'name=None):', 'layers', '=', 'tf.keras.layers', 'bn_axis', '=', '3', 'if', 'tf.keras.backend.image_data_format()', '==', "'channels_last'", 'else', '1', 'preact', '=', 'layers.BatchNormalization(axis=bn_axis,', 'epsilon=1.001e... | 975,294 |
sek788432/Waymo-2D-Object-Detection | bifpn_utils.py | create_downsample_feature_map_ops | create_downsample_feature_map_ops | Creates Keras layers for downsampling feature maps. | [
"Creates",
"Keras",
"layers",
"for",
"downsampling",
"feature",
"maps."
] | def create_downsample_feature_map_ops(scale, downsample_method, conv_hyperparams, is_training, freeze_batchnorm, name):
layers = []
padding = 'SAME'
stride = int(scale)
kernel_size = stride + 1
if downsample_method == 'max_pooling':
layers.append(tf.keras.layers.MaxPooling2D(pool_size=kernel... | ['def', 'create_downsample_feature_map_ops(scale,', 'downsample_method,', 'conv_hyperparams,', 'is_training,', 'freeze_batchnorm,', 'name):', 'layers', '=', '[]', 'padding', '=', "'SAME'", 'stride', '=', 'int(scale)', 'kernel_size', '=', 'stride', '+', '1', 'if', 'downsample_method', '==', "'max_pooling':", 'layers.app... | 975,362 |
sek788432/Waymo-2D-Object-Detection | config_util_test.py | ConfigUtilTest.testOverwriteSampleFromDatasetWeights | testOverwriteSampleFromDatasetWeights | Tests config override for sample_from_datasets_weights. | [
"Tests",
"config",
"override",
"for",
"sample_from_datasets_weights."
] | def testOverwriteSampleFromDatasetWeights(self):
pipeline_config = pipeline_pb2.TrainEvalPipelineConfig()
pipeline_config.train_input_reader.sample_from_datasets_weights.extend([1, 2])
pipeline_config_path = os.path.join(self.get_temp_dir(), 'pipeline.config')
_write_config(pipeline_config, pipeline_con... | ['def', 'testOverwriteSampleFromDatasetWeights(self):', 'pipeline_config', '=', 'pipeline_pb2.TrainEvalPipelineConfig()', 'pipeline_config.train_input_reader.sample_from_datasets_weights.extend([1,', '2])', 'pipeline_config_path', '=', 'os.path.join(self.get_temp_dir(),', "'pipeline.config')", '_write_config(pipeline_c... | 975,401 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.