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 |
|---|---|---|---|---|---|---|---|---|
airaria/TextBrewer | tokenization_openai.py | OpenAIGPTTokenizer.decode | decode | Converts a sequence of ids in a string. | [
"Converts",
"a",
"sequence",
"of",
"ids",
"in",
"a",
"string."
] | def decode(self, ids, skip_special_tokens=False, clean_up_tokenization_spaces=True):
tokens = self.convert_ids_to_tokens(ids, skip_special_tokens=skip_special_tokens)
out_string = ''.join(tokens).replace('</w>', ' ').strip()
if clean_up_tokenization_spaces:
out_string = out_string.replace('<unk>', '... | ['def', 'decode(self,', 'ids,', 'skip_special_tokens=False,', 'clean_up_tokenization_spaces=True):', 'tokens', '=', 'self.convert_ids_to_tokens(ids,', 'skip_special_tokens=skip_special_tokens)', 'out_string', '=', "''.join(tokens).replace('</w>',", "'", "').strip()", 'if', 'clean_up_tokenization_spaces:', 'out_string',... | 925,828 |
airaria/TextBrewer | tokenization_transfo_xl.py | TransfoXLTokenizer.convert_ids_to_tokens | convert_ids_to_tokens | Converts a sequence of indices in symbols using the vocab. | [
"Converts",
"a",
"sequence",
"of",
"indices",
"in",
"symbols",
"using",
"the",
"vocab."
] | def convert_ids_to_tokens(self, indices):
return [self.get_sym(idx) for idx in indices] | ['def', 'convert_ids_to_tokens(self,', 'indices):', 'return', '[self.get_sym(idx)', 'for', 'idx', 'in', 'indices]'] | 925,833 |
airaria/TextBrewer | tokenization_transfo_xl.py | TransfoXLTokenizer.convert_tokens_to_ids | convert_tokens_to_ids | Converts a sequence of symbols into ids using the vocab. | [
"Converts",
"a",
"sequence",
"of",
"symbols",
"into",
"ids",
"using",
"the",
"vocab."
] | def convert_tokens_to_ids(self, symbols):
return [self.get_idx(sym) for sym in symbols] | ['def', 'convert_tokens_to_ids(self,', 'symbols):', 'return', '[self.get_idx(sym)', 'for', 'sym', 'in', 'symbols]'] | 925,834 |
airaria/TextBrewer | tokenization_transfo_xl.py | TransfoXLTokenizer.decode | decode | Converts a sequence of indices in a string. | [
"Converts",
"a",
"sequence",
"of",
"indices",
"in",
"a",
"string."
] | def decode(self, indices, exclude=None):
if exclude is None:
return ' '.join([self.get_sym(idx) for idx in indices])
else:
return ' '.join([self.get_sym(idx) for idx in indices if idx not in exclude]) | ['def', 'decode(self,', 'indices,', 'exclude=None):', 'if', 'exclude', 'is', 'None:', 'return', "'", "'.join([self.get_sym(idx)", 'for', 'idx', 'in', 'indices])', 'else:', 'return', "'", "'.join([self.get_sym(idx)", 'for', 'idx', 'in', 'indices', 'if', 'idx', 'not', 'in', 'exclude])'] | 925,835 |
airaria/TextBrewer | configurations.py | Config.from_json_file | from_json_file | Construct configurations from a json file. | [
"Construct",
"configurations",
"from",
"a",
"json",
"file."
] | def from_json_file(cls, json_filename):
with open(json_filename, 'r') as f:
json_data = json.load(f)
return cls.from_dict(json_data) | ['def', 'from_json_file(cls,', 'json_filename):', 'with', 'open(json_filename,', "'r')", 'as', 'f:', 'json_data', '=', 'json.load(f)', 'return', 'cls.from_dict(json_data)'] | 925,842 |
airaria/TextBrewer | data_utils.py | masking | masking | Returns a new list by replacing elements in `tokens` by `mask` with probability `p`. | [
"Returns",
"a",
"new",
"list",
"by",
"replacing",
"elements",
"in",
"`tokens`",
"by",
"`mask`",
"with",
"probability",
"`p`."
] | def masking(tokens, p=0.1, mask='[MASK]'):
outputs = tokens[:]
for i in range(len(tokens)):
if np.random.rand() < p:
outputs[i] = mask
return outputs | ['def', 'masking(tokens,', 'p=0.1,', "mask='[MASK]'):", 'outputs', '=', 'tokens[:]', 'for', 'i', 'in', 'range(len(tokens)):', 'if', 'np.random.rand()', '<', 'p:', 'outputs[i]', '=', 'mask', 'return', 'outputs'] | 925,844 |
airaria/TextBrewer | data_utils.py | n_gram_sampling | n_gram_sampling | Samples a length `l` from `l_ng` with probability distribution `p_ng`, then returns a random span of length `l` from `tokens`. | [
"Samples",
"a",
"length",
"`l`",
"from",
"`l_ng`",
"with",
"probability",
"distribution",
"`p_ng`,",
"then",
"returns",
"a",
"random",
"span",
"of",
"length",
"`l`",
"from",
"`tokens`."
] | def n_gram_sampling(tokens, p_ng=[0.2, 0.2, 0.2, 0.2, 0.2], l_ng=[1, 2, 3, 4, 5]):
span_length = np.random.choice(l_ng, p=p_ng)
start_position = max(0, np.random.randint(0, len(tokens) - span_length + 1))
n_gram_span = tokens[start_position:start_position + span_length]
return n_gram_span | ['def', 'n_gram_sampling(tokens,', 'p_ng=[0.2,', '0.2,', '0.2,', '0.2,', '0.2],', 'l_ng=[1,', '2,', '3,', '4,', '5]):', 'span_length', '=', 'np.random.choice(l_ng,', 'p=p_ng)', 'start_position', '=', 'max(0,', 'np.random.randint(0,', 'len(tokens)', '-', 'span_length', '+', '1))', 'n_gram_span', '=', 'tokens[start_posit... | 925,846 |
airaria/TextBrewer | distiller_basic.py | BasicDistiller.train | train | trains the student model. | [
"trains",
"the",
"student",
"model."
] | def train(self, optimizer, dataloader, num_epochs=None, scheduler_class=None, scheduler_args=None, scheduler=None, max_grad_norm=-1.0, num_steps=None, callback=None, batch_postprocessor=None, **args):
(optimizer, scheduler, tqdm_disable) = self.initialize_training(optimizer, scheduler_class, scheduler_args, schedul... | ['def', 'train(self,', 'optimizer,', 'dataloader,', 'num_epochs=None,', 'scheduler_class=None,', 'scheduler_args=None,', 'scheduler=None,', 'max_grad_norm=-1.0,', 'num_steps=None,', 'callback=None,', 'batch_postprocessor=None,', '**args):', '(optimizer,', 'scheduler,', 'tqdm_disable)', '=', 'self.initialize_training(op... | 925,849 |
textflint/textflint | install.py | set_cache_dir | set_cache_dir | Sets all relevant cache directories to ``TR_CACHE_DIR``. | [
"Sets",
"all",
"relevant",
"cache",
"directories",
"to",
"``TR_CACHE_DIR``."
] | def set_cache_dir(cache_dir):
os.environ['TFHUB_CACHE_DIR'] = cache_dir
os.environ['PYTORCH_TRANSFORMERS_CACHE'] = os.path.join(cache_dir, 'transformers')
os.environ['HF_HOME'] = cache_dir
os.environ['XDG_CACHE_HOME'] = cache_dir | ['def', 'set_cache_dir(cache_dir):', "os.environ['TFHUB_CACHE_DIR']", '=', 'cache_dir', "os.environ['PYTORCH_TRANSFORMERS_CACHE']", '=', 'os.path.join(cache_dir,', "'transformers')", "os.environ['HF_HOME']", '=', 'cache_dir', "os.environ['XDG_CACHE_HOME']", '=', 'cache_dir'] | 925,910 |
textflint/textflint | mlm_suggestion.py | MLMSuggestion.get_model | get_model | Loads masked language model to predict candidates. | [
"Loads",
"masked",
"language",
"model",
"to",
"predict",
"candidates."
] | def get_model(self):
from transformers import BertTokenizer, BertForMaskedLM
self.tokenizer = BertTokenizer.from_pretrained(self.masked_model, do_lower_case=False)
self.model = BertForMaskedLM.from_pretrained(self.masked_model)
self.model.to(self.device)
self.model.eval() | ['def', 'get_model(self):', 'from', 'transformers', 'import', 'BertTokenizer,', 'BertForMaskedLM', 'self.tokenizer', '=', 'BertTokenizer.from_pretrained(self.masked_model,', 'do_lower_case=False)', 'self.model', '=', 'BertForMaskedLM.from_pretrained(self.masked_model)', 'self.model.to(self.device)', 'self.model.eval()'... | 926,038 |
textflint/textflint | mrc_sample.py | ConstituencyParse.replace_words | replace_words | Return a new tree, with new words replacing old ones. | [
"Return",
"a",
"new",
"tree,",
"with",
"new",
"words",
"replacing",
"old",
"ones."
] | def replace_words(cls, tree, new_words):
(new_tree, i) = cls._recursive_replace_words(tree, new_words, 0)
return new_tree | ['def', 'replace_words(cls,', 'tree,', 'new_words):', '(new_tree,', 'i)', '=', 'cls._recursive_replace_words(tree,', 'new_words,', '0)', 'return', 'new_tree'] | 926,192 |
johnnyp2587/transfer-learning | test_inc.py | test_pyt_image_classification_quantization | test_pyt_image_classification_quantization | Given a valid directory for output dir, test the quantization function with the actual INC called mocked out. | [
"Given",
"a",
"valid",
"directory",
"for",
"output",
"dir,",
"test",
"the",
"quantization",
"function",
"with",
"the",
"actual",
"INC",
"called",
"mocked",
"out."
] | def test_pyt_image_classification_quantization():
try:
output_dir = tempfile.mkdtemp()
model = model_factory.get_model('efficientnet_b0', 'pytorch')
with patch('tlt.datasets.image_classification.pytorch_custom_image_classification_dataset.PyTorchCustomImageClassificationDataset') as mock_dat... | ['def', 'test_pyt_image_classification_quantization():', 'try:', 'output_dir', '=', 'tempfile.mkdtemp()', 'model', '=', "model_factory.get_model('efficientnet_b0',", "'pytorch')", 'with', "patch('tlt.datasets.image_classification.pytorch_custom_image_classification_dataset.PyTorchCustomImageClassificationDataset')", 'a... | 926,696 |
johnnyp2587/transfer-learning | test_models.py | test_get_supported_models | test_get_supported_models | Call get supported models and checks to make sure the dictionary has keys for each use case, and checks for a known supported model. | [
"Call",
"get",
"supported",
"models",
"and",
"checks",
"to",
"make",
"sure",
"the",
"dictionary",
"has",
"keys",
"for",
"each",
"use",
"case,",
"and",
"checks",
"for",
"a",
"known",
"supported",
"model."
] | def test_get_supported_models():
model_dict = model_factory.get_supported_models()
for k in UseCaseType:
assert str(k) in model_dict.keys()
assert 'efficientnet_b0' in model_dict[str(UseCaseType.IMAGE_CLASSIFICATION)]
assert 'resnet50' in model_dict[str(UseCaseType.IMAGE_ANOMALY_DETECTION)]
... | ['def', 'test_get_supported_models():', 'model_dict', '=', 'model_factory.get_supported_models()', 'for', 'k', 'in', 'UseCaseType:', 'assert', 'str(k)', 'in', 'model_dict.keys()', 'assert', "'efficientnet_b0'", 'in', 'model_dict[str(UseCaseType.IMAGE_CLASSIFICATION)]', 'assert', "'resnet50'", 'in', 'model_dict[str(UseC... | 926,730 |
johnnyp2587/transfer-learning | test_image_classification.py | test_custom_callback | test_custom_callback | Tests passing custom callbacks to the TensorFlow image classification train, evaluate, and predict functions. | [
"Tests",
"passing",
"custom",
"callbacks",
"to",
"the",
"TensorFlow",
"image",
"classification",
"train,",
"evaluate,",
"and",
"predict",
"functions."
] | def test_custom_callback():
model = model_factory.get_model('efficientnet_b0', 'tensorflow')
with patch('tlt.models.image_classification.tfhub_image_classification_model.TFHubImageClassificationModel._get_hub_model') as mock_get_hub_model:
mock_dataset = MagicMock()
mock_dataset.__class__ = Imag... | ['def', 'test_custom_callback():', 'model', '=', "model_factory.get_model('efficientnet_b0',", "'tensorflow')", 'with', "patch('tlt.models.image_classification.tfhub_image_classification_model.TFHubImageClassificationModel._get_hub_model')", 'as', 'mock_get_hub_model:', 'mock_dataset', '=', 'MagicMock()', 'mock_dataset... | 926,803 |
IntelAI/transfer-learning | test_models.py | test_custom_model_train | test_custom_model_train | Tests calling train on a custom TF model with a mock dataset and mock model and verifies we get back the return value from the fit function. | [
"Tests",
"calling",
"train",
"on",
"a",
"custom",
"TF",
"model",
"with",
"a",
"mock",
"dataset",
"and",
"mock",
"model",
"and",
"verifies",
"we",
"get",
"back",
"the",
"return",
"value",
"from",
"the",
"fit",
"function."
] | def test_custom_model_train():
model = model_factory.load_model('custom_model', ALEXNET, 'tensorflow', 'image_classification')
mock_dataset = MagicMock()
mock_dataset.__class__ = ImageClassificationDataset
mock_dataset.class_names = ['1', '2', '3']
model._model = MagicMock()
expected_return_valu... | ['def', 'test_custom_model_train():', 'model', '=', "model_factory.load_model('custom_model',", 'ALEXNET,', "'tensorflow',", "'image_classification')", 'mock_dataset', '=', 'MagicMock()', 'mock_dataset.__class__', '=', 'ImageClassificationDataset', 'mock_dataset.class_names', '=', "['1',", "'2',", "'3']", 'model._model... | 927,064 |
johnnyp2587/transfer-learning | test_eval_cli.py | test_eval_dataset_catalog | test_eval_dataset_catalog | Tests the eval command a named dataset and verifies that get_dataset is called (vs load_dataset, which is used for custom dataset directories in other tests). | [
"Tests",
"the",
"eval",
"command",
"a",
"named",
"dataset",
"and",
"verifies",
"that",
"get_dataset",
"is",
"called",
"(vs",
"load_dataset,",
"which",
"is",
"used",
"for",
"custom",
"dataset",
"directories",
"in",
"other",
"tests)."
] | def test_eval_dataset_catalog(mock_get_dataset, mock_get_model, model_name, framework, dataset_name, dataset_catalog):
runner = CliRunner()
tmp_dir = tempfile.mkdtemp()
dataset_dir = os.path.join(tmp_dir, 'data')
model_dir = os.path.join(tmp_dir, 'model')
try:
for new_dir in [model_dir, data... | ['def', 'test_eval_dataset_catalog(mock_get_dataset,', 'mock_get_model,', 'model_name,', 'framework,', 'dataset_name,', 'dataset_catalog):', 'runner', '=', 'CliRunner()', 'tmp_dir', '=', 'tempfile.mkdtemp()', 'dataset_dir', '=', 'os.path.join(tmp_dir,', "'data')", 'model_dir', '=', 'os.path.join(tmp_dir,', "'model')", ... | 927,201 |
IntelAI/transfer-learning | test_eval_cli.py | test_eval_model_name | test_eval_model_name | Tests the eval command with and without providing a model name to verify that when a model name is provided, that is what's used, and when a model name is not provided, we use the model_dir folder as the model name. | [
"Tests",
"the",
"eval",
"command",
"with",
"and",
"without",
"providing",
"a",
"model",
"name",
"to",
"verify",
"that",
"when",
"a",
"model",
"name",
"is",
"provided,",
"that",
"is",
"what's",
"used,",
"and",
"when",
"a",
"model",
"name",
"is",
"not",
"p... | def test_eval_model_name(mock_load_dataset, mock_get_model, provided_model_name, model_dir, expected_model_name, framework):
runner = CliRunner()
tmp_dir = tempfile.mkdtemp()
dataset_dir = os.path.join(tmp_dir, 'data')
model_dir = os.path.join(tmp_dir, model_dir)
try:
for new_dir in [model_d... | ['def', 'test_eval_model_name(mock_load_dataset,', 'mock_get_model,', 'provided_model_name,', 'model_dir,', 'expected_model_name,', 'framework):', 'runner', '=', 'CliRunner()', 'tmp_dir', '=', 'tempfile.mkdtemp()', 'dataset_dir', '=', 'os.path.join(tmp_dir,', "'data')", 'model_dir', '=', 'os.path.join(tmp_dir,', 'model... | 927,205 |
johnnyp2587/transfer-learning | test_file_utils.py | test_validate_model_name | test_validate_model_name | Verifies that the model name passed as a string into the validate_model_name() function gives us the proper value based on the output string provided. | [
"Verifies",
"that",
"the",
"model",
"name",
"passed",
"as",
"a",
"string",
"into",
"the",
"validate_model_name()",
"function",
"gives",
"us",
"the",
"proper",
"value",
"based",
"on",
"the",
"output",
"string",
"provided."
] | def test_validate_model_name(model_name, valid_model_name):
val = validate_model_name(model_name)
assert val == valid_model_name | ['def', 'test_validate_model_name(model_name,', 'valid_model_name):', 'val', '=', 'validate_model_name(model_name)', 'assert', 'val', '==', 'valid_model_name'] | 927,394 |
johnnyp2587/transfer-learning | test_platform_util.py | test_platform_util_unsupported_os | test_platform_util_unsupported_os | Verifies that platform_utils gives us the proper values that we expect based on the lscpu_output string provided. | [
"Verifies",
"that",
"platform_utils",
"gives",
"us",
"the",
"proper",
"values",
"that",
"we",
"expect",
"based",
"on",
"the",
"lscpu_output",
"string",
"provided."
] | def test_platform_util_unsupported_os(platform_mock, subprocess_mock, os_mock):
os_mock.return_value = True
subprocess_mock.return_value = platform_config.LSCPU_OUTPUT
platform_mock.return_value = 'Mac'
with pytest.raises(NotImplementedError) as e:
PlatformUtil(verbose=True)
assert 'Mac Supp... | ['def', 'test_platform_util_unsupported_os(platform_mock,', 'subprocess_mock,', 'os_mock):', 'os_mock.return_value', '=', 'True', 'subprocess_mock.return_value', '=', 'platform_config.LSCPU_OUTPUT', 'platform_mock.return_value', '=', "'Mac'", 'with', 'pytest.raises(NotImplementedError)', 'as', 'e:', 'PlatformUtil(verbo... | 927,438 |
johnnyp2587/transfer-learning | test_platform_util.py | test_cpu_info_binding_information | test_cpu_info_binding_information | Verifies that cpu_info binding_information property gives us the proper values that we expect based on the lscpu_output string provided. | [
"Verifies",
"that",
"cpu_info",
"binding_information",
"property",
"gives",
"us",
"the",
"proper",
"values",
"that",
"we",
"expect",
"based",
"on",
"the",
"lscpu_output",
"string",
"provided."
] | def test_cpu_info_binding_information(subprocess_mock):
subprocess_mock.return_value = '# The following is the parsable format, which can be fed to other\n# programs. Each different item in every column has an unique ID\n# starting from zero.\n# CPU,Core,Socket,Node\n0,0,0,0\n1,1,0,0\n2,2,0,0\n3,3,0,0\n4,4,0,0\n5,5... | ['def', 'test_cpu_info_binding_information(subprocess_mock):', 'subprocess_mock.return_value', '=', "'#", 'The', 'following', 'is', 'the', 'parsable', 'format,', 'which', 'can', 'be', 'fed', 'to', 'other\\n#', 'programs.', 'Each', 'different', 'item', 'in', 'every', 'column', 'has', 'an', 'unique', 'ID\\n#', 'starting'... | 927,439 |
johnnyp2587/transfer-learning | test_platform_util.py | test_get_list_from_string_ranges | test_get_list_from_string_ranges | Tests the PlatformUtils _get_list_from_string_ranges function that converts string number ranges to an integer list. | [
"Tests",
"the",
"PlatformUtils",
"_get_list_from_string_ranges",
"function",
"that",
"converts",
"string",
"number",
"ranges",
"to",
"an",
"integer",
"list."
] | def test_get_list_from_string_ranges(get_cpuset_mock, platform_mock, subprocess_mock, os_mock, cpuset_range, expected_list):
platform_mock.return_value = platform_config.SYSTEM_TYPE
subprocess_mock.return_value = platform_config.LSCPU_OUTPUT
get_cpuset_mock.return_value = cpuset_range
os_mock.return_val... | ['def', 'test_get_list_from_string_ranges(get_cpuset_mock,', 'platform_mock,', 'subprocess_mock,', 'os_mock,', 'cpuset_range,', 'expected_list):', 'platform_mock.return_value', '=', 'platform_config.SYSTEM_TYPE', 'subprocess_mock.return_value', '=', 'platform_config.LSCPU_OUTPUT', 'get_cpuset_mock.return_value', '=', '... | 927,443 |
johnnyp2587/transfer-learning | test_platform_util.py | test_platform_util_with_no_args | test_platform_util_with_no_args | Verifies that PlatformUtil object can be created with an empty string, as needed by the performance Jupyter notebooks. | [
"Verifies",
"that",
"PlatformUtil",
"object",
"can",
"be",
"created",
"with",
"an",
"empty",
"string,",
"as",
"needed",
"by",
"the",
"performance",
"Jupyter",
"notebooks."
] | def test_platform_util_with_no_args(platform_mock, subprocess_mock):
platform_mock.return_value = platform_config.SYSTEM_TYPE
subprocess_mock.return_value = platform_config.LSCPU_OUTPUT
platform_util = PlatformUtil()
assert platform_util.num_logical_cpus == 112 | ['def', 'test_platform_util_with_no_args(platform_mock,', 'subprocess_mock):', 'platform_mock.return_value', '=', 'platform_config.SYSTEM_TYPE', 'subprocess_mock.return_value', '=', 'platform_config.LSCPU_OUTPUT', 'platform_util', '=', 'PlatformUtil()', 'assert', 'platform_util.num_logical_cpus', '==', '112'] | 927,446 |
johnnyp2587/transfer-learning | dataset_factory.py | get_dataset | get_dataset | A factory method for using a dataset from a catalog. | [
"A",
"factory",
"method",
"for",
"using",
"a",
"dataset",
"from",
"a",
"catalog."
] | def get_dataset(dataset_dir: str, use_case: UseCaseType, framework: FrameworkType, dataset_name: str=None, dataset_catalog: str=None, **kwargs):
if not isinstance(framework, FrameworkType):
framework = FrameworkType.from_str(framework)
if not isinstance(use_case, UseCaseType):
use_case = UseCase... | ['def', 'get_dataset(dataset_dir:', 'str,', 'use_case:', 'UseCaseType,', 'framework:', 'FrameworkType,', 'dataset_name:', 'str=None,', 'dataset_catalog:', 'str=None,', '**kwargs):', 'if', 'not', 'isinstance(framework,', 'FrameworkType):', 'framework', '=', 'FrameworkType.from_str(framework)', 'if', 'not', 'isinstance(u... | 927,569 |
johnnyp2587/transfer-learning | hf_dataset.py | HFDataset.get_batch | get_batch | Get a single batch of images and labels from the dataset. | [
"Get",
"a",
"single",
"batch",
"of",
"images",
"and",
"labels",
"from",
"the",
"dataset."
] | def get_batch(self, subset='all'):
if subset == 'all' and self._dataset is not None:
return next(iter(self._data_loader))
elif subset == 'train' and self.train_subset is not None:
return next(iter(self._train_loader))
elif subset == 'validation' and self.validation_subset is not None:
... | ['def', 'get_batch(self,', "subset='all'):", 'if', 'subset', '==', "'all'", 'and', 'self._dataset', 'is', 'not', 'None:', 'return', 'next(iter(self._data_loader))', 'elif', 'subset', '==', "'train'", 'and', 'self.train_subset', 'is', 'not', 'None:', 'return', 'next(iter(self._train_loader))', 'elif', 'subset', '==', "'... | 927,576 |
johnnyp2587/transfer-learning | hf_dataset.py | HFDataset.shuffle_split | shuffle_split | Randomly split the dataset into train, validation, and test subsets with a pseudo-random seed option. | [
"Randomly",
"split",
"the",
"dataset",
"into",
"train,",
"validation,",
"and",
"test",
"subsets",
"with",
"a",
"pseudo-random",
"seed",
"option."
] | def shuffle_split(self, train_pct=0.75, val_pct=0.25, test_pct=0.0, shuffle_files=True, seed=None):
if not (isinstance(train_pct, float) and isinstance(val_pct, float) and isinstance(test_pct, float)):
raise ValueError('Percentage arguments must be floats.')
if train_pct + val_pct + test_pct > 1.0:
... | ['def', 'shuffle_split(self,', 'train_pct=0.75,', 'val_pct=0.25,', 'test_pct=0.0,', 'shuffle_files=True,', 'seed=None):', 'if', 'not', '(isinstance(train_pct,', 'float)', 'and', 'isinstance(val_pct,', 'float)', 'and', 'isinstance(test_pct,', 'float)):', 'raise', "ValueError('Percentage", 'arguments', 'must', 'be', "flo... | 927,578 |
johnnyp2587/transfer-learning | pytorch_custom_image_anomaly_detection_dataset.py | AnomalyImageFolder.has_valid_file_extension | has_valid_file_extension | Checks if a file has a valid extension. | [
"Checks",
"if",
"a",
"file",
"has",
"a",
"valid",
"extension."
] | def has_valid_file_extension(self, filename: str, extensions: Union[str, Tuple[str, ...]]) -> bool:
return filename.lower().endswith(extensions if isinstance(extensions, str) else tuple(extensions)) | ['def', 'has_valid_file_extension(self,', 'filename:', 'str,', 'extensions:', 'Union[str,', 'Tuple[str,', '...]])', '->', 'bool:', 'return', 'filename.lower().endswith(extensions', 'if', 'isinstance(extensions,', 'str)', 'else', 'tuple(extensions))'] | 927,709 |
yanqi1811/transfer-learning | pytorch_custom_image_anomaly_detection_dataset.py | PyTorchCustomImageAnomalyDetectionDataset.simsiam_transform | simsiam_transform | Perform TwoCropsTransform and GaussianBlur on the dataset for SIMSIAM training. | [
"Perform",
"TwoCropsTransform",
"and",
"GaussianBlur",
"on",
"the",
"dataset",
"for",
"SIMSIAM",
"training."
] | def simsiam_transform(self, image_size):
augmentation = [T.RandomResizedCrop(image_size, scale=(0.2, 1.0)), T.RandomApply([T.ColorJitter(0.1, 0.1, 0.1, 0.1)], p=0.8), T.RandomGrayscale(p=0.2), T.RandomApply([ssloader.GaussianBlur([0.1, 2.0])], p=0.5), T.RandomHorizontalFlip(), T.ToTensor(), T.Normalize(mean=[0.485,... | ['def', 'simsiam_transform(self,', 'image_size):', 'augmentation', '=', '[T.RandomResizedCrop(image_size,', 'scale=(0.2,', '1.0)),', 'T.RandomApply([T.ColorJitter(0.1,', '0.1,', '0.1,', '0.1)],', 'p=0.8),', 'T.RandomGrayscale(p=0.2),', 'T.RandomApply([ssloader.GaussianBlur([0.1,', '2.0])],', 'p=0.5),', 'T.RandomHorizon... | 927,739 |
johnnyp2587/transfer-learning | model_factory.py | load_model | load_model | A factory method for loading an existing model. | [
"A",
"factory",
"method",
"for",
"loading",
"an",
"existing",
"model."
] | def load_model(model_name: str, model, framework: FrameworkType=None, use_case: UseCaseType=None, model_hub: str=None, **kwargs):
if not isinstance(framework, FrameworkType):
framework = FrameworkType.from_str(framework)
if use_case is not None and (not isinstance(use_case, UseCaseType)):
use_ca... | ['def', 'load_model(model_name:', 'str,', 'model,', 'framework:', 'FrameworkType=None,', 'use_case:', 'UseCaseType=None,', 'model_hub:', 'str=None,', '**kwargs):', 'if', 'not', 'isinstance(framework,', 'FrameworkType):', 'framework', '=', 'FrameworkType.from_str(framework)', 'if', 'use_case', 'is', 'not', 'None', 'and'... | 928,059 |
johnnyp2587/transfer-learning | model_factory.py | get_model | get_model | A factory method for creating models. | [
"A",
"factory",
"method",
"for",
"creating",
"models."
] | def get_model(model_name: str, framework: FrameworkType=None, use_case: UseCaseType=None, **kwargs):
if not isinstance(framework, FrameworkType):
framework = FrameworkType.from_str(framework)
if use_case is not None and (not isinstance(use_case, UseCaseType)):
use_case = UseCaseType.from_str(use... | ['def', 'get_model(model_name:', 'str,', 'framework:', 'FrameworkType=None,', 'use_case:', 'UseCaseType=None,', '**kwargs):', 'if', 'not', 'isinstance(framework,', 'FrameworkType):', 'framework', '=', 'FrameworkType.from_str(framework)', 'if', 'use_case', 'is', 'not', 'None', 'and', '(not', 'isinstance(use_case,', 'Use... | 928,060 |
johnnyp2587/transfer-learning | pytorch_image_anomaly_detection_model.py | pca | pca | Finds the principal components of the features specified. | [
"Finds",
"the",
"principal",
"components",
"of",
"the",
"features",
"specified."
] | def pca(features, threshold=0.99):
features = features.numpy()
principal_components = PCA(threshold)
pca_mats = principal_components.fit(features.T)
return pca_mats | ['def', 'pca(features,', 'threshold=0.99):', 'features', '=', 'features.numpy()', 'principal_components', '=', 'PCA(threshold)', 'pca_mats', '=', 'principal_components.fit(features.T)', 'return', 'pca_mats'] | 928,187 |
johnnyp2587/transfer-learning | pytorch_image_anomaly_detection_model.py | PyTorchImageAnomalyDetectionModel.train_simsiam | train_simsiam | Trains a SimSiam model using the specified dataset. | [
"Trains",
"a",
"SimSiam",
"model",
"using",
"the",
"specified",
"dataset."
] | def train_simsiam(self, dataset, output_dir, epochs, feature_dim, pred_dim, batch_size=64, initial_checkpoints=None, generate_checkpoints=False, precision='float32'):
self.LR = 0.171842137353148
self.batch_size = batch_size
self.batch_size_ss = 64
self.epochs = epochs
self.simsiam = True
dataset... | ['def', 'train_simsiam(self,', 'dataset,', 'output_dir,', 'epochs,', 'feature_dim,', 'pred_dim,', 'batch_size=64,', 'initial_checkpoints=None,', 'generate_checkpoints=False,', "precision='float32'):", 'self.LR', '=', '0.171842137353148', 'self.batch_size', '=', 'batch_size', 'self.batch_size_ss', '=', '64', 'self.epoch... | 928,190 |
johnnyp2587/transfer-learning | pytorch_image_anomaly_detection_model.py | PyTorchImageAnomalyDetectionModel.train_cutpaste | train_cutpaste | Trains a CutPaste model using the specified dataset. | [
"Trains",
"a",
"CutPaste",
"model",
"using",
"the",
"specified",
"dataset."
] | def train_cutpaste(self, dataset, output_dir, optim, epochs, freeze_resnet, head_layer, cutpaste_type, initial_checkpoints=None, generate_checkpoints=False, precision='float32'):
self.variant_map = {'normal': CutPasteNormal, 'scar': CutPasteScar, '3way': CutPaste3Way, 'union': CutPasteUnion}
variant = self.vari... | ['def', 'train_cutpaste(self,', 'dataset,', 'output_dir,', 'optim,', 'epochs,', 'freeze_resnet,', 'head_layer,', 'cutpaste_type,', 'initial_checkpoints=None,', 'generate_checkpoints=False,', "precision='float32'):", 'self.variant_map', '=', "{'normal':", 'CutPasteNormal,', "'scar':", 'CutPasteScar,', "'3way':", 'CutPas... | 928,191 |
johnnyp2587/transfer-learning | utils.py | find_threshold | find_threshold | Compute threshold for calculating accuracy. | [
"Compute",
"threshold",
"for",
"calculating",
"accuracy."
] | def find_threshold(fpr, tpr, thr):
j_scores = tpr - fpr
j_ordered = sorted(zip(j_scores, thr))
return np.round(j_ordered[-1][1], 2) | ['def', 'find_threshold(fpr,', 'tpr,', 'thr):', 'j_scores', '=', 'tpr', '-', 'fpr', 'j_ordered', '=', 'sorted(zip(j_scores,', 'thr))', 'return', 'np.round(j_ordered[-1][1],', '2)'] | 928,257 |
IntelAI/transfer-learning | pytorch_image_classification_model.py | PyTorchImageClassificationModel.predict | predict | Perform feed-forward inference and predict the classes of the input_samples. | [
"Perform",
"feed-forward",
"inference",
"and",
"predict",
"the",
"classes",
"of",
"the",
"input_samples."
] | def predict(self, input_samples, return_type='class'):
return_types = ['class', 'probabilities', 'scores']
if not isinstance(return_type, str) or return_type not in return_types:
raise ValueError('Invalid return_type ({}). Expected one of {}.'.format(return_type, return_types))
self._model.eval()
... | ['def', 'predict(self,', 'input_samples,', "return_type='class'):", 'return_types', '=', "['class',", "'probabilities',", "'scores']", 'if', 'not', 'isinstance(return_type,', 'str)', 'or', 'return_type', 'not', 'in', 'return_types:', 'raise', "ValueError('Invalid", 'return_type', '({}).', 'Expected', 'one', 'of', "{}.'... | 928,320 |
johnnyp2587/transfer-learning | pytorch_hf_text_classification_model.py | PyTorchHFTextClassificationModel.train | train | Trains the model using the specified text classification dataset. | [
"Trains",
"the",
"model",
"using",
"the",
"specified",
"text",
"classification",
"dataset."
] | def train(self, dataset, output_dir: str, epochs: int=1, initial_checkpoints=None, learning_rate: float=1e-05, do_eval: bool=True, early_stopping: bool=False, lr_decay: bool=True, seed: int=None, extra_layers: list=None, device: str='cpu', ipex_optimize: bool=True, use_trainer: bool=False, force_download: bool=False, d... | ['def', 'train(self,', 'dataset,', 'output_dir:', 'str,', 'epochs:', 'int=1,', 'initial_checkpoints=None,', 'learning_rate:', 'float=1e-05,', 'do_eval:', 'bool=True,', 'early_stopping:', 'bool=False,', 'lr_decay:', 'bool=True,', 'seed:', 'int=None,', 'extra_layers:', 'list=None,', 'device:', "str='cpu',", 'ipex_optimiz... | 928,439 |
johnnyp2587/transfer-learning | pytorch_hf_text_classification_model.py | PyTorchHFTextClassificationModel.predict | predict | Generates predictions for the specified input samples. | [
"Generates",
"predictions",
"for",
"the",
"specified",
"input",
"samples."
] | def predict(self, input_samples, return_raw=False):
encoded_input = None
if isinstance(input_samples, str) or isinstance(input_samples, list):
encoded_input = self._tokenizer(input_samples, padding=True, return_tensors='pt')
elif isinstance(input_samples, dict):
required_keys = ['input_ids',... | ['def', 'predict(self,', 'input_samples,', 'return_raw=False):', 'encoded_input', '=', 'None', 'if', 'isinstance(input_samples,', 'str)', 'or', 'isinstance(input_samples,', 'list):', 'encoded_input', '=', 'self._tokenizer(input_samples,', 'padding=True,', "return_tensors='pt')", 'elif', 'isinstance(input_samples,', 'di... | 928,441 |
IntelAI/transfer-learning | pytorch_hf_text_classification_model.py | PyTorchHFTextClassificationModel.export | export | Saves the model to the given output_dir directory. | [
"Saves",
"the",
"model",
"to",
"the",
"given",
"output_dir",
"directory."
] | def export(self, output_dir: str):
if self._model:
verify_directory(output_dir)
valid_model_name = validate_model_name(self.model_name)
saved_model_dir = os.path.join(output_dir, valid_model_name)
if os.path.exists(saved_model_dir) and len(os.listdir(saved_model_dir)):
sa... | ['def', 'export(self,', 'output_dir:', 'str):', 'if', 'self._model:', 'verify_directory(output_dir)', 'valid_model_name', '=', 'validate_model_name(self.model_name)', 'saved_model_dir', '=', 'os.path.join(output_dir,', 'valid_model_name)', 'if', 'os.path.exists(saved_model_dir)', 'and', 'len(os.listdir(saved_model_dir)... | 928,452 |
johnnyp2587/transfer-learning | list.py | list_models | list_models | List the supported models and the information that we have about each model from the config files. | [
"List",
"the",
"supported",
"models",
"and",
"the",
"information",
"that",
"we",
"have",
"about",
"each",
"model",
"from",
"the",
"config",
"files."
] | def list_models(framework, use_case, verbose, markdown):
from tlt.models.model_factory import print_supported_models
try:
print_supported_models(framework, use_case, verbose, markdown)
except Exception as e:
sys.exit('Error while listing the supported models for framework: {}, use case: {}\n... | ['def', 'list_models(framework,', 'use_case,', 'verbose,', 'markdown):', 'from', 'tlt.models.model_factory', 'import', 'print_supported_models', 'try:', 'print_supported_models(framework,', 'use_case,', 'verbose,', 'markdown)', 'except', 'Exception', 'as', 'e:', "sys.exit('Error", 'while', 'listing', 'the', 'supported'... | 928,613 |
johnnyp2587/transfer-learning | file_utils.py | download_and_extract_zip_file | download_and_extract_zip_file | Downloads a tar file using the specified URL to the destination directory, then extracts the zip file to the destination directory. | [
"Downloads",
"a",
"tar",
"file",
"using",
"the",
"specified",
"URL",
"to",
"the",
"destination",
"directory,",
"then",
"extracts",
"the",
"zip",
"file",
"to",
"the",
"destination",
"directory."
] | def download_and_extract_zip_file(zip_file_url, destination_directory):
local_zip_path = download_file(zip_file_url, destination_directory)
if os.path.isfile(local_zip_path):
extract_zip_file(local_zip_path, destination_directory)
else:
raise FileNotFoundError('Unable to find the downloaded ... | ['def', 'download_and_extract_zip_file(zip_file_url,', 'destination_directory):', 'local_zip_path', '=', 'download_file(zip_file_url,', 'destination_directory)', 'if', 'os.path.isfile(local_zip_path):', 'extract_zip_file(local_zip_path,', 'destination_directory)', 'else:', 'raise', "FileNotFoundError('Unable", 'to', 'f... | 928,652 |
IntelAI/transfer-learning | file_utils.py | download_and_extract_tar_file | download_and_extract_tar_file | Downloads a tar file using the specified URL to the destination directory, then extracts the tar file to the destination directory. | [
"Downloads",
"a",
"tar",
"file",
"using",
"the",
"specified",
"URL",
"to",
"the",
"destination",
"directory,",
"then",
"extracts",
"the",
"tar",
"file",
"to",
"the",
"destination",
"directory."
] | def download_and_extract_tar_file(tar_file_url, destination_directory):
local_tar_path = download_file(tar_file_url, destination_directory)
if os.path.isfile(local_tar_path):
extract_tar_file(local_tar_path, destination_directory)
else:
raise FileNotFoundError('Unable to find the downloaded ... | ['def', 'download_and_extract_tar_file(tar_file_url,', 'destination_directory):', 'local_tar_path', '=', 'download_file(tar_file_url,', 'destination_directory)', 'if', 'os.path.isfile(local_tar_path):', 'extract_tar_file(local_tar_path,', 'destination_directory)', 'else:', 'raise', "FileNotFoundError('Unable", 'to', 'f... | 928,660 |
johnnyp2587/transfer-learning | inc_utils.py | get_inc_config | get_inc_config | Creates an INC post-training quantization config from the specified parameters. | [
"Creates",
"an",
"INC",
"post-training",
"quantization",
"config",
"from",
"the",
"specified",
"parameters."
] | def get_inc_config(approach='static', accuracy_criterion_relative=0.01, exit_policy_timeout=0, exit_policy_max_trials=50):
if approach not in ['static', 'dynamic']:
raise ValueError("Invalid value for the quantization approach ({}). Expected either 'static' or 'dynamic'.")
if accuracy_criterion_relative... | ['def', "get_inc_config(approach='static',", 'accuracy_criterion_relative=0.01,', 'exit_policy_timeout=0,', 'exit_policy_max_trials=50):', 'if', 'approach', 'not', 'in', "['static',", "'dynamic']:", 'raise', 'ValueError("Invalid', 'value', 'for', 'the', 'quantization', 'approach', '({}).', 'Expected', 'either', "'stati... | 928,710 |
yanqi1811/transfer-learning | util_functions.py | gen_preds | gen_preds | Generates predictions on a novel data array using a fit classifier clf is a classifier that has already been fit arr is a data array identical in dimension to the array clf was trained on Returns the array of predictions. | [
"Generates",
"predictions",
"on",
"a",
"novel",
"data",
"array",
"using",
"a",
"fit",
"classifier",
"clf",
"is",
"a",
"classifier",
"that",
"has",
"already",
"been",
"fit",
"arr",
"is",
"a",
"data",
"array",
"identical",
"in",
"dimension",
"to",
"the",
"ar... | def gen_preds(clf, arr):
if hasattr(clf, 'predict_proba'):
ret = clf.predict(arr)
else:
ret = clf.predict(arr)
return ret | ['def', 'gen_preds(clf,', 'arr):', 'if', 'hasattr(clf,', "'predict_proba'):", 'ret', '=', 'clf.predict(arr)', 'else:', 'ret', '=', 'clf.predict(arr)', 'return', 'ret'] | 929,363 |
johnnyp2587/transfer-learning | seq2seq.py | variational_encoder_with_buckets | variational_encoder_with_buckets | Create a sequence-to-sequence model with support for bucketing. | [
"Create",
"a",
"sequence-to-sequence",
"model",
"with",
"support",
"for",
"bucketing."
] | def variational_encoder_with_buckets(encoder_inputs, buckets, encoder, enc_latent, softmax_loss_function=None, per_example_loss=False, name=None):
if len(encoder_inputs) < buckets[-1][0]:
raise ValueError('Length of encoder_inputs (%d) must be at least that of last bucket (%d).' % (len(encoder_inputs), buck... | ['def', 'variational_encoder_with_buckets(encoder_inputs,', 'buckets,', 'encoder,', 'enc_latent,', 'softmax_loss_function=None,', 'per_example_loss=False,', 'name=None):', 'if', 'len(encoder_inputs)', '<', 'buckets[-1][0]:', 'raise', "ValueError('Length", 'of', 'encoder_inputs', '(%d)', 'must', 'be', 'at', 'least', 'th... | 929,518 |
ciads-ut/transfer-learning-ner | label_mismatch.py | plot_TSNE | plot_TSNE | Make one plot of the TSNE embedding of the label points given in matrix U. | [
"Make",
"one",
"plot",
"of",
"the",
"TSNE",
"embedding",
"of",
"the",
"label",
"points",
"given",
"in",
"matrix",
"U."
] | def plot_TSNE(U, i2l, numclusters, seed=0):
(clusters, cl) = kmeans(U, i2l, numclusters)
model = TSNE(n_components=2, random_state=seed)
tsne = model.fit_transform(U)
clustercolors = [i / (U.shape[0] + 0.0) for i in clusters]
cm = plt.cm.get_cmap('RdYlBu')
avg_norm = np.mean([norm(tsne[i]) for i... | ['def', 'plot_TSNE(U,', 'i2l,', 'numclusters,', 'seed=0):', '(clusters,', 'cl)', '=', 'kmeans(U,', 'i2l,', 'numclusters)', 'model', '=', 'TSNE(n_components=2,', 'random_state=seed)', 'tsne', '=', 'model.fit_transform(U)', 'clustercolors', '=', '[i', '/', '(U.shape[0]', '+', '0.0)', 'for', 'i', 'in', 'clusters]', 'cm', ... | 929,711 |
ciads-ut/transfer-learning-ner | label_mismatch.py | distance_matrix | distance_matrix | Get distances between every pair of points; each point is a row of U. | [
"Get",
"distances",
"between",
"every",
"pair",
"of",
"points;",
"each",
"point",
"is",
"a",
"row",
"of",
"U."
] | def distance_matrix(U, l2i, i2l):
n = U.shape[0]
distances = np.zeros((n, n))
for i in range(n):
for j in range(n):
distances[i, j] = np.linalg.norm(U[i] - U[j])
distances[i, i] = 1e+16
closest = [np.argmin(distances[i]) for i in range(n)]
closest_labels = {}
for ... | ['def', 'distance_matrix(U,', 'l2i,', 'i2l):', 'n', '=', 'U.shape[0]', 'distances', '=', 'np.zeros((n,', 'n))', 'for', 'i', 'in', 'range(n):', 'for', 'j', 'in', 'range(n):', 'distances[i,', 'j]', '=', 'np.linalg.norm(U[i]', '-', 'U[j])', 'distances[i,', 'i]', '=', '1e+16', 'closest', '=', '[np.argmin(distances[i])', 'f... | 929,712 |
MLC-CV/transfer-learning-understanding | fixup_resnet_imagenet.py | fixup_resnet18 | fixup_resnet18 | Constructs a Fixup-ResNet-18 model. | [
"Constructs",
"a",
"Fixup-ResNet-18",
"model."
] | def fixup_resnet18(**kwargs):
model = FixupResNet(FixupBasicBlock, [2, 2, 2, 2], **kwargs)
return model | ['def', 'fixup_resnet18(**kwargs):', 'model', '=', 'FixupResNet(FixupBasicBlock,', '[2,', '2,', '2,', '2],', '**kwargs)', 'return', 'model'] | 929,762 |
MLC-CV/transfer-learning-understanding | fixup_resnet_imagenet.py | fixup_resnet101 | fixup_resnet101 | Constructs a Fixup-ResNet-101 model. | [
"Constructs",
"a",
"Fixup-ResNet-101",
"model."
] | def fixup_resnet101(**kwargs):
model = FixupResNet(FixupBottleneck, [3, 4, 23, 3], **kwargs)
return model | ['def', 'fixup_resnet101(**kwargs):', 'model', '=', 'FixupResNet(FixupBottleneck,', '[3,', '4,', '23,', '3],', '**kwargs)', 'return', 'model'] | 929,765 |
MLC-CV/transfer-learning-understanding | fixup_resnet_imagenet.py | fixup_resnet152 | fixup_resnet152 | Constructs a Fixup-ResNet-152 model. | [
"Constructs",
"a",
"Fixup-ResNet-152",
"model."
] | def fixup_resnet152(**kwargs):
model = FixupResNet(FixupBottleneck, [3, 8, 36, 3], **kwargs)
return model | ['def', 'fixup_resnet152(**kwargs):', 'model', '=', 'FixupResNet(FixupBottleneck,', '[3,', '8,', '36,', '3],', '**kwargs)', 'return', 'model'] | 929,766 |
sunziping2016/transfer-tensorflow | loader.py | load_dataset | load_dataset | Shuffles and loads data from dataset, applys specified transforms and joins transformed data to mini batches. | [
"Shuffles",
"and",
"loads",
"data",
"from",
"dataset,",
"applys",
"specified",
"transforms",
"and",
"joins",
"transformed",
"data",
"to",
"mini",
"batches."
] | def load_dataset(dataset, batch_size=None, transforms=None, shuffle=True, shuffle_buffer_size=None, epochs=None):
sources = tuple(map(tf.convert_to_tensor, dataset.sources))
if shuffle:
indices = tf.range(0, tf.shape(dataset.sources[0])[0])
indices = tf.random_shuffle(indices)
sources = ... | ['def', 'load_dataset(dataset,', 'batch_size=None,', 'transforms=None,', 'shuffle=True,', 'shuffle_buffer_size=None,', 'epochs=None):', 'sources', '=', 'tuple(map(tf.convert_to_tensor,', 'dataset.sources))', 'if', 'shuffle:', 'indices', '=', 'tf.range(0,', 'tf.shape(dataset.sources[0])[0])', 'indices', '=', 'tf.random_... | 929,859 |
mrkolarik/transfer2d3d | losses.py | accuracy_smooth | accuracy_smooth | Calculates accuracy for label smoothing - rounds labels and predictions. | [
"Calculates",
"accuracy",
"for",
"label",
"smoothing",
"-",
"rounds",
"labels",
"and",
"predictions."
] | def accuracy_smooth(y_true, y_pred):
y_true_f = K.flatten(tf.round(y_true))
y_pred_f = K.flatten(tf.round(y_pred))
count_equal = tf.math.count_nonzero(tf.equal(y_true_f, y_pred_f), dtype=tf.dtypes.int32)
count_all = tf.shape(y_true_f, out_type=tf.dtypes.int32)[0]
return tf.math.divide(count_equal, c... | ['def', 'accuracy_smooth(y_true,', 'y_pred):', 'y_true_f', '=', 'K.flatten(tf.round(y_true))', 'y_pred_f', '=', 'K.flatten(tf.round(y_pred))', 'count_equal', '=', 'tf.math.count_nonzero(tf.equal(y_true_f,', 'y_pred_f),', 'dtype=tf.dtypes.int32)', 'count_all', '=', 'tf.shape(y_true_f,', 'out_type=tf.dtypes.int32)[0]', '... | 929,861 |
mrkolarik/transfer2d3d | losses.py | recall | recall | Calculates the recall, a metric for multi-label classification of how many relevant items are selected. | [
"Calculates",
"the",
"recall,",
"a",
"metric",
"for",
"multi-label",
"classification",
"of",
"how",
"many",
"relevant",
"items",
"are",
"selected."
] | def recall(y_true, y_pred):
true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))
possible_positives = K.sum(K.round(K.clip(y_true, 0, 1)))
recall = true_positives / (possible_positives + K.epsilon())
return recall | ['def', 'recall(y_true,', 'y_pred):', 'true_positives', '=', 'K.sum(K.round(K.clip(y_true', '*', 'y_pred,', '0,', '1)))', 'possible_positives', '=', 'K.sum(K.round(K.clip(y_true,', '0,', '1)))', 'recall', '=', 'true_positives', '/', '(possible_positives', '+', 'K.epsilon())', 'return', 'recall'] | 929,862 |
rr-learning/transferable_dynamics_dataset | dynamics_learner_interface.py | DynamicsLearnerInterface.load_normalization_stats | load_normalization_stats | Loads the normalization statistics from the input data. | [
"Loads",
"the",
"normalization",
"statistics",
"from",
"the",
"input",
"data."
] | def load_normalization_stats(self, observation_sequences, action_sequences):
self._check_learning_inputs(observation_sequences, action_sequences)
if not self.streaming:
(targets, inputs) = unrollTrainingData(observation_sequences, action_sequences, self.history_length, self.prediction_horizon, self.diff... | ['def', 'load_normalization_stats(self,', 'observation_sequences,', 'action_sequences):', 'self._check_learning_inputs(observation_sequences,', 'action_sequences)', 'if', 'not', 'self.streaming:', '(targets,', 'inputs)', '=', 'unrollTrainingData(observation_sequences,', 'action_sequences,', 'self.history_length,', 'sel... | 929,914 |
rr-learning/transferable_dynamics_dataset | BNN.py | BNNLearner.load | load | Parameters ---------- filename: string used as filename to load a model. | [
"Parameters",
"----------",
"filename:",
"string",
"used",
"as",
"filename",
"to",
"load",
"a",
"model."
] | def load(self, filename):
raise NotImplementedError | ['def', 'load(self,', 'filename):', 'raise', 'NotImplementedError'] | 929,917 |
rr-learning/transferable_dynamics_dataset | eql_dynamics_learner.py | EQL.load | load | Parameters ---------- filename: string used as filename to save a model. | [
"Parameters",
"----------",
"filename:",
"string",
"used",
"as",
"filename",
"to",
"save",
"a",
"model."
] | def load(self, model_filename):
with open(model_filename, 'rb') as handle:
expr = pickle.load(handle)
self.model_fn.evaluation_hook.numba_expr = expr | ['def', 'load(self,', 'model_filename):', 'with', 'open(model_filename,', "'rb')", 'as', 'handle:', 'expr', '=', 'pickle.load(handle)', 'self.model_fn.evaluation_hook.numba_expr', '=', 'expr'] | 929,920 |
rr-learning/transferable_dynamics_dataset | SKI.py | SKIDynamicsLearner.learn | learn | Parameters ---------- observations_sequences: np-array of shape nSequences x nStepsPerRollout x nStates past state observations action_sequences: np-array of shape nSequences x nStepsPerRollout x nInputs actions taken at the corresponding time points. | [
"Parameters",
"----------",
"observations_sequences:",
"np-array",
"of",
"shape",
"nSequences",
"x",
"nStepsPerRollout",
"x",
"nStates",
"past",
"state",
"observations",
"action_sequences:",
"np-array",
"of",
"shape",
"nSequences",
"x",
"nStepsPerRollout",
"x",
"nInputs",... | def learn(self, observation_sequences, action_sequences):
(targets, inputs) = unrollForDifferenceTraining(observation_sequences, action_sequences)
targets = np.asarray(targets, dtype=np.double)
inputs = np.asarray(inputs, dtype=np.double)
self.targetStandardizer = Standardizer(targets)
self.inputSta... | ['def', 'learn(self,', 'observation_sequences,', 'action_sequences):', '(targets,', 'inputs)', '=', 'unrollForDifferenceTraining(observation_sequences,', 'action_sequences)', 'targets', '=', 'np.asarray(targets,', 'dtype=np.double)', 'inputs', '=', 'np.asarray(inputs,', 'dtype=np.double)', 'self.targetStandardizer', '=... | 929,922 |
rr-learning/transferable_dynamics_dataset | SVGPR.py | SVGPR.run_adam_ | run_adam_ | Utility function running the Adam Optimiser interleaved with a `Logger` action. | [
"Utility",
"function",
"running",
"the",
"Adam",
"Optimiser",
"interleaved",
"with",
"a",
"`Logger`",
"action."
] | def run_adam_(self, ntraining):
niterations = ntraining // self.minibatch_size
if niterations % self.minibatch_size > 0:
niterations += 1
niterations = niterations * self.epochs
print('Initial loglikelihood: ', self.model_.compute_log_likelihood())
adam = gpflow.train.AdamOptimizer().make_op... | ['def', 'run_adam_(self,', 'ntraining):', 'niterations', '=', 'ntraining', '//', 'self.minibatch_size', 'if', 'niterations', '%', 'self.minibatch_size', '>', '0:', 'niterations', '+=', '1', 'niterations', '=', 'niterations', '*', 'self.epochs', "print('Initial", 'loglikelihood:', "',", 'self.model_.compute_log_likeliho... | 929,924 |
rr-learning/transferable_dynamics_dataset | system_id.py | save_simulated_data | save_simulated_data | Stores the simulated data in a compatible format with the dynamics learning code. | [
"Stores",
"the",
"simulated",
"data",
"in",
"a",
"compatible",
"format",
"with",
"the",
"dynamics",
"learning",
"code."
] | def save_simulated_data(angles, velocities, torques, filename):
data_dict = {}
data_dict['measured_angles'] = angles
data_dict['measured_velocities'] = velocities
data_dict['measured_torques'] = torques
data_dict['constrained_torques'] = torques
data_dict['desired_torques'] = torques
np.save... | ['def', 'save_simulated_data(angles,', 'velocities,', 'torques,', 'filename):', 'data_dict', '=', '{}', "data_dict['measured_angles']", '=', 'angles', "data_dict['measured_velocities']", '=', 'velocities', "data_dict['measured_torques']", '=', 'torques', "data_dict['constrained_torques']", '=', 'torques', "data_dict['d... | 929,927 |
rr-learning/transferable_dynamics_dataset | system_id.py | Robot.simulate | simulate | Returns the sequence of angles, velocities and torques resulting from simulating the given torques. | [
"Returns",
"the",
"sequence",
"of",
"angles,",
"velocities",
"and",
"torques",
"resulting",
"from",
"simulating",
"the",
"given",
"torques."
] | def simulate(self, dt, n_steps=None, torque=None, initial_angle=None, initial_velocity=None, mask=np.ones(3), verbose=False):
zero = pinocchio.utils.zero(self.model.nv)
torque = np.array(zero) if torque is None else np.array(torque)
torque = torque.reshape(-1, 3, 1)
if torque.shape[0] == 1:
asse... | ['def', 'simulate(self,', 'dt,', 'n_steps=None,', 'torque=None,', 'initial_angle=None,', 'initial_velocity=None,', 'mask=np.ones(3),', 'verbose=False):', 'zero', '=', 'pinocchio.utils.zero(self.model.nv)', 'torque', '=', 'np.array(zero)', 'if', 'torque', 'is', 'None', 'else', 'np.array(torque)', 'torque', '=', 'torque.... | 929,928 |
rr-learning/transferable_dynamics_dataset | data_extractor.py | discard_prefix | discard_prefix | Removes the prefix of each rollout. | [
"Removes",
"the",
"prefix",
"of",
"each",
"rollout."
] | def discard_prefix(data, discard_prefix):
for key in data.keys():
data[key] = data[key][:, discard_prefix:, :]
return data | ['def', 'discard_prefix(data,', 'discard_prefix):', 'for', 'key', 'in', 'data.keys():', 'data[key]', '=', 'data[key][:,', 'discard_prefix:,', ':]', 'return', 'data'] | 929,929 |
sbjelogr/TransferBoost | conftest.py | leaves_indexes | leaves_indexes | Mocked indexes of the leaf trees in an xgboost model. | [
"Mocked",
"indexes",
"of",
"the",
"leaf",
"trees",
"in",
"an",
"xgboost",
"model."
] | def leaves_indexes():
return np.array([[2, 2, 2, 2], [1, 1, 1, 1], [2, 2, 2, 2], [2, 2, 2, 2], [1, 2, 1, 1], [1, 1, 1, 1], [2, 2, 2, 2], [1, 1, 1, 1], [1, 2, 2, 2], [1, 1, 1, 1]]) | ['def', 'leaves_indexes():', 'return', 'np.array([[2,', '2,', '2,', '2],', '[1,', '1,', '1,', '1],', '[2,', '2,', '2,', '2],', '[2,', '2,', '2,', '2],', '[1,', '2,', '1,', '1],', '[1,', '1,', '1,', '1],', '[2,', '2,', '2,', '2],', '[1,', '1,', '1,', '1],', '[1,', '2,', '2,', '2],', '[1,', '1,', '1,', '1]])'] | 930,161 |
sbjelogr/TransferBoost | conftest.py | leaves_values | leaves_values | Mocked leaf values in an xgboost model. | [
"Mocked",
"leaf",
"values",
"in",
"an",
"xgboost",
"model."
] | def leaves_values():
return np.array([[0.0, -0.3, -0.1426, -0.0072, -0.0051], [0.0, 0.0, 0.0, -0.1116, -0.0785], [0.0, -0.3, -0.1426, -0.0072, -0.0051], [0.0, -0.3, -0.1426, -0.0072, -0.0051], [0.0, 0.0, -0.1426, -0.1116, -0.0785], [0.0, 0.0, 0.0, -0.1116, -0.0785], [0.0, -0.3, -0.1426, -0.0072, -0.0051], [0.0, 0.0... | ['def', 'leaves_values():', 'return', 'np.array([[0.0,', '-0.3,', '-0.1426,', '-0.0072,', '-0.0051],', '[0.0,', '0.0,', '0.0,', '-0.1116,', '-0.0785],', '[0.0,', '-0.3,', '-0.1426,', '-0.0072,', '-0.0051],', '[0.0,', '-0.3,', '-0.1426,', '-0.0072,', '-0.0051],', '[0.0,', '0.0,', '-0.1426,', '-0.1116,', '-0.0785],', '[0... | 930,162 |
sbjelogr/TransferBoost | test_boost.py | rec_leaf_values | rec_leaf_values | Fixture to recompute the leaf values. | [
"Fixture",
"to",
"recompute",
"the",
"leaf",
"values."
] | def rec_leaf_values(X_y, leaves_indexes, model_params):
(X, y) = X_y
tb = TBoost(model_params=model_params, base_score=0.5)._fit(leaves_indexes, y)
remapped_leaves = tb._apply_leaf_map(leaves_indexes)
return remapped_leaves | ['def', 'rec_leaf_values(X_y,', 'leaves_indexes,', 'model_params):', '(X,', 'y)', '=', 'X_y', 'tb', '=', 'TBoost(model_params=model_params,', 'base_score=0.5)._fit(leaves_indexes,', 'y)', 'remapped_leaves', '=', 'tb._apply_leaf_map(leaves_indexes)', 'return', 'remapped_leaves'] | 930,164 |
sbjelogr/TransferBoost | test_boost.py | test_recompute_leaves | test_recompute_leaves | Test the recalculation of the leaves. | [
"Test",
"the",
"recalculation",
"of",
"the",
"leaves."
] | def test_recompute_leaves(rec_leaf_values, leaves_values):
np.testing.assert_array_almost_equal(rec_leaf_values, leaves_values, decimal=3) | ['def', 'test_recompute_leaves(rec_leaf_values,', 'leaves_values):', 'np.testing.assert_array_almost_equal(rec_leaf_values,', 'leaves_values,', 'decimal=3)'] | 930,165 |
sbjelogr/TransferBoost | test_docstrings.py | get_public_methods | get_public_methods | Helper test function, gets all public methods in a class. | [
"Helper",
"test",
"function,",
"gets",
"all",
"public",
"methods",
"in",
"a",
"class."
] | def get_public_methods(cls_ref):
return [m for m in dir(cls_ref) if m == '__init__' or not m.startswith('_')] | ['def', 'get_public_methods(cls_ref):', 'return', '[m', 'for', 'm', 'in', 'dir(cls_ref)', 'if', 'm', '==', "'__init__'", 'or', 'not', "m.startswith('_')]"] | 930,167 |
sbjelogr/TransferBoost | test_models.py | test_tboost_vs_xgb | test_tboost_vs_xgb | Test that using bins=1 puts everything into 1 bucket. | [
"Test",
"that",
"using",
"bins=1",
"puts",
"everything",
"into",
"1",
"bucket."
] | def test_tboost_vs_xgb(X_y) -> None:
(X, y) = X_y
model = xgb.XGBClassifier(max_depth=2, reg_lambda=0, num_leaves=4, n_estimators=4)
with pytest.raises(NotFittedError):
XGBTransferLearner(model)
model.fit(X, y)
probas = model.predict_proba(X)
tbooster = XGBTransferLearner(model)
tboo... | ['def', 'test_tboost_vs_xgb(X_y)', '->', 'None:', '(X,', 'y)', '=', 'X_y', 'model', '=', 'xgb.XGBClassifier(max_depth=2,', 'reg_lambda=0,', 'num_leaves=4,', 'n_estimators=4)', 'with', 'pytest.raises(NotFittedError):', 'XGBTransferLearner(model)', 'model.fit(X,', 'y)', 'probas', '=', 'model.predict_proba(X)', 'tbooster'... | 930,172 |
sbjelogr/TransferBoost | xgb.py | XGBTransferLearner.predict_proba | predict_proba | Predict the probabilities after transfer learning. | [
"Predict",
"the",
"probabilities",
"after",
"transfer",
"learning."
] | def predict_proba(self, X, tree_index=-1):
X_leaves_ixs = self.model.apply(X)
probas = self._predict_proba(X_leaves_ixs=X_leaves_ixs, tree_index=tree_index)
return probas | ['def', 'predict_proba(self,', 'X,', 'tree_index=-1):', 'X_leaves_ixs', '=', 'self.model.apply(X)', 'probas', '=', 'self._predict_proba(X_leaves_ixs=X_leaves_ixs,', 'tree_index=tree_index)', 'return', 'probas'] | 930,176 |
boschresearch/transfergpbo | experiment.py | generate_functions | generate_functions | Generate the source and target functions from the respective family. | [
"Generate",
"the",
"source",
"and",
"target",
"functions",
"from",
"the",
"respective",
"family."
] | def generate_functions(function_name: str, num_source_functions: int=1, params_source: List[Dict[str, float]]=None, params_target: Dict[str, float]=None) -> Tuple[Callable, List[Callable], ParameterSpace]:
function = getattr(benchmarks, function_name)
(fun_target, space) = function() if params_target is None el... | ['def', 'generate_functions(function_name:', 'str,', 'num_source_functions:', 'int=1,', 'params_source:', 'List[Dict[str,', 'float]]=None,', 'params_target:', 'Dict[str,', 'float]=None)', '->', 'Tuple[Callable,', 'List[Callable],', 'ParameterSpace]:', 'function', '=', 'getattr(benchmarks,', 'function_name)', '(fun_targ... | 930,212 |
boschresearch/transfergpbo | experiment.py | get_benchmark | get_benchmark | Create the benchmark object. | [
"Create",
"the",
"benchmark",
"object."
] | def get_benchmark(benchmark_name: str, num_source_points: List[int], output_noise: float=0.0, params_source: List[Dict[str, float]]=None, params_target: Dict[str, float]=None) -> Tuple[Callable, Dict[Hashable, TaskData], ParameterSpace]:
num_source_functions = len(num_source_points)
(f_target, f_source, space) ... | ['def', 'get_benchmark(benchmark_name:', 'str,', 'num_source_points:', 'List[int],', 'output_noise:', 'float=0.0,', 'params_source:', 'List[Dict[str,', 'float]]=None,', 'params_target:', 'Dict[str,', 'float]=None)', '->', 'Tuple[Callable,', 'Dict[Hashable,', 'TaskData],', 'ParameterSpace]:', 'num_source_functions', '='... | 930,213 |
boschresearch/transfergpbo | experiment.py | get_model | get_model | Create the model object. | [
"Create",
"the",
"model",
"object."
] | def get_model(model_name: str, space: ParameterSpace, source_data: Dict[Hashable, TaskData]) -> WrapperBase:
model_class = getattr(models, model_name)
if model_class == MHGP or model_class == SHGP or model_class == BHGP:
model = model_class(space.dimensionality)
else:
kernel = RBF(space.dime... | ['def', 'get_model(model_name:', 'str,', 'space:', 'ParameterSpace,', 'source_data:', 'Dict[Hashable,', 'TaskData])', '->', 'WrapperBase:', 'model_class', '=', 'getattr(models,', 'model_name)', 'if', 'model_class', '==', 'MHGP', 'or', 'model_class', '==', 'SHGP', 'or', 'model_class', '==', 'BHGP:', 'model', '=', 'model... | 930,214 |
boschresearch/transfergpbo | experiment.py | run_experiment | run_experiment | The actual experiment code. | [
"The",
"actual",
"experiment",
"code."
] | def run_experiment(parameters: dict) -> List[float]:
num_source_points = parameters['benchmark']['num_source_points']
technique = parameters['technique']
benchmark_name = parameters['benchmark']['name']
num_steps = parameters['benchmark']['num_steps']
output_noise = parameters['output_noise']
pa... | ['def', 'run_experiment(parameters:', 'dict)', '->', 'List[float]:', 'num_source_points', '=', "parameters['benchmark']['num_source_points']", 'technique', '=', "parameters['technique']", 'benchmark_name', '=', "parameters['benchmark']['name']", 'num_steps', '=', "parameters['benchmark']['num_steps']", 'output_noise', ... | 930,215 |
boschresearch/transfergpbo | gpbo.py | GPBO.kernel | kernel | Return GPy kernel in the normalized space. | [
"Return",
"GPy",
"kernel",
"in",
"the",
"normalized",
"space."
] | def kernel(self):
return self._kernel | ['def', 'kernel(self):', 'return', 'self._kernel'] | 930,220 |
boschresearch/transfergpbo | mhgp.py | MHGP.meta_fit | meta_fit | Train the source GPs on the given source data. | [
"Train",
"the",
"source",
"GPs",
"on",
"the",
"given",
"source",
"data."
] | def meta_fit(self, source_datasets: Dict[Hashable, TaskData], optimize: Union[bool, Sequence[bool]]=True):
assert isinstance(optimize, bool) or isinstance(optimize, list)
if isinstance(optimize, list):
assert len(source_datasets) == len(optimize)
optimize_flag = copy.copy(optimize)
if isinstance... | ['def', 'meta_fit(self,', 'source_datasets:', 'Dict[Hashable,', 'TaskData],', 'optimize:', 'Union[bool,', 'Sequence[bool]]=True):', 'assert', 'isinstance(optimize,', 'bool)', 'or', 'isinstance(optimize,', 'list)', 'if', 'isinstance(optimize,', 'list):', 'assert', 'len(source_datasets)', '==', 'len(optimize)', 'optimize... | 930,229 |
boschresearch/transfergpbo | mhgp.py | MHGP.predict_posterior_covariance | predict_posterior_covariance | Posterior covariance between two inputs. | [
"Posterior",
"covariance",
"between",
"two",
"inputs."
] | def predict_posterior_covariance(self, x1: InputData, x2: InputData) -> np.ndarray:
return self.target_gp.predict_posterior_covariance(x1, x2) | ['def', 'predict_posterior_covariance(self,', 'x1:', 'InputData,', 'x2:', 'InputData)', '->', 'np.ndarray:', 'return', 'self.target_gp.predict_posterior_covariance(x1,', 'x2)'] | 930,231 |
cjerry1243/TransferLearning-CLVC | utils.py | load_filepaths | load_filepaths | Read in a list of file paths. | [
"Read",
"in",
"a",
"list",
"of",
"file",
"paths."
] | def load_filepaths(filename):
with open(filename) as f:
filepaths = [line.strip() for line in f]
return filepaths | ['def', 'load_filepaths(filename):', 'with', 'open(filename)', 'as', 'f:', 'filepaths', '=', '[line.strip()', 'for', 'line', 'in', 'f]', 'return', 'filepaths'] | 930,259 |
cjerry1243/TransferLearning-CLVC | utils.py | notch_filtering | notch_filtering | Apply a notch (band-stop) filter to the audio signal. | [
"Apply",
"a",
"notch",
"(band-stop)",
"filter",
"to",
"the",
"audio",
"signal."
] | def notch_filtering(wav, fs, w0, Q):
(b, a) = signal.iirnotch(2 * w0 / fs, Q)
wav = signal.lfilter(b, a, wav)
return wav | ['def', 'notch_filtering(wav,', 'fs,', 'w0,', 'Q):', '(b,', 'a)', '=', 'signal.iirnotch(2', '*', 'w0', '/', 'fs,', 'Q)', 'wav', '=', 'signal.lfilter(b,', 'a,', 'wav)', 'return', 'wav'] | 930,260 |
cjerry1243/TransferLearning-CLVC | functional.py | spectrogram | spectrogram | spectrogram(waveform, pad, window, n_fft, hop_length, win_length, power, normalized) Create a spectrogram from a raw audio signal. | [
"spectrogram(waveform,",
"pad,",
"window,",
"n_fft,",
"hop_length,",
"win_length,",
"power,",
"normalized)",
"Create",
"a",
"spectrogram",
"from",
"a",
"raw",
"audio",
"signal."
] | def spectrogram(waveform, pad, window, n_fft, hop_length, win_length, power, normalized, center):
assert waveform.dim() == 2
if pad > 0:
waveform = torch.nn.functional.pad(waveform, (pad, pad), 'constant')
spec_f = _stft(waveform, n_fft, hop_length, win_length, window, center, 'reflect', False, True... | ['def', 'spectrogram(waveform,', 'pad,', 'window,', 'n_fft,', 'hop_length,', 'win_length,', 'power,', 'normalized,', 'center):', 'assert', 'waveform.dim()', '==', '2', 'if', 'pad', '>', '0:', 'waveform', '=', 'torch.nn.functional.pad(waveform,', '(pad,', 'pad),', "'constant')", 'spec_f', '=', '_stft(waveform,', 'n_fft,... | 930,261 |
cjerry1243/TransferLearning-CLVC | functional.py | angle | angle | Compute the angle of complex tensor input. | [
"Compute",
"the",
"angle",
"of",
"complex",
"tensor",
"input."
] | def angle(complex_tensor):
return torch.atan2(complex_tensor[..., 1], complex_tensor[..., 0]) | ['def', 'angle(complex_tensor):', 'return', 'torch.atan2(complex_tensor[...,', '1],', 'complex_tensor[...,', '0])'] | 930,268 |
cjerry1243/TransferLearning-CLVC | functional.py | magphase | magphase | Separate a complex-valued spectrogram with shape `(*, 2)` into its magnitude and phase. | [
"Separate",
"a",
"complex-valued",
"spectrogram",
"with",
"shape",
"`(*,",
"2)`",
"into",
"its",
"magnitude",
"and",
"phase."
] | def magphase(complex_tensor, power=1.0):
mag = complex_norm(complex_tensor, power)
phase = angle(complex_tensor)
return (mag, phase) | ['def', 'magphase(complex_tensor,', 'power=1.0):', 'mag', '=', 'complex_norm(complex_tensor,', 'power)', 'phase', '=', 'angle(complex_tensor)', 'return', '(mag,', 'phase)'] | 930,269 |
cjerry1243/TransferLearning-CLVC | functional.py | phase_vocoder | phase_vocoder | Given a STFT tensor, speed up in time without modifying pitch by a factor of ``rate``. | [
"Given",
"a",
"STFT",
"tensor,",
"speed",
"up",
"in",
"time",
"without",
"modifying",
"pitch",
"by",
"a",
"factor",
"of",
"``rate``."
] | def phase_vocoder(complex_specgrams, rate, phase_advance):
time_steps = torch.arange(0, complex_specgrams.size(-2), rate, device=complex_specgrams.device, dtype=complex_specgrams.dtype)
alphas = time_steps % 1.0
phase_0 = angle(complex_specgrams[:, :, :1])
complex_specgrams = torch.nn.functional.pad(com... | ['def', 'phase_vocoder(complex_specgrams,', 'rate,', 'phase_advance):', 'time_steps', '=', 'torch.arange(0,', 'complex_specgrams.size(-2),', 'rate,', 'device=complex_specgrams.device,', 'dtype=complex_specgrams.dtype)', 'alphas', '=', 'time_steps', '%', '1.0', 'phase_0', '=', 'angle(complex_specgrams[:,', ':,', ':1])',... | 930,270 |
cjerry1243/TransferLearning-CLVC | functional.py | lfilter | lfilter | Performs an IIR filter by evaluating difference equation. | [
"Performs",
"an",
"IIR",
"filter",
"by",
"evaluating",
"difference",
"equation."
] | def lfilter(waveform, a_coeffs, b_coeffs):
assert a_coeffs.size(0) == b_coeffs.size(0)
assert len(waveform.size()) == 2
assert waveform.device == a_coeffs.device
assert b_coeffs.device == a_coeffs.device
device = waveform.device
dtype = waveform.dtype
(n_channels, n_frames) = waveform.size()... | ['def', 'lfilter(waveform,', 'a_coeffs,', 'b_coeffs):', 'assert', 'a_coeffs.size(0)', '==', 'b_coeffs.size(0)', 'assert', 'len(waveform.size())', '==', '2', 'assert', 'waveform.device', '==', 'a_coeffs.device', 'assert', 'b_coeffs.device', '==', 'a_coeffs.device', 'device', '=', 'waveform.device', 'dtype', '=', 'wavefo... | 930,271 |
cjerry1243/TransferLearning-CLVC | kaldi_io.py | read_vec_int_ark | read_vec_int_ark | Create generator of (key,vector<int>) tuples, which reads from the ark file/stream. | [
"Create",
"generator",
"of",
"(key,vector<int>)",
"tuples,",
"which",
"reads",
"from",
"the",
"ark",
"file/stream."
] | def read_vec_int_ark(file_or_fd):
return _convert_method_output_to_tensor(file_or_fd, kaldi_io.read_vec_int_ark, convert_contiguous=True) | ['def', 'read_vec_int_ark(file_or_fd):', 'return', '_convert_method_output_to_tensor(file_or_fd,', 'kaldi_io.read_vec_int_ark,', 'convert_contiguous=True)'] | 930,278 |
cjerry1243/TransferLearning-CLVC | kaldi_io.py | read_mat_ark | read_mat_ark | Create generator of (key,matrix<float32/float64>) tuples, which reads from the ark file/stream. | [
"Create",
"generator",
"of",
"(key,matrix<float32/float64>)",
"tuples,",
"which",
"reads",
"from",
"the",
"ark",
"file/stream."
] | def read_mat_ark(file_or_fd):
return _convert_method_output_to_tensor(file_or_fd, kaldi_io.read_mat_ark) | ['def', 'read_mat_ark(file_or_fd):', 'return', '_convert_method_output_to_tensor(file_or_fd,', 'kaldi_io.read_mat_ark)'] | 930,282 |
cjerry1243/TransferLearning-CLVC | sox_effects.py | SoxEffect | SoxEffect | Create an object for passing sox effect information between python and c++ Returns: SoxEffect: An object with the following attributes: ename (str) which is the name of effect, and eopts (List[str]) which is a list of effect options. | [
"Create",
"an",
"object",
"for",
"passing",
"sox",
"effect",
"information",
"between",
"python",
"and",
"c++",
"Returns:",
"SoxEffect:",
"An",
"object",
"with",
"the",
"following",
"attributes:",
"ename",
"(str)",
"which",
"is",
"the",
"name",
"of",
"effect,",
... | def SoxEffect():
return _torch_sox.SoxEffect() | ['def', 'SoxEffect():', 'return', '_torch_sox.SoxEffect()'] | 930,284 |
cjerry1243/TransferLearning-CLVC | sox_effects.py | SoxEffectsChain.append_effect_to_chain | append_effect_to_chain | Append effect to a sox effects chain. | [
"Append",
"effect",
"to",
"a",
"sox",
"effects",
"chain."
] | def append_effect_to_chain(self, ename, eargs=None):
e = SoxEffect()
ename = self._check_effect(ename)
if eargs is None or eargs == []:
eargs = ['']
elif not isinstance(eargs, list):
eargs = [eargs]
eargs = self._flatten(eargs)
if len(eargs) > self.MAX_EFFECT_OPTS:
raise ... | ['def', 'append_effect_to_chain(self,', 'ename,', 'eargs=None):', 'e', '=', 'SoxEffect()', 'ename', '=', 'self._check_effect(ename)', 'if', 'eargs', 'is', 'None', 'or', 'eargs', '==', '[]:', 'eargs', '=', "['']", 'elif', 'not', 'isinstance(eargs,', 'list):', 'eargs', '=', '[eargs]', 'eargs', '=', 'self._flatten(eargs)'... | 930,285 |
cjerry1243/TransferLearning-CLVC | vctk.py | load_txts | load_txts | Create a dictionary with all the text of the audio transcriptions. | [
"Create",
"a",
"dictionary",
"with",
"all",
"the",
"text",
"of",
"the",
"audio",
"transcriptions."
] | def load_txts(dir):
utterences = dict()
dir = os.path.expanduser(dir)
for target in sorted(os.listdir(dir)):
d = os.path.join(dir, target)
if not os.path.isdir(d):
continue
for (root, _, fnames) in sorted(os.walk(d)):
for fname in fnames:
if fn... | ['def', 'load_txts(dir):', 'utterences', '=', 'dict()', 'dir', '=', 'os.path.expanduser(dir)', 'for', 'target', 'in', 'sorted(os.listdir(dir)):', 'd', '=', 'os.path.join(dir,', 'target)', 'if', 'not', 'os.path.isdir(d):', 'continue', 'for', '(root,', '_,', 'fnames)', 'in', 'sorted(os.walk(d)):', 'for', 'fname', 'in', '... | 930,294 |
cjerry1243/TransferLearning-CLVC | vctk.py | VCTK.download | download | Download the VCTK data if it doesn't exist in processed_folder already. | [
"Download",
"the",
"VCTK",
"data",
"if",
"it",
"doesn't",
"exist",
"in",
"processed_folder",
"already."
] | def download(self):
from six.moves import urllib
import tarfile
if self._check_exists():
return
raw_abs_dir = os.path.join(self.root, self.raw_folder)
processed_abs_dir = os.path.join(self.root, self.processed_folder)
dset_abs_path = os.path.join(self.root, self.raw_folder, self.dset_pat... | ['def', 'download(self):', 'from', 'six.moves', 'import', 'urllib', 'import', 'tarfile', 'if', 'self._check_exists():', 'return', 'raw_abs_dir', '=', 'os.path.join(self.root,', 'self.raw_folder)', 'processed_abs_dir', '=', 'os.path.join(self.root,', 'self.processed_folder)', 'dset_abs_path', '=', 'os.path.join(self.roo... | 930,295 |
cjerry1243/TransferLearning-CLVC | yesno.py | YESNO.download | download | Download the yesno data if it doesn't exist in processed_folder already. | [
"Download",
"the",
"yesno",
"data",
"if",
"it",
"doesn't",
"exist",
"in",
"processed_folder",
"already."
] | def download(self):
from six.moves import urllib
import tarfile
if self._check_exists():
return
raw_abs_dir = os.path.join(self.root, self.raw_folder)
processed_abs_dir = os.path.join(self.root, self.processed_folder)
dset_abs_path = os.path.join(self.root, self.raw_folder, self.dset_pat... | ['def', 'download(self):', 'from', 'six.moves', 'import', 'urllib', 'import', 'tarfile', 'if', 'self._check_exists():', 'return', 'raw_abs_dir', '=', 'os.path.join(self.root,', 'self.raw_folder)', 'processed_abs_dir', '=', 'os.path.join(self.root,', 'self.processed_folder)', 'dset_abs_path', '=', 'os.path.join(self.roo... | 930,296 |
CPTR-ReSeqTB/UVP | snp.py | Snp.cleanUp | cleanUp | Clean up the temporary files, and move them to a proper folder. | [
"Clean",
"up",
"the",
"temporary",
"files,",
"and",
"move",
"them",
"to",
"a",
"proper",
"folder."
] | def cleanUp(self):
i = datetime.now()
self.__CallCommand('rm', ['rm', '-r', self.outdir])
self.__CallCommand('rm', ['rm', self.fOut + '/' + self.name + '.mpileup'])
self.__CallCommand('rm', ['rm', self.fOut + '/' + self.name + '_annotation.txt'])
self.__CallCommand('rm', ['rm', self.fOut + '/' + sel... | ['def', 'cleanUp(self):', 'i', '=', 'datetime.now()', "self.__CallCommand('rm',", "['rm',", "'-r',", 'self.outdir])', "self.__CallCommand('rm',", "['rm',", 'self.fOut', '+', "'/'", '+', 'self.name', '+', "'.mpileup'])", "self.__CallCommand('rm',", "['rm',", 'self.fOut', '+', "'/'", '+', 'self.name', '+', "'_annotation.... | 930,472 |
dvlab-research/UVTR | uvtr.py | UVTR.init_weights | init_weights | Initialize weights of the depth head. | [
"Initialize",
"weights",
"of",
"the",
"depth",
"head."
] | def init_weights(self):
if not self.with_img_backbone:
return
if self.pretrained_pts is not None:
ckpt_load = torch.load(self.pretrained_pts, map_location='cuda:{}'.format(torch.cuda.current_device()))['state_dict']
print('Loaded pretrained model from: {}'.format(self.pretrained_pts))
... | ['def', 'init_weights(self):', 'if', 'not', 'self.with_img_backbone:', 'return', 'if', 'self.pretrained_pts', 'is', 'not', 'None:', 'ckpt_load', '=', 'torch.load(self.pretrained_pts,', "map_location='cuda:{}'.format(torch.cuda.current_device()))['state_dict']", "print('Loaded", 'pretrained', 'model', 'from:', "{}'.form... | 930,511 |
dvlab-research/UVTR | uvtr.py | UVTR.aug_test_pts | aug_test_pts | Test function of point cloud branch with augmentaiton. | [
"Test",
"function",
"of",
"point",
"cloud",
"branch",
"with",
"augmentaiton."
] | def aug_test_pts(self, pts_feats, img_feats, img_depths, img_metas, rescale=False):
aug_bboxes = []
for (_idx, img_meta) in enumerate(img_metas):
outs = self.pts_bbox_head(pts_feats[_idx], img_feats[_idx], img_meta, img_depths[_idx])
bbox_list = self.pts_bbox_head.get_bboxes(outs, img_meta, resc... | ['def', 'aug_test_pts(self,', 'pts_feats,', 'img_feats,', 'img_depths,', 'img_metas,', 'rescale=False):', 'aug_bboxes', '=', '[]', 'for', '(_idx,', 'img_meta)', 'in', 'enumerate(img_metas):', 'outs', '=', 'self.pts_bbox_head(pts_feats[_idx],', 'img_feats[_idx],', 'img_meta,', 'img_depths[_idx])', 'bbox_list', '=', 'sel... | 930,522 |
dvlab-research/UVTR | uvtr_kd_cs.py | UVTRKDCS.with_depth_head | with_depth_head | bool: Whether the detector has a depth head. | [
"bool:",
"Whether",
"the",
"detector",
"has",
"a",
"depth",
"head."
] | def with_depth_head(self):
return hasattr(self, 'depth_head') and self.depth_head is not None | ['def', 'with_depth_head(self):', 'return', 'hasattr(self,', "'depth_head')", 'and', 'self.depth_head', 'is', 'not', 'None'] | 930,524 |
dvlab-research/UVTR | uni3d_detr.py | UniTransformerDecoder.forward | forward | Forward function for `UniTransformerDecoder`. | [
"Forward",
"function",
"for",
"`UniTransformerDecoder`."
] | def forward(self, query, *args, reference_points=None, reg_branches=None, **kwargs):
output = query
intermediate = []
intermediate_reference_points = []
for (lid, layer) in enumerate(self.layers):
output = layer(output, *args, reference_points=reference_points, **kwargs)
output = output.... | ['def', 'forward(self,', 'query,', '*args,', 'reference_points=None,', 'reg_branches=None,', '**kwargs):', 'output', '=', 'query', 'intermediate', '=', '[]', 'intermediate_reference_points', '=', '[]', 'for', '(lid,', 'layer)', 'in', 'enumerate(self.layers):', 'output', '=', 'layer(output,', '*args,', 'reference_points... | 930,560 |
dvlab-research/UVTR | uni3d_detr.py | UniCrossAtten.forward | forward | Forward Function of UniCrossAtten. | [
"Forward",
"Function",
"of",
"UniCrossAtten."
] | def forward(self, query, key, value, residual=None, query_pos=None, key_padding_mask=None, reference_points=None, spatial_shapes=None, level_start_index=None, **kwargs):
if key is None:
key = query
if value is None:
value = key
if residual is None:
inp_residual = query
if query_p... | ['def', 'forward(self,', 'query,', 'key,', 'value,', 'residual=None,', 'query_pos=None,', 'key_padding_mask=None,', 'reference_points=None,', 'spatial_shapes=None,', 'level_start_index=None,', '**kwargs):', 'if', 'key', 'is', 'None:', 'key', '=', 'query', 'if', 'value', 'is', 'None:', 'value', '=', 'key', 'if', 'residu... | 930,562 |
dvlab-research/UVTR | uni3d_viewtrans.py | Uni3DViewTrans.forward | forward | Forward function for `Uni3DViewTrans`. | [
"Forward",
"function",
"for",
"`Uni3DViewTrans`."
] | def forward(self, mlvl_feats, **kwargs):
if self.num_sweeps > 1:
(num_sweep, num_cam) = kwargs['img_metas'][0]['sweeps_ids'].shape
else:
num_sweep = self.num_sweeps
num_cam = self.num_cams
kwargs['num_sweep'] = num_sweep
kwargs['num_cam'] = num_cam
kwargs['batch_size'] = len(... | ['def', 'forward(self,', 'mlvl_feats,', '**kwargs):', 'if', 'self.num_sweeps', '>', '1:', '(num_sweep,', 'num_cam)', '=', "kwargs['img_metas'][0]['sweeps_ids'].shape", 'else:', 'num_sweep', '=', 'self.num_sweeps', 'num_cam', '=', 'self.num_cams', "kwargs['num_sweep']", '=', 'num_sweep', "kwargs['num_cam']", '=', 'num_c... | 930,564 |
tigvarts/vaeac | mask_generators.py | RandomPattern.regenerate_cache | regenerate_cache | Resamples the big matrix and resets the counter of the total number of elements in the returned masks. | [
"Resamples",
"the",
"big",
"matrix",
"and",
"resets",
"the",
"counter",
"of",
"the",
"total",
"number",
"of",
"elements",
"in",
"the",
"returned",
"masks."
] | def regenerate_cache(self):
low_size = int(self.resolution * self.max_size)
low_pattern = self.rng.uniform(0, 1, size=(low_size, low_size)) * 255
low_pattern = torch.from_numpy(low_pattern.astype('float32'))
pattern = transforms.Compose([transforms.ToPILImage(), transforms.Resize(self.max_size, Image.BI... | ['def', 'regenerate_cache(self):', 'low_size', '=', 'int(self.resolution', '*', 'self.max_size)', 'low_pattern', '=', 'self.rng.uniform(0,', '1,', 'size=(low_size,', 'low_size))', '*', '255', 'low_pattern', '=', "torch.from_numpy(low_pattern.astype('float32'))", 'pattern', '=', 'transforms.Compose([transforms.ToPILImag... | 930,768 |
tigvarts/vaeac | VAEAC.py | VAEAC.make_observed | make_observed | Copy batch of objects and zero unobserved features. | [
"Copy",
"batch",
"of",
"objects",
"and",
"zero",
"unobserved",
"features."
] | def make_observed(self, batch, mask):
observed = torch.tensor(batch)
observed[mask.byte()] = 0
return observed | ['def', 'make_observed(self,', 'batch,', 'mask):', 'observed', '=', 'torch.tensor(batch)', 'observed[mask.byte()]', '=', '0', 'return', 'observed'] | 930,773 |
tigvarts/vaeac | VAEAC.py | VAEAC.batch_vlb | batch_vlb | Compute differentiable lower bound for the given batch of objects and mask. | [
"Compute",
"differentiable",
"lower",
"bound",
"for",
"the",
"given",
"batch",
"of",
"objects",
"and",
"mask."
] | def batch_vlb(self, batch, mask):
(proposal, prior) = self.make_latent_distributions(batch, mask)
prior_regularization = self.prior_regularization(prior)
latent = proposal.rsample()
rec_params = self.generative_network(latent)
rec_loss = self.rec_log_prob(batch, rec_params, mask)
kl = kl_diverge... | ['def', 'batch_vlb(self,', 'batch,', 'mask):', '(proposal,', 'prior)', '=', 'self.make_latent_distributions(batch,', 'mask)', 'prior_regularization', '=', 'self.prior_regularization(prior)', 'latent', '=', 'proposal.rsample()', 'rec_params', '=', 'self.generative_network(latent)', 'rec_loss', '=', 'self.rec_log_prob(ba... | 930,776 |
ajboyd2/vae_mpp | train.py | set_random_seed | set_random_seed | Set random seed for reproducibility. | [
"Set",
"random",
"seed",
"for",
"reproducibility."
] | def set_random_seed(args):
seed = args.seed
if seed is not None and seed > 0:
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed) | ['def', 'set_random_seed(args):', 'seed', '=', 'args.seed', 'if', 'seed', 'is', 'not', 'None', 'and', 'seed', '>', '0:', 'random.seed(seed)', 'np.random.seed(seed)', 'torch.manual_seed(seed)'] | 930,810 |
ajboyd2/vae_mpp | utils.py | kl_div | kl_div | Computes closed-form KL if available, else computes a MC estimate. | [
"Computes",
"closed-form",
"KL",
"if",
"available,",
"else",
"computes",
"a",
"MC",
"estimate."
] | def kl_div(d1, d2, K=100):
if (type(d1), type(d2)) in torch.distributions.kl._KL_REGISTRY:
return torch.distributions.kl_divergence(d1, d2)
else:
samples = d1.rsample(torch.Size([K]))
return (d1.log_prob(samples) - d2.log_prob(samples)).mean(0) | ['def', 'kl_div(d1,', 'd2,', 'K=100):', 'if', '(type(d1),', 'type(d2))', 'in', 'torch.distributions.kl._KL_REGISTRY:', 'return', 'torch.distributions.kl_divergence(d1,', 'd2)', 'else:', 'samples', '=', 'd1.rsample(torch.Size([K]))', 'return', '(d1.log_prob(samples)', '-', 'd2.log_prob(samples)).mean(0)'] | 930,811 |
ajboyd2/vae_mpp | hawkes.py | HawkesModel.get_states | get_states | Get the hidden states that can be used to extract intensity values from. | [
"Get",
"the",
"hidden",
"states",
"that",
"can",
"be",
"used",
"to",
"extract",
"intensity",
"values",
"from."
] | def get_states(self, tgt_marks, tgt_timestamps, latent_state):
return {'state_values': tgt_marks, 'state_times': tgt_timestamps} | ['def', 'get_states(self,', 'tgt_marks,', 'tgt_timestamps,', 'latent_state):', 'return', "{'state_values':", 'tgt_marks,', "'state_times':", 'tgt_timestamps}'] | 930,812 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.