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
openvinotoolkit/training_extensions
test_tiling_detection.py
TestTilingDetection.test_tiling_train_dataloader
test_tiling_train_dataloader
Test that the training dataloader is built correctly for tiling.
[ "Test", "that", "the", "training", "dataloader", "is", "built", "correctly", "for", "tiling." ]
def test_tiling_train_dataloader(self): dataset = build_dataset(self.train_data_cfg) train_dataloader = build_dataloader(dataset, **self.dataloader_cfg) for data in train_dataloader: assert isinstance(data['img'].data[0], torch.Tensor) assert isinstance(data['gt_bboxes'].data[0][0], torch.Te...
['def', 'test_tiling_train_dataloader(self):', 'dataset', '=', 'build_dataset(self.train_data_cfg)', 'train_dataloader', '=', 'build_dataloader(dataset,', '**self.dataloader_cfg)', 'for', 'data', 'in', 'train_dataloader:', 'assert', "isinstance(data['img'].data[0],", 'torch.Tensor)', 'assert', "isinstance(data['gt_bbox...
919,353
openvinotoolkit/training_extensions
test_tiling_detection.py
TestTilingDetection.test_inference_merge
test_inference_merge
Test that the inference merge works correctly.
[ "Test", "that", "the", "inference", "merge", "works", "correctly." ]
def test_inference_merge(self): dataset = build_dataset(self.test_data_cfg) results: List[List[np.ndarray]] = [] for i in range(len(dataset)): results.append([]) for _ in range(len(self.labels)): results[i].append(np.zeros((0, 5), dtype=np.float32)) for i in range(len(dataset...
['def', 'test_inference_merge(self):', 'dataset', '=', 'build_dataset(self.test_data_cfg)', 'results:', 'List[List[np.ndarray]]', '=', '[]', 'for', 'i', 'in', 'range(len(dataset)):', 'results.append([])', 'for', '_', 'in', 'range(len(self.labels)):', 'results[i].append(np.zeros((0,', '5),', 'dtype=np.float32))', 'for',...
919,355
openvinotoolkit/training_extensions
test_tiling_detection.py
TestTilingDetection.test_merge_feature_vectors
test_merge_feature_vectors
Test that the merge feature vectors works correctly.
[ "Test", "that", "the", "merge", "feature", "vectors", "works", "correctly." ]
def test_merge_feature_vectors(self): dataset = build_dataset(self.test_data_cfg) feature_vectors: List[np.ndarray] = [] vectors_per_image = 5 vector_length = 10 feature_vectors = [np.zeros((vectors_per_image, vector_length), dtype=np.float32) for _ in range(len(dataset))] merged_vectors = datas...
['def', 'test_merge_feature_vectors(self):', 'dataset', '=', 'build_dataset(self.test_data_cfg)', 'feature_vectors:', 'List[np.ndarray]', '=', '[]', 'vectors_per_image', '=', '5', 'vector_length', '=', '10', 'feature_vectors', '=', '[np.zeros((vectors_per_image,', 'vector_length),', 'dtype=np.float32)', 'for', '_', 'in...
919,356
openvinotoolkit/training_extensions
test_tiling_detection.py
TestTilingDetection.test_tile_ir_scale_deploy
test_tile_ir_scale_deploy
Test that the IR scale factor is correctly applied during inference.
[ "Test", "that", "the", "IR", "scale", "factor", "is", "correctly", "applied", "during", "inference." ]
def test_tile_ir_scale_deploy(self, tmp_dir_path, scale_factor): model_template = parse_model_template(os.path.join(DEFAULT_ISEG_TEMPLATE_DIR, 'template.yaml')) hyper_parameters = create(model_template.hyper_parameters.data) hyper_parameters.tiling_parameters.enable_tiling = True hyper_parameters.tiling...
['def', 'test_tile_ir_scale_deploy(self,', 'tmp_dir_path,', 'scale_factor):', 'model_template', '=', 'parse_model_template(os.path.join(DEFAULT_ISEG_TEMPLATE_DIR,', "'template.yaml'))", 'hyper_parameters', '=', 'create(model_template.hyper_parameters.data)', 'hyper_parameters.tiling_parameters.enable_tiling', '=', 'Tru...
919,359
openvinotoolkit/training_extensions
test_compose.py
TestProbCompose.test_dict_transforms
test_dict_transforms
Test whether dict transforms are correctly appended.
[ "Test", "whether", "dict", "transforms", "are", "correctly", "appended." ]
def test_dict_transforms(self) -> None: prob_compose = ProbCompose(transforms=[dict(type='Resize')], probs=[0.7]) assert repr(prob_compose.transforms[0]) == 'Resize(img_scale=None, multiscale_mode=range, ratio_range=None, keep_ratio=True)'
['def', 'test_dict_transforms(self)', '->', 'None:', 'prob_compose', '=', "ProbCompose(transforms=[dict(type='Resize')],", 'probs=[0.7])', 'assert', 'repr(prob_compose.transforms[0])', '==', "'Resize(img_scale=None,", 'multiscale_mode=range,', 'ratio_range=None,', "keep_ratio=True)'"]
919,365
openvinotoolkit/training_extensions
test_compose.py
TestProbCompose.test_invalid_transform_type
test_invalid_transform_type
Test invalid transform type raises error.
[ "Test", "invalid", "transform", "type", "raises", "error." ]
def test_invalid_transform_type(self) -> None: with pytest.raises(TypeError): transforms = ['Dummy Transform'] probs = [0.5] pipeline = ProbCompose(transforms, probs) del pipeline
['def', 'test_invalid_transform_type(self)', '->', 'None:', 'with', 'pytest.raises(TypeError):', 'transforms', '=', "['Dummy", "Transform']", 'probs', '=', '[0.5]', 'pipeline', '=', 'ProbCompose(transforms,', 'probs)', 'del', 'pipeline']
919,366
openvinotoolkit/training_extensions
test_compose.py
TestMaskCompose.test_keep_original_true
test_keep_original_true
Test that the mixed image is added as aux_img when keep_original is True.
[ "Test", "that", "the", "mixed", "image", "is", "added", "as", "aux_img", "when", "keep_original", "is", "True." ]
def test_keep_original_true(self, data: dict[str, np.ndarray]) -> None: transforms = [dict(type='TestTransform')] pipeline = MaskCompose(transforms=transforms, prob=1.0, keep_original=True) mixed_data = pipeline(data) assert np.array_equal(mixed_data['img'], mixed_data['aux_img']) assert np.array_eq...
['def', 'test_keep_original_true(self,', 'data:', 'dict[str,', 'np.ndarray])', '->', 'None:', 'transforms', '=', "[dict(type='TestTransform')]", 'pipeline', '=', 'MaskCompose(transforms=transforms,', 'prob=1.0,', 'keep_original=True)', 'mixed_data', '=', 'pipeline(data)', 'assert', "np.array_equal(mixed_data['img'],", ...
919,369
openvinotoolkit/training_extensions
test_compose.py
TestMaskCompose.test_callable_transform
test_callable_transform
Test callable transform is appended to the list of transforms.
[ "Test", "callable", "transform", "is", "appended", "to", "the", "list", "of", "transforms." ]
def test_callable_transform(self, data: dict[str, np.ndarray]) -> None: crop_size = (10, 10) transform = RandomCrop(crop_size=crop_size) pipeline = MaskCompose(transforms=[transform], prob=1.0, keep_original=False) mixed_data = pipeline(data) assert mixed_data['img_shape'][:2] == crop_size
['def', 'test_callable_transform(self,', 'data:', 'dict[str,', 'np.ndarray])', '->', 'None:', 'crop_size', '=', '(10,', '10)', 'transform', '=', 'RandomCrop(crop_size=crop_size)', 'pipeline', '=', 'MaskCompose(transforms=[transform],', 'prob=1.0,', 'keep_original=False)', 'mixed_data', '=', 'pipeline(data)', 'assert', ...
919,370
openvinotoolkit/training_extensions
test_compose.py
TestMaskCompose.test_apply_transforms_returns_none
test_apply_transforms_returns_none
Test that None is returned when apply_transforms returns None.
[ "Test", "that", "None", "is", "returned", "when", "apply_transforms", "returns", "None." ]
def test_apply_transforms_returns_none(self, data: dict[str, np.ndarray]) -> None: transforms = [dict(type='RandomFlip', prob=0.5, direction='horizontal'), lambda x: None] pipeline = MaskCompose(transforms=transforms, prob=1.0, keep_original=False) with pytest.raises(AssertionError): mixed_data = pi...
['def', 'test_apply_transforms_returns_none(self,', 'data:', 'dict[str,', 'np.ndarray])', '->', 'None:', 'transforms', '=', "[dict(type='RandomFlip',", 'prob=0.5,', "direction='horizontal'),", 'lambda', 'x:', 'None]', 'pipeline', '=', 'MaskCompose(transforms=transforms,', 'prob=1.0,', 'keep_original=False)', 'with', 'p...
919,373
openvinotoolkit/training_extensions
test_transforms.py
TestTwoCropTransform.test_call_with_single_pipeline
test_call_with_single_pipeline
Test __call__ with single pipeline.
[ "Test", "__call__", "with", "single", "pipeline." ]
def test_call_with_single_pipeline(self, mocker, inputs_np: Dict[str, Any]) -> None: self.two_crop_transform.is_both = False results = self.two_crop_transform(inputs_np) assert isinstance(results, dict) assert 'img' in results and results['img'].ndim == 3 assert 'gt_semantic_seg' in results and resu...
['def', 'test_call_with_single_pipeline(self,', 'mocker,', 'inputs_np:', 'Dict[str,', 'Any])', '->', 'None:', 'self.two_crop_transform.is_both', '=', 'False', 'results', '=', 'self.two_crop_transform(inputs_np)', 'assert', 'isinstance(results,', 'dict)', 'assert', "'img'", 'in', 'results', 'and', "results['img'].ndim",...
919,374
openvinotoolkit/training_extensions
test_schedulers.py
TestSchedulers.test_poly_scalar_scheduler_by_epoch_false
test_poly_scalar_scheduler_by_epoch_false
Test poly scalar scheduler.
[ "Test", "poly", "scalar", "scheduler." ]
def test_poly_scalar_scheduler_by_epoch_false(self): scheduler = PolyScalarScheduler(start_scale=30.0, end_scale=0.0, num_iters=100, power=0.9, by_epoch=False) assert scheduler(0, 1) == 30.0 assert scheduler(1, 1) < 30.0 assert scheduler(2, 1) < scheduler(1, 1) assert scheduler(3, 1) < scheduler(2, ...
['def', 'test_poly_scalar_scheduler_by_epoch_false(self):', 'scheduler', '=', 'PolyScalarScheduler(start_scale=30.0,', 'end_scale=0.0,', 'num_iters=100,', 'power=0.9,', 'by_epoch=False)', 'assert', 'scheduler(0,', '1)', '==', '30.0', 'assert', 'scheduler(1,', '1)', '<', '30.0', 'assert', 'scheduler(2,', '1)', '<', 'sch...
919,383
openvinotoolkit/training_extensions
test_dataset.py
dataset_polygon
dataset_polygon
Set dataset with polygon.
[ "Set", "dataset", "with", "polygon." ]
def dataset_polygon() -> DatasetEntity: return generate_visual_prompting_dataset(use_mask=False)
['def', 'dataset_polygon()', '->', 'DatasetEntity:', 'return', 'generate_visual_prompting_dataset(use_mask=False)']
919,387
openvinotoolkit/training_extensions
test_segment_anything.py
TestSegmentAnything.test_load_checkpoint_with_state_dict
test_load_checkpoint_with_state_dict
Test load_checkpoint with state_dict.
[ "Test", "load_checkpoint", "with", "state_dict." ]
def test_load_checkpoint_with_state_dict(self, mocker, is_backbone_arg: bool, state_dict: OrderedDict): mocker.patch('otx.algorithms.visual_prompting.adapters.pytorch_lightning.models.visual_prompters.segment_anything.SegmentAnything.freeze_networks') mocker.patch('otx.algorithms.visual_prompting.adapters.pytor...
['def', 'test_load_checkpoint_with_state_dict(self,', 'mocker,', 'is_backbone_arg:', 'bool,', 'state_dict:', 'OrderedDict):', "mocker.patch('otx.algorithms.visual_prompting.adapters.pytorch_lightning.models.visual_prompters.segment_anything.SegmentAnything.freeze_networks')", "mocker.patch('otx.algorithms.visual_prompt...
919,389
openvinotoolkit/training_extensions
test_segment_anything.py
TestSegmentAnything.test_load_checkpoint_from_local_checkpoint
test_load_checkpoint_from_local_checkpoint
Test load_checkpoint from local checkpoint.
[ "Test", "load_checkpoint", "from", "local", "checkpoint." ]
def test_load_checkpoint_from_local_checkpoint(self, mocker, monkeypatch, checkpoint: str): mocker.patch('otx.algorithms.visual_prompting.adapters.pytorch_lightning.models.visual_prompters.segment_anything.SegmentAnything.freeze_networks') mocker.patch('otx.algorithms.visual_prompting.adapters.pytorch_lightning...
['def', 'test_load_checkpoint_from_local_checkpoint(self,', 'mocker,', 'monkeypatch,', 'checkpoint:', 'str):', "mocker.patch('otx.algorithms.visual_prompting.adapters.pytorch_lightning.models.visual_prompters.segment_anything.SegmentAnything.freeze_networks')", "mocker.patch('otx.algorithms.visual_prompting.adapters.py...
919,392
openvinotoolkit/training_extensions
test_inference.py
TestInferenceTask.test_load_model_without_otx_model_or_with_lightning_ckpt
test_load_model_without_otx_model_or_with_lightning_ckpt
Test load_model to resume.
[ "Test", "load_model", "to", "resume." ]
def test_load_model_without_otx_model_or_with_lightning_ckpt(self, mocker, load_inference_task, path: str, resume: bool): mocker_segment_anything = mocker.patch('otx.algorithms.visual_prompting.adapters.pytorch_lightning.models.SegmentAnything') inference_task = load_inference_task(path=path, resume=resume) ...
['def', 'test_load_model_without_otx_model_or_with_lightning_ckpt(self,', 'mocker,', 'load_inference_task,', 'path:', 'str,', 'resume:', 'bool):', 'mocker_segment_anything', '=', "mocker.patch('otx.algorithms.visual_prompting.adapters.pytorch_lightning.models.SegmentAnything')", 'inference_task', '=', 'load_inference_t...
919,395
openvinotoolkit/training_extensions
general.py
label_schema_example
label_schema_example
Returns a label schema example.
[ "Returns", "a", "label", "schema", "example." ]
def label_schema_example(): return LabelSchemaExample()
['def', 'label_schema_example():', 'return', 'LabelSchemaExample()']
919,701
openvinotoolkit/training_extensions
test_datetime_mapper.py
TestDatetimeMapper.test_serialization_deserialization
test_serialization_deserialization
This test serializes datetime, deserializes serialized datetime and compares with original one.
[ "This", "test", "serializes", "datetime,", "deserializes", "serialized", "datetime", "and", "compares", "with", "original", "one." ]
def test_serialization_deserialization(self): original_time = now() serialized_time = DatetimeMapper.forward(original_time) assert serialized_time == original_time.strftime('%Y-%m-%dT%H:%M:%S.%f') deserialized_time = DatetimeMapper.backward(serialized_time) assert original_time == deserialized_time ...
['def', 'test_serialization_deserialization(self):', 'original_time', '=', 'now()', 'serialized_time', '=', 'DatetimeMapper.forward(original_time)', 'assert', 'serialized_time', '==', "original_time.strftime('%Y-%m-%dT%H:%M:%S.%f')", 'deserialized_time', '=', 'DatetimeMapper.backward(serialized_time)', 'assert', 'origi...
919,704
openvinotoolkit/training_extensions
test_id_mapper.py
TestIDMapper.test_serialized_representiaton
test_serialized_representiaton
This test serializes ID and checks serialized representation.
[ "This", "test", "serializes", "ID", "and", "checks", "serialized", "representation." ]
def test_serialized_representiaton(self): id_ = ID('21434231456') serialized_id = IDMapper.forward(id_) assert serialized_id == '21434231456'
['def', 'test_serialized_representiaton(self):', 'id_', '=', "ID('21434231456')", 'serialized_id', '=', 'IDMapper.forward(id_)', 'assert', 'serialized_id', '==', "'21434231456'"]
919,705
openvinotoolkit/training_extensions
test_cli_builder.py
TestOTXCLIBuilder.test_builder_build_backbone_config_abnormal_output_path
test_builder_build_backbone_config_abnormal_output_path
Raise ValueError with wrong output_path.
[ "Raise", "ValueError", "with", "wrong", "output_path." ]
def test_builder_build_backbone_config_abnormal_output_path(self, backbone_type: str) -> None: tmp_backbone_path = self.tmp_dir_path / 'wrong.path' with pytest.raises(ValueError): self.otx_builder.build_backbone_config(backbone_type, tmp_backbone_path)
['def', 'test_builder_build_backbone_config_abnormal_output_path(self,', 'backbone_type:', 'str)', '->', 'None:', 'tmp_backbone_path', '=', 'self.tmp_dir_path', '/', "'wrong.path'", 'with', 'pytest.raises(ValueError):', 'self.otx_builder.build_backbone_config(backbone_type,', 'tmp_backbone_path)']
919,834
openvinotoolkit/training_extensions
test_cli_builder.py
TestOTXCLIBuilder.test_builder_merge_backbone_abnormal_backbone_path
test_builder_merge_backbone_abnormal_backbone_path
Raise ValueError with wrong backbone_config_path.
[ "Raise", "ValueError", "with", "wrong", "backbone_config_path." ]
def test_builder_merge_backbone_abnormal_backbone_path(self) -> None: workspace_path = self.tmp_dir_path / 'test_builder_merge_backbone' tmp_model_path = workspace_path / 'model.py' with pytest.raises(ValueError): self.otx_builder.merge_backbone(tmp_model_path, 'unexpected')
['def', 'test_builder_merge_backbone_abnormal_backbone_path(self)', '->', 'None:', 'workspace_path', '=', 'self.tmp_dir_path', '/', "'test_builder_merge_backbone'", 'tmp_model_path', '=', 'workspace_path', '/', "'model.py'", 'with', 'pytest.raises(ValueError):', 'self.otx_builder.merge_backbone(tmp_model_path,', "'unex...
919,836
openvinotoolkit/training_extensions
test_cli_builder.py
TestOTXCLIBuilder.test_builder_merge_backbone
test_builder_merge_backbone
Update model config without backbone's out_indices.
[ "Update", "model", "config", "without", "backbone's", "out_indices." ]
def test_builder_merge_backbone(self, mocker) -> None: mocker.patch('otx.cli.builder.builder.Path.exists', return_value=True) mock_backbone_config = {'backbone': {'type': 'torchvision.resnet18', 'use_out_indices': True, 'out_indices': [0, 1, 2]}} mock_mmcv_load = mocker.patch('otx.cli.builder.builder.mmcv.l...
['def', 'test_builder_merge_backbone(self,', 'mocker)', '->', 'None:', "mocker.patch('otx.cli.builder.builder.Path.exists',", 'return_value=True)', 'mock_backbone_config', '=', "{'backbone':", "{'type':", "'torchvision.resnet18',", "'use_out_indices':", 'True,', "'out_indices':", '[0,', '1,', '2]}}', 'mock_mmcv_load', ...
919,837
openvinotoolkit/training_extensions
test_cli_builder.py
TestOTXBuilderUtils.test_update_backbone_args_required_args
test_update_backbone_args_required_args
Update required Args in Backbone (Check Missing Args).
[ "Update", "required", "Args", "in", "Backbone", "(Check", "Missing", "Args)." ]
def test_update_backbone_args_required_args(self) -> None: def mock_init(self, depth, a=1, b=2): super(MockBackbone, self).__init__() self.backbone.__init__ = mock_init self.registry.register_module(module=self.backbone, force=True) backbone_config = {'type': 'MockBackbone'} inputs = {'back...
['def', 'test_update_backbone_args_required_args(self)', '->', 'None:', 'def', 'mock_init(self,', 'depth,', 'a=1,', 'b=2):', 'super(MockBackbone,', 'self).__init__()', 'self.backbone.__init__', '=', 'mock_init', 'self.registry.register_module(module=self.backbone,', 'force=True)', 'backbone_config', '=', "{'type':", "'...
919,840
openvinotoolkit/training_extensions
test_cli_builder.py
TestOTXBuilderUtils.test_update_backbone_args_with_option
test_update_backbone_args_with_option
Update backbone using the backbone name from the backbone list (Check updating with options).
[ "Update", "backbone", "using", "the", "backbone", "name", "from", "the", "backbone", "list", "(Check", "updating", "with", "options)." ]
def test_update_backbone_args_with_option(self) -> None: child_registry = MockRegistry(name='mmseg', parent=self.registry, scope='mmseg') backbone_config = {'type': 'mmseg.ResNet'} child_registry.register_module(name='ResNet', module=self.backbone, force=True) inputs = {'backbone_config': backbone_confi...
['def', 'test_update_backbone_args_with_option(self)', '->', 'None:', 'child_registry', '=', "MockRegistry(name='mmseg',", 'parent=self.registry,', "scope='mmseg')", 'backbone_config', '=', "{'type':", "'mmseg.ResNet'}", "child_registry.register_module(name='ResNet',", 'module=self.backbone,', 'force=True)', 'inputs', ...
919,842
openvinotoolkit/training_extensions
test_cli_builder.py
TestOTXBuilderUtils.test_update_backbone_args_without_options
test_update_backbone_args_without_options
Update backbone using the backbone name from the backbone list (Check updating without options).
[ "Update", "backbone", "using", "the", "backbone", "name", "from", "the", "backbone", "list", "(Check", "updating", "without", "options)." ]
def test_update_backbone_args_without_options(self) -> None: def mock_init(self, extra): super(MockBackbone, self).__init__() backbone_config = {'type': 'mmseg.HRNet'} self.backbone.__init__ = mock_init child_registry = MockRegistry(name='mmseg', parent=self.registry, scope='mmseg') child_r...
['def', 'test_update_backbone_args_without_options(self)', '->', 'None:', 'def', 'mock_init(self,', 'extra):', 'super(MockBackbone,', 'self).__init__()', 'backbone_config', '=', "{'type':", "'mmseg.HRNet'}", 'self.backbone.__init__', '=', 'mock_init', 'child_registry', '=', "MockRegistry(name='mmseg',", 'parent=self.re...
919,843
openvinotoolkit/training_extensions
test_cli_builder.py
TestOTXBuilderUtils.test_update_backbone_args_abnormal_backbone_type
test_update_backbone_args_abnormal_backbone_type
Raise ValueError with unexpected backbone.
[ "Raise", "ValueError", "with", "unexpected", "backbone." ]
def test_update_backbone_args_abnormal_backbone_type(self) -> None: backbone_config = {'type': 'unexpected'} inputs = {'backbone_config': backbone_config, 'registry': self.registry, 'backend': 'mmseg'} with pytest.raises(ValueError): update_backbone_args(**inputs)
['def', 'test_update_backbone_args_abnormal_backbone_type(self)', '->', 'None:', 'backbone_config', '=', "{'type':", "'unexpected'}", 'inputs', '=', "{'backbone_config':", 'backbone_config,', "'registry':", 'self.registry,', "'backend':", "'mmseg'}", 'with', 'pytest.raises(ValueError):', 'update_backbone_args(**inputs)...
919,844
openvinotoolkit/training_extensions
test_cli_builder.py
TestOTXBuilderUtils.test_update_channels_abnormal_inputs
test_update_channels_abnormal_inputs
Raise NotImplementedError with unexpected model key.
[ "Raise", "NotImplementedError", "with", "unexpected", "model", "key." ]
def test_update_channels_abnormal_inputs(self) -> None: out_channels = (10, 20, 30, 40) cfg_dict = {'model': {'unexpected': {'in_channels': (0, 1, 2)}}} model_config = OTXConfig(cfg_dict=cfg_dict) with pytest.raises(NotImplementedError): update_channels(model_config, out_channels)
['def', 'test_update_channels_abnormal_inputs(self)', '->', 'None:', 'out_channels', '=', '(10,', '20,', '30,', '40)', 'cfg_dict', '=', "{'model':", "{'unexpected':", "{'in_channels':", '(0,', '1,', '2)}}}', 'model_config', '=', 'OTXConfig(cfg_dict=cfg_dict)', 'with', 'pytest.raises(NotImplementedError):', 'update_chan...
919,846
openvinotoolkit/training_extensions
test_multi_gpu.py
test_set_arguments_to_argv_key_exist
test_set_arguments_to_argv_key_exist
Test a case where key already exists and value exists.
[ "Test", "a", "case", "where", "key", "already", "exists", "and", "value", "exists." ]
def test_set_arguments_to_argv_key_exist(mock_argv_without_params): other_val = 'other_val' set_arguments_to_argv('--a_key', other_val) assert mock_argv_without_params[1] == other_val
['def', 'test_set_arguments_to_argv_key_exist(mock_argv_without_params):', 'other_val', '=', "'other_val'", "set_arguments_to_argv('--a_key',", 'other_val)', 'assert', 'mock_argv_without_params[1]', '==', 'other_val']
919,852
openvinotoolkit/training_extensions
test_multi_gpu.py
test_set_arguments_to_argv_key_exist_none_val
test_set_arguments_to_argv_key_exist_none_val
Test a case where key already exists in argv and value doesn't exists.
[ "Test", "a", "case", "where", "key", "already", "exists", "in", "argv", "and", "value", "doesn't", "exists." ]
def test_set_arguments_to_argv_key_exist_none_val(mock_argv_without_params): expected_result = deepcopy(mock_argv_without_params) set_arguments_to_argv('--a_key') assert mock_argv_without_params == expected_result
['def', 'test_set_arguments_to_argv_key_exist_none_val(mock_argv_without_params):', 'expected_result', '=', 'deepcopy(mock_argv_without_params)', "set_arguments_to_argv('--a_key')", 'assert', 'mock_argv_without_params', '==', 'expected_result']
919,854
openvinotoolkit/training_extensions
test_multi_gpu.py
test_set_arguments_to_argv_key_after_param_non_val
test_set_arguments_to_argv_key_after_param_non_val
Test a case where key to set doesn't exists in argv and order of key is after params and vlaue doesn't exist.
[ "Test", "a", "case", "where", "key", "to", "set", "doesn't", "exists", "in", "argv", "and", "order", "of", "key", "is", "after", "params", "and", "vlaue", "doesn't", "exist." ]
def test_set_arguments_to_argv_key_after_param_non_val(mock_argv_with_params): set_arguments_to_argv('--other_key', after_params=True) param_idx = mock_argv_with_params.index('params') new_key_idx = mock_argv_with_params.index('--other_key') assert new_key_idx > param_idx assert '--other_key' in moc...
['def', 'test_set_arguments_to_argv_key_after_param_non_val(mock_argv_with_params):', "set_arguments_to_argv('--other_key',", 'after_params=True)', 'param_idx', '=', "mock_argv_with_params.index('params')", 'new_key_idx', '=', "mock_argv_with_params.index('--other_key')", 'assert', 'new_key_idx', '>', 'param_idx', 'ass...
919,858
openvinotoolkit/training_extensions
test_segmentation_adapter.py
TestSelfSLSegmentationDatasetAdapter.test_import_dataset_just_load_masks
test_import_dataset_just_load_masks
Test _import_datasets when just loading all masks.
[ "Test", "_import_datasets", "when", "just", "loading", "all", "masks." ]
def test_import_dataset_just_load_masks(self, mocker): spy_create_pseudo_masks = mocker.spy(SelfSLSegmentationDatasetAdapter, 'create_pseudo_masks') _ = SelfSLSegmentationDatasetAdapter(task_type=self.task_type, train_data_roots=self.train_data_roots, pseudo_mask_dir=self.pseudo_mask_dir) spy_create_pseudo_...
['def', 'test_import_dataset_just_load_masks(self,', 'mocker):', 'spy_create_pseudo_masks', '=', 'mocker.spy(SelfSLSegmentationDatasetAdapter,', "'create_pseudo_masks')", '_', '=', 'SelfSLSegmentationDatasetAdapter(task_type=self.task_type,', 'train_data_roots=self.train_data_roots,', 'pseudo_mask_dir=self.pseudo_mask_...
919,862
nlp-uoregon/trankit
adapter_config.py
ModelAdaptersConfig.set_config
set_config
Sets the default adapter configuration of the specified adapter type.
[ "Sets", "the", "default", "adapter", "configuration", "of", "the", "specified", "adapter", "type." ]
def set_config(self, adapter_type: AdapterType, config: Union[dict, str, AdapterConfig]): assert len(self.adapter_list(adapter_type)) < 1, 'Can only set new config if no adapters have been added.' if isinstance(config, Mapping) or config in ADAPTER_CONFIG_MAP: self.config_map[adapter_type] = config ...
['def', 'set_config(self,', 'adapter_type:', 'AdapterType,', 'config:', 'Union[dict,', 'str,', 'AdapterConfig]):', 'assert', 'len(self.adapter_list(adapter_type))', '<', '1,', "'Can", 'only', 'set', 'new', 'config', 'if', 'no', 'adapters', 'have', 'been', "added.'", 'if', 'isinstance(config,', 'Mapping)', 'or', 'config...
920,016
nlp-uoregon/trankit
adapter_model_mixin.py
AdapterFusionLoader.load
load
Loads a AdapterFusion module from the given directory.
[ "Loads", "a", "AdapterFusion", "module", "from", "the", "given", "directory." ]
def load(self, save_directory, load_as=None, loading_info=None): if not exists(join(save_directory, ADAPTERFUSION_WEIGHTS_NAME)): if self.error_on_missing: raise ValueError('Loading path should be a directory where AdapterFusion is saved.') else: logger.debug("No matching ada...
['def', 'load(self,', 'save_directory,', 'load_as=None,', 'loading_info=None):', 'if', 'not', 'exists(join(save_directory,', 'ADAPTERFUSION_WEIGHTS_NAME)):', 'if', 'self.error_on_missing:', 'raise', "ValueError('Loading", 'path', 'should', 'be', 'a', 'directory', 'where', 'AdapterFusion', 'is', "saved.')", 'else:', 'lo...
920,026
nlp-uoregon/trankit
adapter_model_mixin.py
ModelAdaptersMixin.set_adapter_config
set_adapter_config
Sets the adapter configuration of the specified adapter type.
[ "Sets", "the", "adapter", "configuration", "of", "the", "specified", "adapter", "type." ]
def set_adapter_config(self, adapter_type: AdapterType, adapter_config): if AdapterType.has(adapter_type): self.config.adapters.set_config(adapter_type, adapter_config) else: raise ValueError('Invalid adapter type {}'.format(adapter_type))
['def', 'set_adapter_config(self,', 'adapter_type:', 'AdapterType,', 'adapter_config):', 'if', 'AdapterType.has(adapter_type):', 'self.config.adapters.set_config(adapter_type,', 'adapter_config)', 'else:', 'raise', "ValueError('Invalid", 'adapter', 'type', "{}'.format(adapter_type))"]
920,033
nlp-uoregon/trankit
adapter_model_mixin.py
ModelWithHeadsAdaptersMixin.train_fusion
train_fusion
Sets the model in mode for training of adapter fusion determined by a list of adapter names.
[ "Sets", "the", "model", "in", "mode", "for", "training", "of", "adapter", "fusion", "determined", "by", "a", "list", "of", "adapter", "names." ]
def train_fusion(self, adapter_names: list): self.base_model.train_fusion(adapter_names)
['def', 'train_fusion(self,', 'adapter_names:', 'list):', 'self.base_model.train_fusion(adapter_names)']
920,045
nlp-uoregon/trankit
seq2seq.py
Seq2SeqModel.predict
predict
Predict with beam search.
[ "Predict", "with", "beam", "search." ]
def predict(self, src, src_mask, pos=None, beam_size=5): if beam_size == 1: return self.predict_greedy(src, src_mask, pos=pos) enc_inputs = self.embedding(src) batch_size = enc_inputs.size(0) if self.use_pos: assert pos is not None, 'Missing POS input for seq2seq lemmatizer.' pos...
['def', 'predict(self,', 'src,', 'src_mask,', 'pos=None,', 'beam_size=5):', 'if', 'beam_size', '==', '1:', 'return', 'self.predict_greedy(src,', 'src_mask,', 'pos=pos)', 'enc_inputs', '=', 'self.embedding(src)', 'batch_size', '=', 'enc_inputs.size(0)', 'if', 'self.use_pos:', 'assert', 'pos', 'is', 'not', 'None,', "'Mis...
920,452
nlp-uoregon/trankit
lemma_model.py
Trainer.skip_seq2seq
skip_seq2seq
Determine if we can skip the seq2seq module when ensembling with the frequency lexicon.
[ "Determine", "if", "we", "can", "skip", "the", "seq2seq", "module", "when", "ensembling", "with", "the", "frequency", "lexicon." ]
def skip_seq2seq(self, pairs): skip = [] for p in pairs: (w, pos) = p if (w, pos) in self.composite_dict: skip.append(True) elif w in self.word_dict: skip.append(True) else: skip.append(False) return skip
['def', 'skip_seq2seq(self,', 'pairs):', 'skip', '=', '[]', 'for', 'p', 'in', 'pairs:', '(w,', 'pos)', '=', 'p', 'if', '(w,', 'pos)', 'in', 'self.composite_dict:', 'skip.append(True)', 'elif', 'w', 'in', 'self.word_dict:', 'skip.append(True)', 'else:', 'skip.append(False)', 'return', 'skip']
920,456
nlp-uoregon/trankit
mwt_model.py
Trainer.predict_dict
predict_dict
Predict a list of expansions given words.
[ "Predict", "a", "list", "of", "expansions", "given", "words." ]
def predict_dict(self, words): expansions = [] for w in words: if w in self.expansion_dict: expansions += [self.expansion_dict[w]] elif w.lower() in self.expansion_dict: expansions += [self.expansion_dict[w.lower()]] else: expansions += [w] return ...
['def', 'predict_dict(self,', 'words):', 'expansions', '=', '[]', 'for', 'w', 'in', 'words:', 'if', 'w', 'in', 'self.expansion_dict:', 'expansions', '+=', '[self.expansion_dict[w]]', 'elif', 'w.lower()', 'in', 'self.expansion_dict:', 'expansions', '+=', '[self.expansion_dict[w.lower()]]', 'else:', 'expansions', '+=', '...
920,459
nlp-uoregon/trankit
conll.py
CoNLL.conll_as_string
conll_as_string
Dump the loaded CoNLL-U format list data to string.
[ "Dump", "the", "loaded", "CoNLL-U", "format", "list", "data", "to", "string." ]
def conll_as_string(doc): return_string = '' for sent in doc: for ln in sent: return_string += '\t'.join(ln) + '\n' return_string += '\n' return return_string
['def', 'conll_as_string(doc):', 'return_string', '=', "''", 'for', 'sent', 'in', 'doc:', 'for', 'ln', 'in', 'sent:', 'return_string', '+=', "'\\t'.join(ln)", '+', "'\\n'", 'return_string', '+=', "'\\n'", 'return', 'return_string']
920,467
nlp-uoregon/trankit
conll.py
CoNLL.dict2conll
dict2conll
Convert the dictionary format input data to the CoNLL-U format output data and write to a file.
[ "Convert", "the", "dictionary", "format", "input", "data", "to", "the", "CoNLL-U", "format", "output", "data", "and", "write", "to", "a", "file." ]
def dict2conll(doc_dict, filename): doc_conll = CoNLL.convert_dict(doc_dict) conll_string = CoNLL.conll_as_string(doc_conll) with open(filename, 'w') as outfile: outfile.write(conll_string)
['def', 'dict2conll(doc_dict,', 'filename):', 'doc_conll', '=', 'CoNLL.convert_dict(doc_dict)', 'conll_string', '=', 'CoNLL.conll_as_string(doc_conll)', 'with', 'open(filename,', "'w')", 'as', 'outfile:', 'outfile.write(conll_string)']
920,468
nlp-uoregon/trankit
seq2seq_utils.py
get_long_tensor
get_long_tensor
Convert (list of )+ tokens to a padded LongTensor.
[ "Convert", "(list", "of", ")+", "tokens", "to", "a", "padded", "LongTensor." ]
def get_long_tensor(tokens_list, batch_size, pad_id=PAD_ID): sizes = [] x = tokens_list while isinstance(x[0], list): sizes.append(max((len(y) for y in x))) x = [z for y in x for z in y] tokens = torch.LongTensor(batch_size, *sizes).fill_(pad_id) for (i, s) in enumerate(tokens_list):...
['def', 'get_long_tensor(tokens_list,', 'batch_size,', 'pad_id=PAD_ID):', 'sizes', '=', '[]', 'x', '=', 'tokens_list', 'while', 'isinstance(x[0],', 'list):', 'sizes.append(max((len(y)', 'for', 'y', 'in', 'x)))', 'x', '=', '[z', 'for', 'y', 'in', 'x', 'for', 'z', 'in', 'y]', 'tokens', '=', 'torch.LongTensor(batch_size,'...
920,472
nlp-uoregon/trankit
seq2seq_utils.py
sort_all
sort_all
Sort all fields by descending order of lens, and return the original indices.
[ "Sort", "all", "fields", "by", "descending", "order", "of", "lens,", "and", "return", "the", "original", "indices." ]
def sort_all(batch, lens): unsorted_all = [lens] + [range(len(lens))] + list(batch) sorted_all = [list(t) for t in zip(*sorted(zip(*unsorted_all), reverse=True))] return (sorted_all[2:], sorted_all[1])
['def', 'sort_all(batch,', 'lens):', 'unsorted_all', '=', '[lens]', '+', '[range(len(lens))]', '+', 'list(batch)', 'sorted_all', '=', '[list(t)', 'for', 't', 'in', 'zip(*sorted(zip(*unsorted_all),', 'reverse=True))]', 'return', '(sorted_all[2:],', 'sorted_all[1])']
920,473
nlp-uoregon/trankit
seq2seq_utils.py
unpack_mwt_batch
unpack_mwt_batch
Unpack a batch from the data loader.
[ "Unpack", "a", "batch", "from", "the", "data", "loader." ]
def unpack_mwt_batch(batch, use_cuda): if use_cuda: inputs = [b.cuda() if b is not None else None for b in batch[:4]] else: inputs = [b if b is not None else None for b in batch[:4]] orig_idx = batch[4] return (inputs, orig_idx)
['def', 'unpack_mwt_batch(batch,', 'use_cuda):', 'if', 'use_cuda:', 'inputs', '=', '[b.cuda()', 'if', 'b', 'is', 'not', 'None', 'else', 'None', 'for', 'b', 'in', 'batch[:4]]', 'else:', 'inputs', '=', '[b', 'if', 'b', 'is', 'not', 'None', 'else', 'None', 'for', 'b', 'in', 'batch[:4]]', 'orig_idx', '=', 'batch[4]', 'retu...
920,475
nlp-uoregon/trankit
seq2seq_utils.py
unmap_with_copy
unmap_with_copy
Unmap a list of list of indices, by optionally copying from src_tokens.
[ "Unmap", "a", "list", "of", "list", "of", "indices,", "by", "optionally", "copying", "from", "src_tokens." ]
def unmap_with_copy(indices, src_tokens, vocab): result = [] for (ind, tokens) in zip(indices, src_tokens): words = [] for idx in ind: if idx >= 0: words.append(vocab.id2word[idx]) else: idx = -idx - 1 words.append(tokens[id...
['def', 'unmap_with_copy(indices,', 'src_tokens,', 'vocab):', 'result', '=', '[]', 'for', '(ind,', 'tokens)', 'in', 'zip(indices,', 'src_tokens):', 'words', '=', '[]', 'for', 'idx', 'in', 'ind:', 'if', 'idx', '>=', '0:', 'words.append(vocab.id2word[idx])', 'else:', 'idx', '=', '-idx', '-', '1', 'words.append(tokens[idx...
920,481
nlp-uoregon/trankit
seq2seq_utils.py
prune_decoded_seqs
prune_decoded_seqs
Prune decoded sequences after EOS token.
[ "Prune", "decoded", "sequences", "after", "EOS", "token." ]
def prune_decoded_seqs(seqs): out = [] for s in seqs: if EOS in s: idx = s.index(EOS) out += [s[:idx]] else: out += [s] return out
['def', 'prune_decoded_seqs(seqs):', 'out', '=', '[]', 'for', 's', 'in', 'seqs:', 'if', 'EOS', 'in', 's:', 'idx', '=', 's.index(EOS)', 'out', '+=', '[s[:idx]]', 'else:', 'out', '+=', '[s]', 'return', 'out']
920,482
nlp-uoregon/trankit
seq2seq_utils.py
unsort
unsort
Unsort a sorted list, based on the original idx.
[ "Unsort", "a", "sorted", "list,", "based", "on", "the", "original", "idx." ]
def unsort(sorted_list, oidx): assert len(sorted_list) == len(oidx), 'Number of list elements must match with original indices.' (_, unsorted) = [list(t) for t in zip(*sorted(zip(oidx, sorted_list)))] return unsorted
['def', 'unsort(sorted_list,', 'oidx):', 'assert', 'len(sorted_list)', '==', 'len(oidx),', "'Number", 'of', 'list', 'elements', 'must', 'match', 'with', 'original', "indices.'", '(_,', 'unsorted)', '=', '[list(t)', 'for', 't', 'in', 'zip(*sorted(zip(oidx,', 'sorted_list)))]', 'return', 'unsorted']
920,485
nlp-uoregon/trankit
seq2seq_vocabs.py
BaseVocab.load_state_dict
load_state_dict
Returns a new Vocab instance constructed from a state dict.
[ "Returns", "a", "new", "Vocab", "instance", "constructed", "from", "a", "state", "dict." ]
def load_state_dict(cls, state_dict): new = cls() for (attr, value) in state_dict.items(): setattr(new, attr, value) return new
['def', 'load_state_dict(cls,', 'state_dict):', 'new', '=', 'cls()', 'for', '(attr,', 'value)', 'in', 'state_dict.items():', 'setattr(new,', 'attr,', 'value)', 'return', 'new']
920,490
yihengsun/TransBoost
core.py
ctypes2numpy
ctypes2numpy
Convert a ctypes pointer array to a numpy array.
[ "Convert", "a", "ctypes", "pointer", "array", "to", "a", "numpy", "array." ]
def ctypes2numpy(cptr, length, dtype): ctype = _numpy2ctypes_type(dtype) if not isinstance(cptr, ctypes.POINTER(ctype)): raise RuntimeError('expected {} pointer'.format(ctype)) res = np.zeros(length, dtype=dtype) if not ctypes.memmove(res.ctypes.data, cptr, length * res.strides[0]): rais...
['def', 'ctypes2numpy(cptr,', 'length,', 'dtype):', 'ctype', '=', '_numpy2ctypes_type(dtype)', 'if', 'not', 'isinstance(cptr,', 'ctypes.POINTER(ctype)):', 'raise', "RuntimeError('expected", '{}', "pointer'.format(ctype))", 'res', '=', 'np.zeros(length,', 'dtype=dtype)', 'if', 'not', 'ctypes.memmove(res.ctypes.data,', '...
920,495
yihengsun/TransBoost
core.py
ctypes2buffer
ctypes2buffer
Convert ctypes pointer to buffer type.
[ "Convert", "ctypes", "pointer", "to", "buffer", "type." ]
def ctypes2buffer(cptr, length): if not isinstance(cptr, ctypes.POINTER(ctypes.c_char)): raise RuntimeError('expected char pointer') res = bytearray(length) rptr = (ctypes.c_char * length).from_buffer(res) if not ctypes.memmove(rptr, cptr, length): raise RuntimeError('memmove failed') ...
['def', 'ctypes2buffer(cptr,', 'length):', 'if', 'not', 'isinstance(cptr,', 'ctypes.POINTER(ctypes.c_char)):', 'raise', "RuntimeError('expected", 'char', "pointer')", 'res', '=', 'bytearray(length)', 'rptr', '=', '(ctypes.c_char', '*', 'length).from_buffer(res)', 'if', 'not', 'ctypes.memmove(rptr,', 'cptr,', 'length):'...
920,497
yihengsun/TransBoost
core.py
c_str
c_str
Convert a python string to cstring.
[ "Convert", "a", "python", "string", "to", "cstring." ]
def c_str(string): return ctypes.c_char_p(string.encode('utf-8'))
['def', 'c_str(string):', 'return', "ctypes.c_char_p(string.encode('utf-8'))"]
920,498
yihengsun/TransBoost
core.py
DataIter.proxy
proxy
Handler of DMatrix proxy.
[ "Handler", "of", "DMatrix", "proxy." ]
def proxy(self): return self._handle
['def', 'proxy(self):', 'return', 'self._handle']
920,500
yihengsun/TransBoost
core.py
DataIter.reset_wrapper
reset_wrapper
A wrapper for user defined `reset` function.
[ "A", "wrapper", "for", "user", "defined", "`reset`", "function." ]
def reset_wrapper(self, this): self.reset()
['def', 'reset_wrapper(self,', 'this):', 'self.reset()']
920,501
yihengsun/TransBoost
sklearn.py
XGBModel.get_xgb_params
get_xgb_params
Get xgboost specific parameters.
[ "Get", "xgboost", "specific", "parameters." ]
def get_xgb_params(self): params = self.get_params() wrapper_specific = {'importance_type', 'kwargs', 'missing', 'n_estimators', 'use_label_encoder'} filtered = dict() for (k, v) in params.items(): if k not in wrapper_specific and (not callable(v)): filtered[k] = v return filtere...
['def', 'get_xgb_params(self):', 'params', '=', 'self.get_params()', 'wrapper_specific', '=', "{'importance_type',", "'kwargs',", "'missing',", "'n_estimators',", "'use_label_encoder'}", 'filtered', '=', 'dict()', 'for', '(k,', 'v)', 'in', 'params.items():', 'if', 'k', 'not', 'in', 'wrapper_specific', 'and', '(not', 'c...
920,552
sign-language-processing/transcription
dataset.py
PoseTextDataset.src
src
get detokenized preprocessed data in src language.
[ "get", "detokenized", "preprocessed", "data", "in", "src", "language." ]
def src(self) -> List[str]: return ['' for _ in self.dataset.data]
['def', 'src(self)', '->', 'List[str]:', 'return', "[''", 'for', '_', 'in', 'self.dataset.data]']
920,570
sign-language-processing/transcription
sign_language_tokenizer.py
SignLanguageTokenizer.post_process
post_process
JoeyNMT expects this method to exist for BLEU calculation.
[ "JoeyNMT", "expects", "this", "method", "to", "exist", "for", "BLEU", "calculation." ]
def post_process(self, tokens: List[str], generate_unk: bool=True): return ' '.join(tokens)
['def', 'post_process(self,', 'tokens:', 'List[str],', 'generate_unk:', 'bool=True):', 'return', "'", "'.join(tokens)"]
920,574
eebowen/Transfer-Learning-and-Deep-Neural-Network-Acceleration-for-Image-Classification
nntools.py
Experiment.epoch
epoch
Returns the number of epochs already performed.
[ "Returns", "the", "number", "of", "epochs", "already", "performed." ]
def epoch(self): return len(self.history)
['def', 'epoch(self):', 'return', 'len(self.history)']
920,688
eebowen/Transfer-Learning-and-Deep-Neural-Network-Acceleration-for-Image-Classification
nntools.py
Experiment.setting
setting
Returns the setting of the experiment.
[ "Returns", "the", "setting", "of", "the", "experiment." ]
def setting(self): return {'Net': self.net, 'TrainSet': self.train_set, 'ValSet': self.val_set, 'Optimizer': self.optimizer, 'StatsManager': self.stats_manager, 'BatchSize': self.batch_size, 'PerformValidationDuringTraining': self.perform_validation_during_training}
['def', 'setting(self):', 'return', "{'Net':", 'self.net,', "'TrainSet':", 'self.train_set,', "'ValSet':", 'self.val_set,', "'Optimizer':", 'self.optimizer,', "'StatsManager':", 'self.stats_manager,', "'BatchSize':", 'self.batch_size,', "'PerformValidationDuringTraining':", 'self.perform_validation_during_training}']
920,689
eebowen/Transfer-Learning-and-Deep-Neural-Network-Acceleration-for-Image-Classification
nntools.py
Experiment.state_dict
state_dict
Returns the current state of the experiment.
[ "Returns", "the", "current", "state", "of", "the", "experiment." ]
def state_dict(self): return {'Net': self.net.state_dict(), 'Optimizer': self.optimizer.state_dict(), 'History': self.history}
['def', 'state_dict(self):', 'return', "{'Net':", 'self.net.state_dict(),', "'Optimizer':", 'self.optimizer.state_dict(),', "'History':", 'self.history}']
920,690
eebowen/Transfer-Learning-and-Deep-Neural-Network-Acceleration-for-Image-Classification
nntools.py
Experiment.load_state_dict
load_state_dict
Loads the experiment from the input checkpoint.
[ "Loads", "the", "experiment", "from", "the", "input", "checkpoint." ]
def load_state_dict(self, checkpoint): self.net.load_state_dict(checkpoint['Net']) self.optimizer.load_state_dict(checkpoint['Optimizer']) self.history = checkpoint['History'] for state in self.optimizer.state.values(): for (k, v) in state.items(): if isinstance(v, torch.Tensor): ...
['def', 'load_state_dict(self,', 'checkpoint):', "self.net.load_state_dict(checkpoint['Net'])", "self.optimizer.load_state_dict(checkpoint['Optimizer'])", 'self.history', '=', "checkpoint['History']", 'for', 'state', 'in', 'self.optimizer.state.values():', 'for', '(k,', 'v)', 'in', 'state.items():', 'if', 'isinstance(v...
920,691
eebowen/Transfer-Learning-and-Deep-Neural-Network-Acceleration-for-Image-Classification
nntools.py
Experiment.load
load
Loads the experiment from the last checkpoint saved on disk.
[ "Loads", "the", "experiment", "from", "the", "last", "checkpoint", "saved", "on", "disk." ]
def load(self): checkpoint = torch.load(self.checkpoint_path, map_location=self.net.device) self.load_state_dict(checkpoint) del checkpoint
['def', 'load(self):', 'checkpoint', '=', 'torch.load(self.checkpoint_path,', 'map_location=self.net.device)', 'self.load_state_dict(checkpoint)', 'del', 'checkpoint']
920,693
BaderLab/Transfer-Learning-BNER-Bioinformatics-2018
brat_standoff_corpus_proccessing.py
change_ann_labels
change_ann_labels
Changes the label of each annotation <label_to_replace> with <new_label> for a given corpus.
[ "Changes", "the", "label", "of", "each", "annotation", "<label_to_replace>", "with", "<new_label>", "for", "a", "given", "corpus." ]
def change_ann_labels(corpus_dir, labels_to_replace, new_label, drop=False): print('[INFO] Changing annotations...', end='') for filename in get_filenames(corpus_dir): if filename.endswith('.ann'): filepath = os.path.join(corpus_dir, filename) with codecs.open(filepath, 'r', enco...
['def', 'change_ann_labels(corpus_dir,', 'labels_to_replace,', 'new_label,', 'drop=False):', "print('[INFO]", 'Changing', "annotations...',", "end='')", 'for', 'filename', 'in', 'get_filenames(corpus_dir):', 'if', "filename.endswith('.ann'):", 'filepath', '=', 'os.path.join(corpus_dir,', 'filename)', 'with', 'codecs.op...
920,792
BaderLab/Transfer-Learning-BNER-Bioinformatics-2018
brat_standoff_corpus_proccessing.py
convert_bin_to_glove
convert_bin_to_glove
Converts word embeddings given in the binary C format (w2v) to a text format that can be used with NeuroNER.
[ "Converts", "word", "embeddings", "given", "in", "the", "binary", "C", "format", "(w2v)", "to", "a", "text", "format", "that", "can", "be", "used", "with", "NeuroNER." ]
def convert_bin_to_glove(input_file, output_dir=os.getcwd()): assert input_file.endswith('.bin'), 'You need to provide a .bin file!' word_vectors = KeyedVectors.load_word2vec_format(binary_w2v_file_path, binary=True) vocab = word_vectors.vocab output_file_path = output_dir + '/converted_word_vectors.txt...
['def', 'convert_bin_to_glove(input_file,', 'output_dir=os.getcwd()):', 'assert', "input_file.endswith('.bin'),", "'You", 'need', 'to', 'provide', 'a', '.bin', "file!'", 'word_vectors', '=', 'KeyedVectors.load_word2vec_format(binary_w2v_file_path,', 'binary=True)', 'vocab', '=', 'word_vectors.vocab', 'output_file_path'...
920,796
BaderLab/Transfer-Learning-BNER-Bioinformatics-2018
brat_standoff_corpus_proccessing.py
split_brat_standoff
split_brat_standoff
Randomly splits the corpus into train, test and validation sets.
[ "Randomly", "splits", "the", "corpus", "into", "train,", "test", "and", "validation", "sets." ]
def split_brat_standoff(corpra_dir, train_size, test_size, valid_size, random_seed=42): assert train_size < 1.0 and train_size > 0.0, 'TRAIN_SIZE must be between 0.0 and 1.0' assert test_size < 1.0 and test_size > 0.0, 'TEST_SIZE must be between 0.0 and 1.0' assert valid_size < 1.0 and valid_size > 0.0, 'VA...
['def', 'split_brat_standoff(corpra_dir,', 'train_size,', 'test_size,', 'valid_size,', 'random_seed=42):', 'assert', 'train_size', '<', '1.0', 'and', 'train_size', '>', '0.0,', "'TRAIN_SIZE", 'must', 'be', 'between', '0.0', 'and', "1.0'", 'assert', 'test_size', '<', '1.0', 'and', 'test_size', '>', '0.0,', "'TEST_SIZE",...
920,799
BaderLab/Transfer-Learning-BNER-Bioinformatics-2018
brat_standoff_corpus_proccessing.py
get_labels
get_labels
Returns a list of strings containing the annotations from file at path_to_labels with TX counter removed.
[ "Returns", "a", "list", "of", "strings", "containing", "the", "annotations", "from", "file", "at", "path_to_labels", "with", "TX", "counter", "removed." ]
def get_labels(path_to_labels): global_labels = [] for file in os.listdir(path_to_labels): filename = os.fsdecode(file) if filename.endswith('.ann') or filename.endswith('.a1'): with codecs.open(os.path.join(path_to_labels, filename), 'r', encoding='utf-8') as test: l...
['def', 'get_labels(path_to_labels):', 'global_labels', '=', '[]', 'for', 'file', 'in', 'os.listdir(path_to_labels):', 'filename', '=', 'os.fsdecode(file)', 'if', "filename.endswith('.ann')", 'or', "filename.endswith('.a1'):", 'with', 'codecs.open(os.path.join(path_to_labels,', 'filename),', "'r',", "encoding='utf-8')"...
920,806
BaderLab/Transfer-Learning-BNER-Bioinformatics-2018
brat_standoff_corpus_proccessing.py
get_FN_FP_TP
get_FN_FP_TP
Returns tuple of lists containing false-negatives, false-positives and true-positives.
[ "Returns", "tuple", "of", "lists", "containing", "false-negatives,", "false-positives", "and", "true-positives." ]
def get_FN_FP_TP(predictions, labels): FN = set() FP = set() TP = set() for label in labels: if not label in predictions: FN.add(label) for pred in predictions: if not pred in labels: FP.add(pred) for pred in predictions: if pred in labels: ...
['def', 'get_FN_FP_TP(predictions,', 'labels):', 'FN', '=', 'set()', 'FP', '=', 'set()', 'TP', '=', 'set()', 'for', 'label', 'in', 'labels:', 'if', 'not', 'label', 'in', 'predictions:', 'FN.add(label)', 'for', 'pred', 'in', 'predictions:', 'if', 'not', 'pred', 'in', 'labels:', 'FP.add(pred)', 'for', 'pred', 'in', 'pred...
920,807
BaderLab/Transfer-Learning-BNER-Bioinformatics-2018
brat_standoff_corpus_proccessing.py
get_top_n_difference
get_top_n_difference
Returns a tuple of lists, where the first list contains the n most common elements in A \ B and the second list contains the n most common elements in B \ A.
[ "Returns", "a", "tuple", "of", "lists,", "where", "the", "first", "list", "contains", "the", "n", "most", "common", "elements", "in", "A", "\\", "B", "and", "the", "second", "list", "contains", "the", "n", "most", "common", "elements", "in", "B", "\\", ...
def get_top_n_difference(A, B, n=10): A_minus_B = Counter([x.split('\t')[1] for x in A - B]).most_common(n) B_minus_A = Counter([x.split('\t')[1] for x in B - A]).most_common(n) return (A_minus_B, B_minus_A)
['def', 'get_top_n_difference(A,', 'B,', 'n=10):', 'A_minus_B', '=', "Counter([x.split('\\t')[1]", 'for', 'x', 'in', 'A', '-', 'B]).most_common(n)', 'B_minus_A', '=', "Counter([x.split('\\t')[1]", 'for', 'x', 'in', 'B', '-', 'A]).most_common(n)', 'return', '(A_minus_B,', 'B_minus_A)']
920,809
BaderLab/Transfer-Learning-BNER-Bioinformatics-2018
brat_standoff_corpus_proccessing.py
extract_ann
extract_ann
Returns a Counter object, where keys are unique textual annotations in copra at copra_dir, and values are their respective counts.
[ "Returns", "a", "Counter", "object,", "where", "keys", "are", "unique", "textual", "annotations", "in", "copra", "at", "copra_dir,", "and", "values", "are", "their", "respective", "counts." ]
def extract_ann(corpra_dir): unique_entities_in_corpra = Counter() for filename in os.listdir(corpra_dir): if filename.endswith('.ann') or filename.endswith('.a1'): try: with open(os.path.join(corpra_dir, filename), 'r') as ann_file: ann_file_lines = ann_f...
['def', 'extract_ann(corpra_dir):', 'unique_entities_in_corpra', '=', 'Counter()', 'for', 'filename', 'in', 'os.listdir(corpra_dir):', 'if', "filename.endswith('.ann')", 'or', "filename.endswith('.a1'):", 'try:', 'with', 'open(os.path.join(corpra_dir,', 'filename),', "'r')", 'as', 'ann_file:', 'ann_file_lines', '=', 'a...
920,814
rtoengi/transfer-learning-for-sign-language-recognition
info.py
display_dataset_example_spec
display_dataset_example_spec
Displays a specification entry of the `MS-ASL` dataset.
[ "Displays", "a", "specification", "entry", "of", "the", "`MS-ASL`", "dataset." ]
def display_dataset_example_spec(): with open(f'{_MSASL_FILTERED_SPECS_DIR}/{DatasetType.TRAIN.value}.json', 'r') as file: dataset = json.load(file) print('MSASL dataset example spec') print('=' * 27) print(json.dumps(dataset[0], indent=4))
['def', 'display_dataset_example_spec():', 'with', "open(f'{_MSASL_FILTERED_SPECS_DIR}/{DatasetType.TRAIN.value}.json',", "'r')", 'as', 'file:', 'dataset', '=', 'json.load(file)', "print('MSASL", 'dataset', 'example', "spec')", "print('='", '*', '27)', 'print(json.dumps(dataset[0],', 'indent=4))']
920,885
MegEngine/Transfer-Learning-Library
bbox_adaptation.py
clamp
clamp
clamp (limit) the values in boxes within the widths and heights of the image.
[ "clamp", "(limit)", "the", "values", "in", "boxes", "within", "the", "widths", "and", "heights", "of", "the", "image." ]
def clamp(boxes, widths, heights): clamped_boxes = [] for (box, w, h) in zip(boxes, widths, heights): clamped_boxes.append(clamp_single(box, w, h)) return torch.stack(clamped_boxes, dim=0)
['def', 'clamp(boxes,', 'widths,', 'heights):', 'clamped_boxes', '=', '[]', 'for', '(box,', 'w,', 'h)', 'in', 'zip(boxes,', 'widths,', 'heights):', 'clamped_boxes.append(clamp_single(box,', 'w,', 'h))', 'return', 'torch.stack(clamped_boxes,', 'dim=0)']
921,009
thuml/Transfer-Learning-Library
mdd.py
GeneralModule.get_parameters
get_parameters
Return a parameters list which decides optimization hyper-parameters, such as the relative learning rate of each layer.
[ "Return", "a", "parameters", "list", "which", "decides", "optimization", "hyper-parameters,", "such", "as", "the", "relative", "learning", "rate", "of", "each", "layer." ]
def get_parameters(self, base_lr=1.0) -> List[Dict]: params = [{'params': self.backbone.parameters(), 'lr': 0.1 * base_lr if self.finetune else base_lr}, {'params': self.bottleneck.parameters(), 'lr': base_lr}, {'params': self.head.parameters(), 'lr': base_lr}, {'params': self.adv_head.parameters(), 'lr': base_lr}]...
['def', 'get_parameters(self,', 'base_lr=1.0)', '->', 'List[Dict]:', 'params', '=', "[{'params':", 'self.backbone.parameters(),', "'lr':", '0.1', '*', 'base_lr', 'if', 'self.finetune', 'else', 'base_lr},', "{'params':", 'self.bottleneck.parameters(),', "'lr':", 'base_lr},', "{'params':", 'self.head.parameters(),', "'lr...
921,109
thuml/Transfer-Learning-Library
feedback.py
transform_feedbacks
transform_feedbacks
Apply transformations to the feedbacks in dataset_dict, if any.
[ "Apply", "transformations", "to", "the", "feedbacks", "in", "dataset_dict,", "if", "any." ]
def transform_feedbacks(dataset_dict, image_shape, transforms, *, min_box_size=0): if 'feedback_proposal_boxes' in dataset_dict: proposal_boxes = transforms.apply_box(BoxMode.convert(dataset_dict.pop('feedback_proposal_boxes'), dataset_dict.get('feedback_bbox_mode'), BoxMode.XYXY_ABS)) proposal_boxe...
['def', 'transform_feedbacks(dataset_dict,', 'image_shape,', 'transforms,', '*,', 'min_box_size=0):', 'if', "'feedback_proposal_boxes'", 'in', 'dataset_dict:', 'proposal_boxes', '=', "transforms.apply_box(BoxMode.convert(dataset_dict.pop('feedback_proposal_boxes'),", "dataset_dict.get('feedback_bbox_mode'),", 'BoxMode....
921,117
MegEngine/Transfer-Learning-Library
feedback.py
load_feedbacks_into_dataset
load_feedbacks_into_dataset
Load precomputed object feedbacks into the dataset.
[ "Load", "precomputed", "object", "feedbacks", "into", "the", "dataset." ]
def load_feedbacks_into_dataset(dataset_dicts, proposals_list: List[Proposal]): feedbacks = {} for record in dataset_dicts: image_id = str(record['image_id']) feedbacks[image_id] = {'pred_boxes': [], 'pred_classes': []} for proposals in proposals_list: image_id = str(proposals.image_...
['def', 'load_feedbacks_into_dataset(dataset_dicts,', 'proposals_list:', 'List[Proposal]):', 'feedbacks', '=', '{}', 'for', 'record', 'in', 'dataset_dicts:', 'image_id', '=', "str(record['image_id'])", 'feedbacks[image_id]', '=', "{'pred_boxes':", '[],', "'pred_classes':", '[]}', 'for', 'proposals', 'in', 'proposals_li...
921,118
thuml/Transfer-Learning-Library
stochnorm.py
convert_model
convert_model
Traverses the input module and its child recursively and replaces all instance of BatchNorm to StochNorm.
[ "Traverses", "the", "input", "module", "and", "its", "child", "recursively", "and", "replaces", "all", "instance", "of", "BatchNorm", "to", "StochNorm." ]
def convert_model(module, p): mod = module for (pth_module, stoch_module) in zip([torch.nn.modules.batchnorm.BatchNorm1d, torch.nn.modules.batchnorm.BatchNorm2d, torch.nn.modules.batchnorm.BatchNorm3d], [StochNorm1d, StochNorm2d, StochNorm3d]): if isinstance(module, pth_module): mod = stoch_...
['def', 'convert_model(module,', 'p):', 'mod', '=', 'module', 'for', '(pth_module,', 'stoch_module)', 'in', 'zip([torch.nn.modules.batchnorm.BatchNorm1d,', 'torch.nn.modules.batchnorm.BatchNorm2d,', 'torch.nn.modules.batchnorm.BatchNorm3d],', '[StochNorm1d,', 'StochNorm2d,', 'StochNorm3d]):', 'if', 'isinstance(module,'...
921,177
thuml/Transfer-Learning-Library
co_tuning.py
Relationship.get_category_relationship
get_category_relationship
The direct approach of learning category relationship p(y_s | y_t).
[ "The", "direct", "approach", "of", "learning", "category", "relationship", "p(y_s", "|", "y_t)." ]
def get_category_relationship(self, source_probabilities, target_labels): N_t = np.max(target_labels) + 1 conditional = [] for i in range(N_t): this_class = source_probabilities[target_labels == i] average = np.mean(this_class, axis=0, keepdims=True) conditional.append(average) r...
['def', 'get_category_relationship(self,', 'source_probabilities,', 'target_labels):', 'N_t', '=', 'np.max(target_labels)', '+', '1', 'conditional', '=', '[]', 'for', 'i', 'in', 'range(N_t):', 'this_class', '=', 'source_probabilities[target_labels', '==', 'i]', 'average', '=', 'np.mean(this_class,', 'axis=0,', 'keepdim...
921,196
thuml/Transfer-Learning-Library
dst.py
shift_log
shift_log
First shift, then calculate log for numerical stability.
[ "First", "shift,", "then", "calculate", "log", "for", "numerical", "stability." ]
def shift_log(x, offset=1e-06): return torch.log(torch.clamp(x + offset, max=1.0))
['def', 'shift_log(x,', 'offset=1e-06):', 'return', 'torch.log(torch.clamp(x', '+', 'offset,', 'max=1.0))']
921,221
MegEngine/Transfer-Learning-Library
data.py
send_to_device
send_to_device
Recursively sends the elements in a nested list/tuple/dictionary of tensors to a given device.
[ "Recursively", "sends", "the", "elements", "in", "a", "nested", "list/tuple/dictionary", "of", "tensors", "to", "a", "given", "device." ]
def send_to_device(tensor, device): if isinstance(tensor, (list, tuple)): return type(tensor)((send_to_device(t, device) for t in tensor)) elif isinstance(tensor, dict): return type(tensor)({k: send_to_device(v, device) for (k, v) in tensor.items()}) elif not hasattr(tensor, 'to'): r...
['def', 'send_to_device(tensor,', 'device):', 'if', 'isinstance(tensor,', '(list,', 'tuple)):', 'return', 'type(tensor)((send_to_device(t,', 'device)', 'for', 't', 'in', 'tensor))', 'elif', 'isinstance(tensor,', 'dict):', 'return', 'type(tensor)({k:', 'send_to_device(v,', 'device)', 'for', '(k,', 'v)', 'in', 'tensor.it...
921,261
thuml/Transfer-Learning-Library
keypoint_dataset.py
KeypointDataset.group_accuracy
group_accuracy
Group the accuracy of K keypoints into different kinds.
[ "Group", "the", "accuracy", "of", "K", "keypoints", "into", "different", "kinds." ]
def group_accuracy(self, accuracies): grouped_accuracies = dict() for (name, keypoints) in self.keypoints_group.items(): grouped_accuracies[name] = sum([accuracies[idx] for idx in keypoints]) / len(keypoints) return grouped_accuracies
['def', 'group_accuracy(self,', 'accuracies):', 'grouped_accuracies', '=', 'dict()', 'for', '(name,', 'keypoints)', 'in', 'self.keypoints_group.items():', 'grouped_accuracies[name]', '=', 'sum([accuracies[idx]', 'for', 'idx', 'in', 'keypoints])', '/', 'len(keypoints)', 'return', 'grouped_accuracies']
921,320
thuml/Transfer-Learning-Library
pose_resnet.py
pose_resnet101
pose_resnet101
Constructs a Simple Baseline model with a ResNet-101 backbone.
[ "Constructs", "a", "Simple", "Baseline", "model", "with", "a", "ResNet-101", "backbone." ]
def pose_resnet101(num_keypoints, pretrained_backbone=True, deconv_with_bias=False, finetune=False, progress=True, **kwargs): return _pose_resnet('resnet101', num_keypoints, Bottleneck, [3, 4, 23, 3], pretrained_backbone, deconv_with_bias, finetune, progress, **kwargs)
['def', 'pose_resnet101(num_keypoints,', 'pretrained_backbone=True,', 'deconv_with_bias=False,', 'finetune=False,', 'progress=True,', '**kwargs):', 'return', "_pose_resnet('resnet101',", 'num_keypoints,', 'Bottleneck,', '[3,', '4,', '23,', '3],', 'pretrained_backbone,', 'deconv_with_bias,', 'finetune,', 'progress,', '*...
921,395
thuml/Transfer-Learning-Library
resnet.py
reid_resnet18
reid_resnet18
Constructs a Reid-ResNet-18 model.
[ "Constructs", "a", "Reid-ResNet-18", "model." ]
def reid_resnet18(pretrained=False, progress=True, **kwargs): return _reid_resnet('resnet18', BasicBlock, [2, 2, 2, 2], pretrained, progress, **kwargs)
['def', 'reid_resnet18(pretrained=False,', 'progress=True,', '**kwargs):', 'return', "_reid_resnet('resnet18',", 'BasicBlock,', '[2,', '2,', '2,', '2],', 'pretrained,', 'progress,', '**kwargs)']
921,417
thuml/Transfer-Learning-Library
resnet.py
reid_resnet101
reid_resnet101
Constructs a Reid-ResNet-101 model.
[ "Constructs", "a", "Reid-ResNet-101", "model." ]
def reid_resnet101(pretrained=False, progress=True, **kwargs): return _reid_resnet('resnet101', Bottleneck, [3, 4, 23, 3], pretrained, progress, **kwargs)
['def', 'reid_resnet101(pretrained=False,', 'progress=True,', '**kwargs):', 'return', "_reid_resnet('resnet101',", 'Bottleneck,', '[3,', '4,', '23,', '3],', 'pretrained,', 'progress,', '**kwargs)']
921,420
MegEngine/Transfer-Learning-Library
resnet.py
reid_resnet34
reid_resnet34
Constructs a Reid-ResNet-34 model.
[ "Constructs", "a", "Reid-ResNet-34", "model." ]
def reid_resnet34(pretrained=False, progress=True, **kwargs): return _reid_resnet('resnet34', BasicBlock, [3, 4, 6, 3], pretrained, progress, **kwargs)
['def', 'reid_resnet34(pretrained=False,', 'progress=True,', '**kwargs):', 'return', "_reid_resnet('resnet34',", 'BasicBlock,', '[3,', '4,', '6,', '3],', 'pretrained,', 'progress,', '**kwargs)']
921,422
MegEngine/Transfer-Learning-Library
resnet.py
reid_resnet50
reid_resnet50
Constructs a Reid-ResNet-50 model.
[ "Constructs", "a", "Reid-ResNet-50", "model." ]
def reid_resnet50(pretrained=False, progress=True, **kwargs): return _reid_resnet('resnet50', Bottleneck, [3, 4, 6, 3], pretrained, progress, **kwargs)
['def', 'reid_resnet50(pretrained=False,', 'progress=True,', '**kwargs):', 'return', "_reid_resnet('resnet50',", 'Bottleneck,', '[3,', '4,', '6,', '3],', 'pretrained,', 'progress,', '**kwargs)']
921,423
evhub/transfer-learning-live-song-id
transfer_learning_live_song_id.py
build_feature_extractor
build_feature_extractor
Builds the transfer_learning_music feature extractor.
[ "Builds", "the", "transfer_learning_music", "feature", "extractor." ]
def build_feature_extractor(): base_model = load_model(BASE_MODEL_FILE, custom_objects={'Melspectrogram': kapre.time_frequency.Melspectrogram, 'Normalization2D': kapre.utils.Normalization2D}) feat_layer1 = GAP2D()(base_model.get_layer('elu_1').output) feat_layer2 = GAP2D()(base_model.get_layer('elu_2').outp...
['def', 'build_feature_extractor():', 'base_model', '=', 'load_model(BASE_MODEL_FILE,', "custom_objects={'Melspectrogram':", 'kapre.time_frequency.Melspectrogram,', "'Normalization2D':", 'kapre.utils.Normalization2D})', 'feat_layer1', '=', "GAP2D()(base_model.get_layer('elu_1').output)", 'feat_layer2', '=', "GAP2D()(ba...
921,444
evhub/transfer-learning-live-song-id
transfer_learning_live_song_id.py
get_num_samples
get_num_samples
Get the number of samples to take.
[ "Get", "the", "number", "of", "samples", "to", "take." ]
def get_num_samples(audio_len): remaining_len = audio_len - SAMPLE_WIDTH + 1 if remaining_len <= 0: return None return audio_len // SAMPLE_STRIDE
['def', 'get_num_samples(audio_len):', 'remaining_len', '=', 'audio_len', '-', 'SAMPLE_WIDTH', '+', '1', 'if', 'remaining_len', '<=', '0:', 'return', 'None', 'return', 'audio_len', '//', 'SAMPLE_STRIDE']
921,446
evhub/transfer-learning-live-song-id
transfer_learning_live_song_id.py
run_models
run_models
Run the given models on the given audio.
[ "Run", "the", "given", "models", "on", "the", "given", "audio." ]
def run_models(audio_arr, feat_extractor, delta_model): samples = get_samples(audio_arr) num_samples = samples.shape[0] features = predict_all(samples, feat_extractor) assert features.shape == (num_samples, NUM_FEATURES), (features.shape, (num_samples, NUM_FEATURES)) features = features.reshape((1, ...
['def', 'run_models(audio_arr,', 'feat_extractor,', 'delta_model):', 'samples', '=', 'get_samples(audio_arr)', 'num_samples', '=', 'samples.shape[0]', 'features', '=', 'predict_all(samples,', 'feat_extractor)', 'assert', 'features.shape', '==', '(num_samples,', 'NUM_FEATURES),', '(features.shape,', '(num_samples,', 'NU...
921,451
evhub/transfer-learning-live-song-id
transfer_learning_live_song_id.py
process
process
Build and run models on the given audio.
[ "Build", "and", "run", "models", "on", "the", "given", "audio." ]
def process(audio_arr, debug=False): (audio_len,) = audio_arr.shape num_samples = get_num_samples(audio_len) if debug: print('\tProcessing audio array of length %r (%r samples)...' % (audio_len, num_samples)) t0 = time.clock() models = build_models(audio_len) result = run_models(audi...
['def', 'process(audio_arr,', 'debug=False):', '(audio_len,)', '=', 'audio_arr.shape', 'num_samples', '=', 'get_num_samples(audio_len)', 'if', 'debug:', "print('\\tProcessing", 'audio', 'array', 'of', 'length', '%r', '(%r', "samples)...'", '%', '(audio_len,', 'num_samples))', 't0', '=', 'time.clock()', 'models', '=', '...
921,452
evhub/transfer-learning-live-song-id
transfer_learning_live_song_id.py
process_all
process_all
Process all the given audio arrays.
[ "Process", "all", "the", "given", "audio", "arrays." ]
def process_all(audio_arrs, debug=False): return [process(audio, debug) for audio in audio_arrs]
['def', 'process_all(audio_arrs,', 'debug=False):', 'return', '[process(audio,', 'debug)', 'for', 'audio', 'in', 'audio_arrs]']
921,453
evhub/transfer-learning-live-song-id
transfer_learning_live_song_id.py
make_db
make_db
Create all the db directories if they need to be made.
[ "Create", "all", "the", "db", "directories", "if", "they", "need", "to", "be", "made." ]
def make_db(): made_dir = False for dirpath in [DB_DIR, REFS_DIR, QUERIES_DIR]: if not os.path.exists(dirpath): os.mkdir(dirpath) made_dir = True return made_dir
['def', 'make_db():', 'made_dir', '=', 'False', 'for', 'dirpath', 'in', '[DB_DIR,', 'REFS_DIR,', 'QUERIES_DIR]:', 'if', 'not', 'os.path.exists(dirpath):', 'os.mkdir(dirpath)', 'made_dir', '=', 'True', 'return', 'made_dir']
921,454
evhub/transfer-learning-live-song-id
transfer_learning_live_song_id.py
get_ref_path
get_ref_path
Get the path to the processed reference of the given index.
[ "Get", "the", "path", "to", "the", "processed", "reference", "of", "the", "given", "index." ]
def get_ref_path(index): return os.path.join(REFS_DIR, '{}.npy'.format(index))
['def', 'get_ref_path(index):', 'return', 'os.path.join(REFS_DIR,', "'{}.npy'.format(index))"]
921,455
evhub/transfer-learning-live-song-id
transfer_learning_live_song_id.py
write_db
write_db
Writes processed refs and queries to the database.
[ "Writes", "processed", "refs", "and", "queries", "to", "the", "database." ]
def write_db(proc_refs, proc_queries): for (i, ref) in enumerate(proc_refs): ref_path = get_ref_path(i) np.save(ref_path, ref) for (i, query) in enumerate(proc_queries): query_path = get_query_path(i) np.save(query_path, query)
['def', 'write_db(proc_refs,', 'proc_queries):', 'for', '(i,', 'ref)', 'in', 'enumerate(proc_refs):', 'ref_path', '=', 'get_ref_path(i)', 'np.save(ref_path,', 'ref)', 'for', '(i,', 'query)', 'in', 'enumerate(proc_queries):', 'query_path', '=', 'get_query_path(i)', 'np.save(query_path,', 'query)']
921,457
evhub/transfer-learning-live-song-id
transfer_learning_live_song_id.py
sorted_paths
sorted_paths
Sorts file paths by their number.
[ "Sorts", "file", "paths", "by", "their", "number." ]
def sorted_paths(paths): return sorted(paths, key=lambda p: int(p.split('.', 1)[0]))
['def', 'sorted_paths(paths):', 'return', 'sorted(paths,', 'key=lambda', 'p:', "int(p.split('.',", '1)[0]))']
921,458
evhub/transfer-learning-live-song-id
transfer_learning_live_song_id.py
read_db
read_db
Reads processed refs and queries from the database.
[ "Reads", "processed", "refs", "and", "queries", "from", "the", "database." ]
def read_db(debug=False): refs = [] for ref_name in sorted_paths(os.listdir(REFS_DIR)): if debug: print('\tLoading ref %s...' % (ref_name,)) ref_path = os.path.join(REFS_DIR, ref_name) refs.append(np.load(ref_path)) queries = [] for query_name in sorted_paths(os.listd...
['def', 'read_db(debug=False):', 'refs', '=', '[]', 'for', 'ref_name', 'in', 'sorted_paths(os.listdir(REFS_DIR)):', 'if', 'debug:', "print('\\tLoading", 'ref', "%s...'", '%', '(ref_name,))', 'ref_path', '=', 'os.path.join(REFS_DIR,', 'ref_name)', 'refs.append(np.load(ref_path))', 'queries', '=', '[]', 'for', 'query_nam...
921,459
evhub/transfer-learning-live-song-id
transfer_learning_live_song_id.py
remove_short_queries
remove_short_queries
Removes queries that are too short from queries and groundTruth.
[ "Removes", "queries", "that", "are", "too", "short", "from", "queries", "and", "groundTruth." ]
def remove_short_queries(queries, groundTruth): assert len(queries) == len(groundTruth), (len(queries), len(groundTruth)) filt_queries = [] filt_groundTruth = [] for (query, truth) in zip(queries, groundTruth): (audio_len,) = query.shape num_samples = get_num_samples(audio_len) i...
['def', 'remove_short_queries(queries,', 'groundTruth):', 'assert', 'len(queries)', '==', 'len(groundTruth),', '(len(queries),', 'len(groundTruth))', 'filt_queries', '=', '[]', 'filt_groundTruth', '=', '[]', 'for', '(query,', 'truth)', 'in', 'zip(queries,', 'groundTruth):', '(audio_len,)', '=', 'query.shape', 'num_samp...
921,460
Hironsan/tensorflow-nlp-examples
data_loader.py
load_glove_vocab
load_glove_vocab
Loads GloVe's vocab from a file.
[ "Loads", "GloVe's", "vocab", "from", "a", "file." ]
def load_glove_vocab(filename): print('Building vocab...') with open(filename) as f: vocab = {line.strip().split()[0] for line in f} print('- done. {} tokens'.format(len(vocab))) return vocab
['def', 'load_glove_vocab(filename):', "print('Building", "vocab...')", 'with', 'open(filename)', 'as', 'f:', 'vocab', '=', '{line.strip().split()[0]', 'for', 'line', 'in', 'f}', "print('-", 'done.', '{}', "tokens'.format(len(vocab)))", 'return', 'vocab']
921,484
Hironsan/tensorflow-nlp-examples
data_loader.py
load_word_embeddings
load_word_embeddings
Loads GloVe vectors in numpy array.
[ "Loads", "GloVe", "vectors", "in", "numpy", "array." ]
def load_word_embeddings(vocab, glove_filename, dim): embeddings = np.zeros([len(vocab), dim]) with open(glove_filename) as f: for line in f: line = line.strip().split(' ') word = line[0] embedding = [float(x) for x in line[1:dim + 1]] if word in vocab: ...
['def', 'load_word_embeddings(vocab,', 'glove_filename,', 'dim):', 'embeddings', '=', 'np.zeros([len(vocab),', 'dim])', 'with', 'open(glove_filename)', 'as', 'f:', 'for', 'line', 'in', 'f:', 'line', '=', "line.strip().split('", "')", 'word', '=', 'line[0]', 'embedding', '=', '[float(x)', 'for', 'x', 'in', 'line[1:dim',...
921,485
Hironsan/tensorflow-nlp-examples
train.py
Trainer.get_feed_dict
get_feed_dict
Builds a feed dictionary.
[ "Builds", "a", "feed", "dictionary." ]
def get_feed_dict(self, data, labels=None, lr=None, dropout=None): feed = {} if self.model_config.char_feature: (word_ids, char_ids, sequence_lengths, word_lengths) = data feed[self.char_ids] = char_ids feed[self.word_lengths] = word_lengths else: (word_ids, sequence_lengths)...
['def', 'get_feed_dict(self,', 'data,', 'labels=None,', 'lr=None,', 'dropout=None):', 'feed', '=', '{}', 'if', 'self.model_config.char_feature:', '(word_ids,', 'char_ids,', 'sequence_lengths,', 'word_lengths)', '=', 'data', 'feed[self.char_ids]', '=', 'char_ids', 'feed[self.word_lengths]', '=', 'word_lengths', 'else:',...
921,491
Hironsan/tensorflow-nlp-examples
preprocessing.py
IndexTransformer.fit
fit
Learn vocabulary from training set.
[ "Learn", "vocabulary", "from", "training", "set." ]
def fit(self, X, y): self._word_vocab.add_documents(X) self._label_vocab.add_documents(y) if self._use_char: for doc in X: self._char_vocab.add_documents(doc) self._word_vocab.build() self._char_vocab.build() self._label_vocab.build() return self
['def', 'fit(self,', 'X,', 'y):', 'self._word_vocab.add_documents(X)', 'self._label_vocab.add_documents(y)', 'if', 'self._use_char:', 'for', 'doc', 'in', 'X:', 'self._char_vocab.add_documents(doc)', 'self._word_vocab.build()', 'self._char_vocab.build()', 'self._label_vocab.build()', 'return', 'self']
921,493
Hironsan/tensorflow-nlp-examples
utils.py
load_data_and_labels
load_data_and_labels
Loads data and label from a file.
[ "Loads", "data", "and", "label", "from", "a", "file." ]
def load_data_and_labels(filename, encoding='utf-8'): (sents, labels) = ([], []) (words, tags) = ([], []) with open(filename, encoding=encoding) as f: for line in f: line = line.rstrip() if line: (word, tag) = line.split('\t') words.append(word...
['def', 'load_data_and_labels(filename,', "encoding='utf-8'):", '(sents,', 'labels)', '=', '([],', '[])', '(words,', 'tags)', '=', '([],', '[])', 'with', 'open(filename,', 'encoding=encoding)', 'as', 'f:', 'for', 'line', 'in', 'f:', 'line', '=', 'line.rstrip()', 'if', 'line:', '(word,', 'tag)', '=', "line.split('\\t')"...
921,500
Hironsan/tensorflow-nlp-examples
utils.py
filter_embeddings
filter_embeddings
Loads word vectors in numpy array.
[ "Loads", "word", "vectors", "in", "numpy", "array." ]
def filter_embeddings(embeddings, vocab, dim): if not isinstance(embeddings, dict): return _embeddings = np.zeros([len(vocab), dim]) for word in vocab: if word in embeddings: word_idx = vocab[word] _embeddings[word_idx] = embeddings[word] return _embeddings
['def', 'filter_embeddings(embeddings,', 'vocab,', 'dim):', 'if', 'not', 'isinstance(embeddings,', 'dict):', 'return', '_embeddings', '=', 'np.zeros([len(vocab),', 'dim])', 'for', 'word', 'in', 'vocab:', 'if', 'word', 'in', 'embeddings:', 'word_idx', '=', 'vocab[word]', '_embeddings[word_idx]', '=', 'embeddings[word]',...
921,501
Hironsan/tensorflow-nlp-examples
utils.py
Vocabulary.add_token
add_token
Add token to vocabulary.
[ "Add", "token", "to", "vocabulary." ]
def add_token(self, token): token = self.process_token(token) self._token_count.update([token])
['def', 'add_token(self,', 'token):', 'token', '=', 'self.process_token(token)', 'self._token_count.update([token])']
921,503
Hironsan/tensorflow-nlp-examples
utils.py
Vocabulary.id2doc
id2doc
Get the token list.
[ "Get", "the", "token", "list." ]
def id2doc(self, ids): return [self.id_to_token(idx) for idx in ids]
['def', 'id2doc(self,', 'ids):', 'return', '[self.id_to_token(idx)', 'for', 'idx', 'in', 'ids]']
921,506