id int32 0 252k | repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 75 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
27,200 | Microsoft/nni | tools/nni_cmd/tensorboard_utils.py | start_tensorboard_process | def start_tensorboard_process(args, nni_config, path_list, temp_nni_path):
'''call cmds to start tensorboard process in local machine'''
if detect_port(args.port):
print_error('Port %s is used by another process, please reset port!' % str(args.port))
exit(1)
stdout_file = open(os.path.j... | python | def start_tensorboard_process(args, nni_config, path_list, temp_nni_path):
'''call cmds to start tensorboard process in local machine'''
if detect_port(args.port):
print_error('Port %s is used by another process, please reset port!' % str(args.port))
exit(1)
stdout_file = open(os.path.j... | [
"def",
"start_tensorboard_process",
"(",
"args",
",",
"nni_config",
",",
"path_list",
",",
"temp_nni_path",
")",
":",
"if",
"detect_port",
"(",
"args",
".",
"port",
")",
":",
"print_error",
"(",
"'Port %s is used by another process, please reset port!'",
"%",
"str",
... | call cmds to start tensorboard process in local machine | [
"call",
"cmds",
"to",
"start",
"tensorboard",
"process",
"in",
"local",
"machine"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/tools/nni_cmd/tensorboard_utils.py#L92-L109 |
27,201 | Microsoft/nni | src/sdk/pynni/nni/metis_tuner/Regression_GMM/Selection.py | _ratio_scores | def _ratio_scores(parameters_value, clusteringmodel_gmm_good, clusteringmodel_gmm_bad):
'''
The ratio is smaller the better
'''
ratio = clusteringmodel_gmm_good.score([parameters_value]) / clusteringmodel_gmm_bad.score([parameters_value])
sigma = 0
return ratio, sigma | python | def _ratio_scores(parameters_value, clusteringmodel_gmm_good, clusteringmodel_gmm_bad):
'''
The ratio is smaller the better
'''
ratio = clusteringmodel_gmm_good.score([parameters_value]) / clusteringmodel_gmm_bad.score([parameters_value])
sigma = 0
return ratio, sigma | [
"def",
"_ratio_scores",
"(",
"parameters_value",
",",
"clusteringmodel_gmm_good",
",",
"clusteringmodel_gmm_bad",
")",
":",
"ratio",
"=",
"clusteringmodel_gmm_good",
".",
"score",
"(",
"[",
"parameters_value",
"]",
")",
"/",
"clusteringmodel_gmm_bad",
".",
"score",
"(... | The ratio is smaller the better | [
"The",
"ratio",
"is",
"smaller",
"the",
"better"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/metis_tuner/Regression_GMM/Selection.py#L37-L43 |
27,202 | Microsoft/nni | src/sdk/pynni/nni/metis_tuner/Regression_GMM/Selection.py | selection | def selection(x_bounds,
x_types,
clusteringmodel_gmm_good,
clusteringmodel_gmm_bad,
minimize_starting_points,
minimize_constraints_fun=None):
'''
Select the lowest mu value
'''
results = lib_acquisition_function.next_hyperparameter_lo... | python | def selection(x_bounds,
x_types,
clusteringmodel_gmm_good,
clusteringmodel_gmm_bad,
minimize_starting_points,
minimize_constraints_fun=None):
'''
Select the lowest mu value
'''
results = lib_acquisition_function.next_hyperparameter_lo... | [
"def",
"selection",
"(",
"x_bounds",
",",
"x_types",
",",
"clusteringmodel_gmm_good",
",",
"clusteringmodel_gmm_bad",
",",
"minimize_starting_points",
",",
"minimize_constraints_fun",
"=",
"None",
")",
":",
"results",
"=",
"lib_acquisition_function",
".",
"next_hyperparam... | Select the lowest mu value | [
"Select",
"the",
"lowest",
"mu",
"value"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/metis_tuner/Regression_GMM/Selection.py#L63-L77 |
27,203 | Microsoft/nni | src/sdk/pynni/nni/metis_tuner/Regression_GMM/Selection.py | _minimize_constraints_fun_summation | def _minimize_constraints_fun_summation(x):
'''
Minimize constraints fun summation
'''
summation = sum([x[i] for i in CONSTRAINT_PARAMS_IDX])
return CONSTRAINT_UPPERBOUND >= summation >= CONSTRAINT_LOWERBOUND | python | def _minimize_constraints_fun_summation(x):
'''
Minimize constraints fun summation
'''
summation = sum([x[i] for i in CONSTRAINT_PARAMS_IDX])
return CONSTRAINT_UPPERBOUND >= summation >= CONSTRAINT_LOWERBOUND | [
"def",
"_minimize_constraints_fun_summation",
"(",
"x",
")",
":",
"summation",
"=",
"sum",
"(",
"[",
"x",
"[",
"i",
"]",
"for",
"i",
"in",
"CONSTRAINT_PARAMS_IDX",
"]",
")",
"return",
"CONSTRAINT_UPPERBOUND",
">=",
"summation",
">=",
"CONSTRAINT_LOWERBOUND"
] | Minimize constraints fun summation | [
"Minimize",
"constraints",
"fun",
"summation"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/metis_tuner/Regression_GMM/Selection.py#L99-L104 |
27,204 | Microsoft/nni | examples/trials/sklearn/classification/main.py | load_data | def load_data():
'''Load dataset, use 20newsgroups dataset'''
digits = load_digits()
X_train, X_test, y_train, y_test = train_test_split(digits.data, digits.target, random_state=99, test_size=0.25)
ss = StandardScaler()
X_train = ss.fit_transform(X_train)
X_test = ss.transform(X_test)
retu... | python | def load_data():
'''Load dataset, use 20newsgroups dataset'''
digits = load_digits()
X_train, X_test, y_train, y_test = train_test_split(digits.data, digits.target, random_state=99, test_size=0.25)
ss = StandardScaler()
X_train = ss.fit_transform(X_train)
X_test = ss.transform(X_test)
retu... | [
"def",
"load_data",
"(",
")",
":",
"digits",
"=",
"load_digits",
"(",
")",
"X_train",
",",
"X_test",
",",
"y_train",
",",
"y_test",
"=",
"train_test_split",
"(",
"digits",
".",
"data",
",",
"digits",
".",
"target",
",",
"random_state",
"=",
"99",
",",
... | Load dataset, use 20newsgroups dataset | [
"Load",
"dataset",
"use",
"20newsgroups",
"dataset"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/examples/trials/sklearn/classification/main.py#L29-L38 |
27,205 | Microsoft/nni | src/sdk/pynni/nni/bohb_advisor/bohb_advisor.py | Bracket.get_hyperparameter_configurations | def get_hyperparameter_configurations(self, num, r, config_generator):
"""generate num hyperparameter configurations from search space using Bayesian optimization
Parameters
----------
num: int
the number of hyperparameter configurations
Returns
-------
... | python | def get_hyperparameter_configurations(self, num, r, config_generator):
"""generate num hyperparameter configurations from search space using Bayesian optimization
Parameters
----------
num: int
the number of hyperparameter configurations
Returns
-------
... | [
"def",
"get_hyperparameter_configurations",
"(",
"self",
",",
"num",
",",
"r",
",",
"config_generator",
")",
":",
"global",
"_KEY",
"assert",
"self",
".",
"i",
"==",
"0",
"hyperparameter_configs",
"=",
"dict",
"(",
")",
"for",
"_",
"in",
"range",
"(",
"num... | generate num hyperparameter configurations from search space using Bayesian optimization
Parameters
----------
num: int
the number of hyperparameter configurations
Returns
-------
list
a list of hyperparameter configurations. Format: [[key1, valu... | [
"generate",
"num",
"hyperparameter",
"configurations",
"from",
"search",
"space",
"using",
"Bayesian",
"optimization"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/bohb_advisor/bohb_advisor.py#L215-L237 |
27,206 | Microsoft/nni | src/sdk/pynni/nni/bohb_advisor/bohb_advisor.py | BOHB.handle_initialize | def handle_initialize(self, data):
"""Initialize Tuner, including creating Bayesian optimization-based parametric models
and search space formations
Parameters
----------
data: search space
search space of this experiment
Raises
------
Value... | python | def handle_initialize(self, data):
"""Initialize Tuner, including creating Bayesian optimization-based parametric models
and search space formations
Parameters
----------
data: search space
search space of this experiment
Raises
------
Value... | [
"def",
"handle_initialize",
"(",
"self",
",",
"data",
")",
":",
"logger",
".",
"info",
"(",
"'start to handle_initialize'",
")",
"# convert search space jason to ConfigSpace",
"self",
".",
"handle_update_search_space",
"(",
"data",
")",
"# generate BOHB config_generator usi... | Initialize Tuner, including creating Bayesian optimization-based parametric models
and search space formations
Parameters
----------
data: search space
search space of this experiment
Raises
------
ValueError
Error: Search space is None | [
"Initialize",
"Tuner",
"including",
"creating",
"Bayesian",
"optimization",
"-",
"based",
"parametric",
"models",
"and",
"search",
"space",
"formations"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/bohb_advisor/bohb_advisor.py#L344-L375 |
27,207 | Microsoft/nni | src/sdk/pynni/nni/bohb_advisor/bohb_advisor.py | BOHB.generate_new_bracket | def generate_new_bracket(self):
"""generate a new bracket"""
logger.debug(
'start to create a new SuccessiveHalving iteration, self.curr_s=%d', self.curr_s)
if self.curr_s < 0:
logger.info("s < 0, Finish this round of Hyperband in BOHB. Generate new round")
se... | python | def generate_new_bracket(self):
"""generate a new bracket"""
logger.debug(
'start to create a new SuccessiveHalving iteration, self.curr_s=%d', self.curr_s)
if self.curr_s < 0:
logger.info("s < 0, Finish this round of Hyperband in BOHB. Generate new round")
se... | [
"def",
"generate_new_bracket",
"(",
"self",
")",
":",
"logger",
".",
"debug",
"(",
"'start to create a new SuccessiveHalving iteration, self.curr_s=%d'",
",",
"self",
".",
"curr_s",
")",
"if",
"self",
".",
"curr_s",
"<",
"0",
":",
"logger",
".",
"info",
"(",
"\"... | generate a new bracket | [
"generate",
"a",
"new",
"bracket"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/bohb_advisor/bohb_advisor.py#L377-L392 |
27,208 | Microsoft/nni | src/sdk/pynni/nni/bohb_advisor/bohb_advisor.py | BOHB.handle_request_trial_jobs | def handle_request_trial_jobs(self, data):
"""recerive the number of request and generate trials
Parameters
----------
data: int
number of trial jobs that nni manager ask to generate
"""
# Receive new request
self.credit += data
for _ in rang... | python | def handle_request_trial_jobs(self, data):
"""recerive the number of request and generate trials
Parameters
----------
data: int
number of trial jobs that nni manager ask to generate
"""
# Receive new request
self.credit += data
for _ in rang... | [
"def",
"handle_request_trial_jobs",
"(",
"self",
",",
"data",
")",
":",
"# Receive new request",
"self",
".",
"credit",
"+=",
"data",
"for",
"_",
"in",
"range",
"(",
"self",
".",
"credit",
")",
":",
"self",
".",
"_request_one_trial_job",
"(",
")"
] | recerive the number of request and generate trials
Parameters
----------
data: int
number of trial jobs that nni manager ask to generate | [
"recerive",
"the",
"number",
"of",
"request",
"and",
"generate",
"trials"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/bohb_advisor/bohb_advisor.py#L394-L406 |
27,209 | Microsoft/nni | src/sdk/pynni/nni/bohb_advisor/bohb_advisor.py | BOHB.handle_trial_end | def handle_trial_end(self, data):
"""receive the information of trial end and generate next configuaration.
Parameters
----------
data: dict()
it has three keys: trial_job_id, event, hyper_params
trial_job_id: the id generated by training service
even... | python | def handle_trial_end(self, data):
"""receive the information of trial end and generate next configuaration.
Parameters
----------
data: dict()
it has three keys: trial_job_id, event, hyper_params
trial_job_id: the id generated by training service
even... | [
"def",
"handle_trial_end",
"(",
"self",
",",
"data",
")",
":",
"logger",
".",
"debug",
"(",
"'Tuner handle trial end, result is %s'",
",",
"data",
")",
"hyper_params",
"=",
"json_tricks",
".",
"loads",
"(",
"data",
"[",
"'hyper_params'",
"]",
")",
"s",
",",
... | receive the information of trial end and generate next configuaration.
Parameters
----------
data: dict()
it has three keys: trial_job_id, event, hyper_params
trial_job_id: the id generated by training service
event: the job's state
hyper_params: ... | [
"receive",
"the",
"information",
"of",
"trial",
"end",
"and",
"generate",
"next",
"configuaration",
"."
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/bohb_advisor/bohb_advisor.py#L498-L526 |
27,210 | Microsoft/nni | src/sdk/pynni/nni/bohb_advisor/bohb_advisor.py | BOHB.handle_report_metric_data | def handle_report_metric_data(self, data):
"""reveice the metric data and update Bayesian optimization with final result
Parameters
----------
data:
it is an object which has keys 'parameter_id', 'value', 'trial_job_id', 'type', 'sequence'.
Raises
------
... | python | def handle_report_metric_data(self, data):
"""reveice the metric data and update Bayesian optimization with final result
Parameters
----------
data:
it is an object which has keys 'parameter_id', 'value', 'trial_job_id', 'type', 'sequence'.
Raises
------
... | [
"def",
"handle_report_metric_data",
"(",
"self",
",",
"data",
")",
":",
"logger",
".",
"debug",
"(",
"'handle report metric data = %s'",
",",
"data",
")",
"assert",
"'value'",
"in",
"data",
"value",
"=",
"extract_scalar_reward",
"(",
"data",
"[",
"'value'",
"]",... | reveice the metric data and update Bayesian optimization with final result
Parameters
----------
data:
it is an object which has keys 'parameter_id', 'value', 'trial_job_id', 'type', 'sequence'.
Raises
------
ValueError
Data type not supported | [
"reveice",
"the",
"metric",
"data",
"and",
"update",
"Bayesian",
"optimization",
"with",
"final",
"result"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/bohb_advisor/bohb_advisor.py#L528-L572 |
27,211 | Microsoft/nni | examples/trials/network_morphism/FashionMNIST/utils.py | data_transforms_cifar10 | def data_transforms_cifar10(args):
""" data_transforms for cifar10 dataset
"""
cifar_mean = [0.49139968, 0.48215827, 0.44653124]
cifar_std = [0.24703233, 0.24348505, 0.26158768]
train_transform = transforms.Compose(
[
transforms.RandomCrop(32, padding=4),
transforms... | python | def data_transforms_cifar10(args):
""" data_transforms for cifar10 dataset
"""
cifar_mean = [0.49139968, 0.48215827, 0.44653124]
cifar_std = [0.24703233, 0.24348505, 0.26158768]
train_transform = transforms.Compose(
[
transforms.RandomCrop(32, padding=4),
transforms... | [
"def",
"data_transforms_cifar10",
"(",
"args",
")",
":",
"cifar_mean",
"=",
"[",
"0.49139968",
",",
"0.48215827",
",",
"0.44653124",
"]",
"cifar_std",
"=",
"[",
"0.24703233",
",",
"0.24348505",
",",
"0.26158768",
"]",
"train_transform",
"=",
"transforms",
".",
... | data_transforms for cifar10 dataset | [
"data_transforms",
"for",
"cifar10",
"dataset"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/examples/trials/network_morphism/FashionMNIST/utils.py#L116-L137 |
27,212 | Microsoft/nni | examples/trials/network_morphism/FashionMNIST/utils.py | data_transforms_mnist | def data_transforms_mnist(args, mnist_mean=None, mnist_std=None):
""" data_transforms for mnist dataset
"""
if mnist_mean is None:
mnist_mean = [0.5]
if mnist_std is None:
mnist_std = [0.5]
train_transform = transforms.Compose(
[
transforms.RandomCrop(28, paddin... | python | def data_transforms_mnist(args, mnist_mean=None, mnist_std=None):
""" data_transforms for mnist dataset
"""
if mnist_mean is None:
mnist_mean = [0.5]
if mnist_std is None:
mnist_std = [0.5]
train_transform = transforms.Compose(
[
transforms.RandomCrop(28, paddin... | [
"def",
"data_transforms_mnist",
"(",
"args",
",",
"mnist_mean",
"=",
"None",
",",
"mnist_std",
"=",
"None",
")",
":",
"if",
"mnist_mean",
"is",
"None",
":",
"mnist_mean",
"=",
"[",
"0.5",
"]",
"if",
"mnist_std",
"is",
"None",
":",
"mnist_std",
"=",
"[",
... | data_transforms for mnist dataset | [
"data_transforms",
"for",
"mnist",
"dataset"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/examples/trials/network_morphism/FashionMNIST/utils.py#L140-L163 |
27,213 | Microsoft/nni | examples/trials/network_morphism/FashionMNIST/utils.py | get_mean_and_std | def get_mean_and_std(dataset):
"""Compute the mean and std value of dataset."""
dataloader = torch.utils.data.DataLoader(
dataset, batch_size=1, shuffle=True, num_workers=2
)
mean = torch.zeros(3)
std = torch.zeros(3)
print("==> Computing mean and std..")
for inputs, _ in dataloader:... | python | def get_mean_and_std(dataset):
"""Compute the mean and std value of dataset."""
dataloader = torch.utils.data.DataLoader(
dataset, batch_size=1, shuffle=True, num_workers=2
)
mean = torch.zeros(3)
std = torch.zeros(3)
print("==> Computing mean and std..")
for inputs, _ in dataloader:... | [
"def",
"get_mean_and_std",
"(",
"dataset",
")",
":",
"dataloader",
"=",
"torch",
".",
"utils",
".",
"data",
".",
"DataLoader",
"(",
"dataset",
",",
"batch_size",
"=",
"1",
",",
"shuffle",
"=",
"True",
",",
"num_workers",
"=",
"2",
")",
"mean",
"=",
"to... | Compute the mean and std value of dataset. | [
"Compute",
"the",
"mean",
"and",
"std",
"value",
"of",
"dataset",
"."
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/examples/trials/network_morphism/FashionMNIST/utils.py#L166-L180 |
27,214 | Microsoft/nni | src/sdk/pynni/nni/metis_tuner/lib_constraint_summation.py | check_feasibility | def check_feasibility(x_bounds, lowerbound, upperbound):
'''
This can have false positives.
For examples, parameters can only be 0 or 5, and the summation constraint is between 6 and 7.
'''
# x_bounds should be sorted, so even for "discrete_int" type,
# the smallest and the largest number should... | python | def check_feasibility(x_bounds, lowerbound, upperbound):
'''
This can have false positives.
For examples, parameters can only be 0 or 5, and the summation constraint is between 6 and 7.
'''
# x_bounds should be sorted, so even for "discrete_int" type,
# the smallest and the largest number should... | [
"def",
"check_feasibility",
"(",
"x_bounds",
",",
"lowerbound",
",",
"upperbound",
")",
":",
"# x_bounds should be sorted, so even for \"discrete_int\" type,",
"# the smallest and the largest number should the first and the last element",
"x_bounds_lowerbound",
"=",
"sum",
"(",
"[",
... | This can have false positives.
For examples, parameters can only be 0 or 5, and the summation constraint is between 6 and 7. | [
"This",
"can",
"have",
"false",
"positives",
".",
"For",
"examples",
"parameters",
"can",
"only",
"be",
"0",
"or",
"5",
"and",
"the",
"summation",
"constraint",
"is",
"between",
"6",
"and",
"7",
"."
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/metis_tuner/lib_constraint_summation.py#L27-L40 |
27,215 | Microsoft/nni | src/sdk/pynni/nni/metis_tuner/lib_constraint_summation.py | rand | def rand(x_bounds, x_types, lowerbound, upperbound, max_retries=100):
'''
Key idea is that we try to move towards upperbound, by randomly choose one
value for each parameter. However, for the last parameter,
we need to make sure that its value can help us get above lowerbound
'''
outputs = None
... | python | def rand(x_bounds, x_types, lowerbound, upperbound, max_retries=100):
'''
Key idea is that we try to move towards upperbound, by randomly choose one
value for each parameter. However, for the last parameter,
we need to make sure that its value can help us get above lowerbound
'''
outputs = None
... | [
"def",
"rand",
"(",
"x_bounds",
",",
"x_types",
",",
"lowerbound",
",",
"upperbound",
",",
"max_retries",
"=",
"100",
")",
":",
"outputs",
"=",
"None",
"if",
"check_feasibility",
"(",
"x_bounds",
",",
"lowerbound",
",",
"upperbound",
")",
"is",
"True",
":"... | Key idea is that we try to move towards upperbound, by randomly choose one
value for each parameter. However, for the last parameter,
we need to make sure that its value can help us get above lowerbound | [
"Key",
"idea",
"is",
"that",
"we",
"try",
"to",
"move",
"towards",
"upperbound",
"by",
"randomly",
"choose",
"one",
"value",
"for",
"each",
"parameter",
".",
"However",
"for",
"the",
"last",
"parameter",
"we",
"need",
"to",
"make",
"sure",
"that",
"its",
... | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/metis_tuner/lib_constraint_summation.py#L42-L115 |
27,216 | Microsoft/nni | tools/nni_cmd/launcher_utils.py | expand_path | def expand_path(experiment_config, key):
'''Change '~' to user home directory'''
if experiment_config.get(key):
experiment_config[key] = os.path.expanduser(experiment_config[key]) | python | def expand_path(experiment_config, key):
'''Change '~' to user home directory'''
if experiment_config.get(key):
experiment_config[key] = os.path.expanduser(experiment_config[key]) | [
"def",
"expand_path",
"(",
"experiment_config",
",",
"key",
")",
":",
"if",
"experiment_config",
".",
"get",
"(",
"key",
")",
":",
"experiment_config",
"[",
"key",
"]",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"experiment_config",
"[",
"key",
"]",
... | Change '~' to user home directory | [
"Change",
"~",
"to",
"user",
"home",
"directory"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/tools/nni_cmd/launcher_utils.py#L29-L32 |
27,217 | Microsoft/nni | tools/nni_cmd/launcher_utils.py | parse_relative_path | def parse_relative_path(root_path, experiment_config, key):
'''Change relative path to absolute path'''
if experiment_config.get(key) and not os.path.isabs(experiment_config.get(key)):
absolute_path = os.path.join(root_path, experiment_config.get(key))
print_normal('expand %s: %s to %s ' % (key,... | python | def parse_relative_path(root_path, experiment_config, key):
'''Change relative path to absolute path'''
if experiment_config.get(key) and not os.path.isabs(experiment_config.get(key)):
absolute_path = os.path.join(root_path, experiment_config.get(key))
print_normal('expand %s: %s to %s ' % (key,... | [
"def",
"parse_relative_path",
"(",
"root_path",
",",
"experiment_config",
",",
"key",
")",
":",
"if",
"experiment_config",
".",
"get",
"(",
"key",
")",
"and",
"not",
"os",
".",
"path",
".",
"isabs",
"(",
"experiment_config",
".",
"get",
"(",
"key",
")",
... | Change relative path to absolute path | [
"Change",
"relative",
"path",
"to",
"absolute",
"path"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/tools/nni_cmd/launcher_utils.py#L34-L39 |
27,218 | Microsoft/nni | tools/nni_cmd/launcher_utils.py | parse_time | def parse_time(time):
'''Change the time to seconds'''
unit = time[-1]
if unit not in ['s', 'm', 'h', 'd']:
print_error('the unit of time could only from {s, m, h, d}')
exit(1)
time = time[:-1]
if not time.isdigit():
print_error('time format error!')
exit(1)
parse... | python | def parse_time(time):
'''Change the time to seconds'''
unit = time[-1]
if unit not in ['s', 'm', 'h', 'd']:
print_error('the unit of time could only from {s, m, h, d}')
exit(1)
time = time[:-1]
if not time.isdigit():
print_error('time format error!')
exit(1)
parse... | [
"def",
"parse_time",
"(",
"time",
")",
":",
"unit",
"=",
"time",
"[",
"-",
"1",
"]",
"if",
"unit",
"not",
"in",
"[",
"'s'",
",",
"'m'",
",",
"'h'",
",",
"'d'",
"]",
":",
"print_error",
"(",
"'the unit of time could only from {s, m, h, d}'",
")",
"exit",
... | Change the time to seconds | [
"Change",
"the",
"time",
"to",
"seconds"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/tools/nni_cmd/launcher_utils.py#L41-L52 |
27,219 | Microsoft/nni | tools/nni_cmd/launcher_utils.py | parse_path | def parse_path(experiment_config, config_path):
'''Parse path in config file'''
expand_path(experiment_config, 'searchSpacePath')
if experiment_config.get('trial'):
expand_path(experiment_config['trial'], 'codeDir')
if experiment_config.get('tuner'):
expand_path(experiment_config['tuner'... | python | def parse_path(experiment_config, config_path):
'''Parse path in config file'''
expand_path(experiment_config, 'searchSpacePath')
if experiment_config.get('trial'):
expand_path(experiment_config['trial'], 'codeDir')
if experiment_config.get('tuner'):
expand_path(experiment_config['tuner'... | [
"def",
"parse_path",
"(",
"experiment_config",
",",
"config_path",
")",
":",
"expand_path",
"(",
"experiment_config",
",",
"'searchSpacePath'",
")",
"if",
"experiment_config",
".",
"get",
"(",
"'trial'",
")",
":",
"expand_path",
"(",
"experiment_config",
"[",
"'tr... | Parse path in config file | [
"Parse",
"path",
"in",
"config",
"file"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/tools/nni_cmd/launcher_utils.py#L54-L80 |
27,220 | Microsoft/nni | tools/nni_cmd/launcher_utils.py | validate_search_space_content | def validate_search_space_content(experiment_config):
'''Validate searchspace content,
if the searchspace file is not json format or its values does not contain _type and _value which must be specified,
it will not be a valid searchspace file'''
try:
search_space_content = json.load(open... | python | def validate_search_space_content(experiment_config):
'''Validate searchspace content,
if the searchspace file is not json format or its values does not contain _type and _value which must be specified,
it will not be a valid searchspace file'''
try:
search_space_content = json.load(open... | [
"def",
"validate_search_space_content",
"(",
"experiment_config",
")",
":",
"try",
":",
"search_space_content",
"=",
"json",
".",
"load",
"(",
"open",
"(",
"experiment_config",
".",
"get",
"(",
"'searchSpacePath'",
")",
",",
"'r'",
")",
")",
"for",
"value",
"i... | Validate searchspace content,
if the searchspace file is not json format or its values does not contain _type and _value which must be specified,
it will not be a valid searchspace file | [
"Validate",
"searchspace",
"content",
"if",
"the",
"searchspace",
"file",
"is",
"not",
"json",
"format",
"or",
"its",
"values",
"does",
"not",
"contain",
"_type",
"and",
"_value",
"which",
"must",
"be",
"specified",
"it",
"will",
"not",
"be",
"a",
"valid",
... | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/tools/nni_cmd/launcher_utils.py#L82-L94 |
27,221 | Microsoft/nni | tools/nni_cmd/launcher_utils.py | validate_kubeflow_operators | def validate_kubeflow_operators(experiment_config):
'''Validate whether the kubeflow operators are valid'''
if experiment_config.get('kubeflowConfig'):
if experiment_config.get('kubeflowConfig').get('operator') == 'tf-operator':
if experiment_config.get('trial').get('master') is not None:
... | python | def validate_kubeflow_operators(experiment_config):
'''Validate whether the kubeflow operators are valid'''
if experiment_config.get('kubeflowConfig'):
if experiment_config.get('kubeflowConfig').get('operator') == 'tf-operator':
if experiment_config.get('trial').get('master') is not None:
... | [
"def",
"validate_kubeflow_operators",
"(",
"experiment_config",
")",
":",
"if",
"experiment_config",
".",
"get",
"(",
"'kubeflowConfig'",
")",
":",
"if",
"experiment_config",
".",
"get",
"(",
"'kubeflowConfig'",
")",
".",
"get",
"(",
"'operator'",
")",
"==",
"'t... | Validate whether the kubeflow operators are valid | [
"Validate",
"whether",
"the",
"kubeflow",
"operators",
"are",
"valid"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/tools/nni_cmd/launcher_utils.py#L96-L125 |
27,222 | Microsoft/nni | tools/nni_cmd/launcher_utils.py | validate_common_content | def validate_common_content(experiment_config):
'''Validate whether the common values in experiment_config is valid'''
if not experiment_config.get('trainingServicePlatform') or \
experiment_config.get('trainingServicePlatform') not in ['local', 'remote', 'pai', 'kubeflow', 'frameworkcontroller']:
... | python | def validate_common_content(experiment_config):
'''Validate whether the common values in experiment_config is valid'''
if not experiment_config.get('trainingServicePlatform') or \
experiment_config.get('trainingServicePlatform') not in ['local', 'remote', 'pai', 'kubeflow', 'frameworkcontroller']:
... | [
"def",
"validate_common_content",
"(",
"experiment_config",
")",
":",
"if",
"not",
"experiment_config",
".",
"get",
"(",
"'trainingServicePlatform'",
")",
"or",
"experiment_config",
".",
"get",
"(",
"'trainingServicePlatform'",
")",
"not",
"in",
"[",
"'local'",
",",... | Validate whether the common values in experiment_config is valid | [
"Validate",
"whether",
"the",
"common",
"values",
"in",
"experiment_config",
"is",
"valid"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/tools/nni_cmd/launcher_utils.py#L127-L182 |
27,223 | Microsoft/nni | tools/nni_cmd/launcher_utils.py | parse_assessor_content | def parse_assessor_content(experiment_config):
'''Validate whether assessor in experiment_config is valid'''
if experiment_config.get('assessor'):
if experiment_config['assessor'].get('builtinAssessorName'):
experiment_config['assessor']['className'] = experiment_config['assessor']['builtinA... | python | def parse_assessor_content(experiment_config):
'''Validate whether assessor in experiment_config is valid'''
if experiment_config.get('assessor'):
if experiment_config['assessor'].get('builtinAssessorName'):
experiment_config['assessor']['className'] = experiment_config['assessor']['builtinA... | [
"def",
"parse_assessor_content",
"(",
"experiment_config",
")",
":",
"if",
"experiment_config",
".",
"get",
"(",
"'assessor'",
")",
":",
"if",
"experiment_config",
"[",
"'assessor'",
"]",
".",
"get",
"(",
"'builtinAssessorName'",
")",
":",
"experiment_config",
"["... | Validate whether assessor in experiment_config is valid | [
"Validate",
"whether",
"assessor",
"in",
"experiment_config",
"is",
"valid"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/tools/nni_cmd/launcher_utils.py#L208-L214 |
27,224 | Microsoft/nni | tools/nni_cmd/launcher_utils.py | validate_pai_trial_conifg | def validate_pai_trial_conifg(experiment_config):
'''validate the trial config in pai platform'''
if experiment_config.get('trainingServicePlatform') == 'pai':
if experiment_config.get('trial').get('shmMB') and \
experiment_config['trial']['shmMB'] > experiment_config['trial']['memoryMB']:
... | python | def validate_pai_trial_conifg(experiment_config):
'''validate the trial config in pai platform'''
if experiment_config.get('trainingServicePlatform') == 'pai':
if experiment_config.get('trial').get('shmMB') and \
experiment_config['trial']['shmMB'] > experiment_config['trial']['memoryMB']:
... | [
"def",
"validate_pai_trial_conifg",
"(",
"experiment_config",
")",
":",
"if",
"experiment_config",
".",
"get",
"(",
"'trainingServicePlatform'",
")",
"==",
"'pai'",
":",
"if",
"experiment_config",
".",
"get",
"(",
"'trial'",
")",
".",
"get",
"(",
"'shmMB'",
")",... | validate the trial config in pai platform | [
"validate",
"the",
"trial",
"config",
"in",
"pai",
"platform"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/tools/nni_cmd/launcher_utils.py#L249-L255 |
27,225 | Microsoft/nni | tools/nni_cmd/launcher_utils.py | validate_all_content | def validate_all_content(experiment_config, config_path):
'''Validate whether experiment_config is valid'''
parse_path(experiment_config, config_path)
validate_common_content(experiment_config)
validate_pai_trial_conifg(experiment_config)
experiment_config['maxExecDuration'] = parse_time(experiment_... | python | def validate_all_content(experiment_config, config_path):
'''Validate whether experiment_config is valid'''
parse_path(experiment_config, config_path)
validate_common_content(experiment_config)
validate_pai_trial_conifg(experiment_config)
experiment_config['maxExecDuration'] = parse_time(experiment_... | [
"def",
"validate_all_content",
"(",
"experiment_config",
",",
"config_path",
")",
":",
"parse_path",
"(",
"experiment_config",
",",
"config_path",
")",
"validate_common_content",
"(",
"experiment_config",
")",
"validate_pai_trial_conifg",
"(",
"experiment_config",
")",
"e... | Validate whether experiment_config is valid | [
"Validate",
"whether",
"experiment_config",
"is",
"valid"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/tools/nni_cmd/launcher_utils.py#L257-L274 |
27,226 | Microsoft/nni | tools/nni_cmd/url_utils.py | get_local_urls | def get_local_urls(port):
'''get urls of local machine'''
url_list = []
for name, info in psutil.net_if_addrs().items():
for addr in info:
if AddressFamily.AF_INET == addr.family:
url_list.append('http://{}:{}'.format(addr.address, port))
return url_list | python | def get_local_urls(port):
'''get urls of local machine'''
url_list = []
for name, info in psutil.net_if_addrs().items():
for addr in info:
if AddressFamily.AF_INET == addr.family:
url_list.append('http://{}:{}'.format(addr.address, port))
return url_list | [
"def",
"get_local_urls",
"(",
"port",
")",
":",
"url_list",
"=",
"[",
"]",
"for",
"name",
",",
"info",
"in",
"psutil",
".",
"net_if_addrs",
"(",
")",
".",
"items",
"(",
")",
":",
"for",
"addr",
"in",
"info",
":",
"if",
"AddressFamily",
".",
"AF_INET"... | get urls of local machine | [
"get",
"urls",
"of",
"local",
"machine"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/tools/nni_cmd/url_utils.py#L76-L83 |
27,227 | Microsoft/nni | tools/nni_annotation/code_generator.py | convert_args_to_dict | def convert_args_to_dict(call, with_lambda=False):
"""Convert all args to a dict such that every key and value in the dict is the same as the value of the arg.
Return the AST Call node with only one arg that is the dictionary
"""
keys, values = list(), list()
for arg in call.args:
if type(ar... | python | def convert_args_to_dict(call, with_lambda=False):
"""Convert all args to a dict such that every key and value in the dict is the same as the value of the arg.
Return the AST Call node with only one arg that is the dictionary
"""
keys, values = list(), list()
for arg in call.args:
if type(ar... | [
"def",
"convert_args_to_dict",
"(",
"call",
",",
"with_lambda",
"=",
"False",
")",
":",
"keys",
",",
"values",
"=",
"list",
"(",
")",
",",
"list",
"(",
")",
"for",
"arg",
"in",
"call",
".",
"args",
":",
"if",
"type",
"(",
"arg",
")",
"in",
"[",
"... | Convert all args to a dict such that every key and value in the dict is the same as the value of the arg.
Return the AST Call node with only one arg that is the dictionary | [
"Convert",
"all",
"args",
"to",
"a",
"dict",
"such",
"that",
"every",
"key",
"and",
"value",
"in",
"the",
"dict",
"is",
"the",
"same",
"as",
"the",
"value",
"of",
"the",
"arg",
".",
"Return",
"the",
"AST",
"Call",
"node",
"with",
"only",
"one",
"arg"... | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/tools/nni_annotation/code_generator.py#L100-L118 |
27,228 | Microsoft/nni | src/sdk/pynni/nni/__main__.py | main | def main():
'''
main function.
'''
args = parse_args()
if args.multi_thread:
enable_multi_thread()
if args.advisor_class_name:
# advisor is enabled and starts to run
if args.multi_phase:
raise AssertionError('multi_phase has not been supported in advisor')
... | python | def main():
'''
main function.
'''
args = parse_args()
if args.multi_thread:
enable_multi_thread()
if args.advisor_class_name:
# advisor is enabled and starts to run
if args.multi_phase:
raise AssertionError('multi_phase has not been supported in advisor')
... | [
"def",
"main",
"(",
")",
":",
"args",
"=",
"parse_args",
"(",
")",
"if",
"args",
".",
"multi_thread",
":",
"enable_multi_thread",
"(",
")",
"if",
"args",
".",
"advisor_class_name",
":",
"# advisor is enabled and starts to run",
"if",
"args",
".",
"multi_phase",
... | main function. | [
"main",
"function",
"."
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/__main__.py#L121-L198 |
27,229 | Microsoft/nni | tools/nni_cmd/common_utils.py | get_yml_content | def get_yml_content(file_path):
'''Load yaml file content'''
try:
with open(file_path, 'r') as file:
return yaml.load(file, Loader=yaml.Loader)
except yaml.scanner.ScannerError as err:
print_error('yaml file format error!')
exit(1)
except Exception as exception:
... | python | def get_yml_content(file_path):
'''Load yaml file content'''
try:
with open(file_path, 'r') as file:
return yaml.load(file, Loader=yaml.Loader)
except yaml.scanner.ScannerError as err:
print_error('yaml file format error!')
exit(1)
except Exception as exception:
... | [
"def",
"get_yml_content",
"(",
"file_path",
")",
":",
"try",
":",
"with",
"open",
"(",
"file_path",
",",
"'r'",
")",
"as",
"file",
":",
"return",
"yaml",
".",
"load",
"(",
"file",
",",
"Loader",
"=",
"yaml",
".",
"Loader",
")",
"except",
"yaml",
".",... | Load yaml file content | [
"Load",
"yaml",
"file",
"content"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/tools/nni_cmd/common_utils.py#L30-L40 |
27,230 | Microsoft/nni | tools/nni_cmd/common_utils.py | detect_port | def detect_port(port):
'''Detect if the port is used'''
socket_test = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
try:
socket_test.connect(('127.0.0.1', int(port)))
socket_test.close()
return True
except:
return False | python | def detect_port(port):
'''Detect if the port is used'''
socket_test = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
try:
socket_test.connect(('127.0.0.1', int(port)))
socket_test.close()
return True
except:
return False | [
"def",
"detect_port",
"(",
"port",
")",
":",
"socket_test",
"=",
"socket",
".",
"socket",
"(",
"socket",
".",
"AF_INET",
",",
"socket",
".",
"SOCK_STREAM",
")",
"try",
":",
"socket_test",
".",
"connect",
"(",
"(",
"'127.0.0.1'",
",",
"int",
"(",
"port",
... | Detect if the port is used | [
"Detect",
"if",
"the",
"port",
"is",
"used"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/tools/nni_cmd/common_utils.py#L71-L79 |
27,231 | Microsoft/nni | src/sdk/pynni/nni/metis_tuner/Regression_GMM/CreateModel.py | create_model | def create_model(samples_x, samples_y_aggregation, percentage_goodbatch=0.34):
'''
Create the Gaussian Mixture Model
'''
samples = [samples_x[i] + [samples_y_aggregation[i]] for i in range(0, len(samples_x))]
# Sorts so that we can get the top samples
samples = sorted(samples, key=itemgetter(-1... | python | def create_model(samples_x, samples_y_aggregation, percentage_goodbatch=0.34):
'''
Create the Gaussian Mixture Model
'''
samples = [samples_x[i] + [samples_y_aggregation[i]] for i in range(0, len(samples_x))]
# Sorts so that we can get the top samples
samples = sorted(samples, key=itemgetter(-1... | [
"def",
"create_model",
"(",
"samples_x",
",",
"samples_y_aggregation",
",",
"percentage_goodbatch",
"=",
"0.34",
")",
":",
"samples",
"=",
"[",
"samples_x",
"[",
"i",
"]",
"+",
"[",
"samples_y_aggregation",
"[",
"i",
"]",
"]",
"for",
"i",
"in",
"range",
"(... | Create the Gaussian Mixture Model | [
"Create",
"the",
"Gaussian",
"Mixture",
"Model"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/metis_tuner/Regression_GMM/CreateModel.py#L30-L57 |
27,232 | Microsoft/nni | src/sdk/pynni/nni/metis_tuner/Regression_GP/Selection.py | selection_r | def selection_r(acquisition_function,
samples_y_aggregation,
x_bounds,
x_types,
regressor_gp,
num_starting_points=100,
minimize_constraints_fun=None):
'''
Selecte R value
'''
minimize_starting_points = [lib_d... | python | def selection_r(acquisition_function,
samples_y_aggregation,
x_bounds,
x_types,
regressor_gp,
num_starting_points=100,
minimize_constraints_fun=None):
'''
Selecte R value
'''
minimize_starting_points = [lib_d... | [
"def",
"selection_r",
"(",
"acquisition_function",
",",
"samples_y_aggregation",
",",
"x_bounds",
",",
"x_types",
",",
"regressor_gp",
",",
"num_starting_points",
"=",
"100",
",",
"minimize_constraints_fun",
"=",
"None",
")",
":",
"minimize_starting_points",
"=",
"[",... | Selecte R value | [
"Selecte",
"R",
"value"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/metis_tuner/Regression_GP/Selection.py#L37-L54 |
27,233 | Microsoft/nni | examples/trials/network_morphism/FashionMNIST/FashionMNIST_pytorch.py | get_args | def get_args():
""" get args from command line
"""
parser = argparse.ArgumentParser("FashionMNIST")
parser.add_argument("--batch_size", type=int, default=128, help="batch size")
parser.add_argument("--optimizer", type=str, default="SGD", help="optimizer")
parser.add_argument("--epochs", type=int... | python | def get_args():
""" get args from command line
"""
parser = argparse.ArgumentParser("FashionMNIST")
parser.add_argument("--batch_size", type=int, default=128, help="batch size")
parser.add_argument("--optimizer", type=str, default="SGD", help="optimizer")
parser.add_argument("--epochs", type=int... | [
"def",
"get_args",
"(",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"\"FashionMNIST\"",
")",
"parser",
".",
"add_argument",
"(",
"\"--batch_size\"",
",",
"type",
"=",
"int",
",",
"default",
"=",
"128",
",",
"help",
"=",
"\"batch size\"",... | get args from command line | [
"get",
"args",
"from",
"command",
"line"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/examples/trials/network_morphism/FashionMNIST/FashionMNIST_pytorch.py#L47-L62 |
27,234 | Microsoft/nni | examples/trials/network_morphism/FashionMNIST/FashionMNIST_pytorch.py | build_graph_from_json | def build_graph_from_json(ir_model_json):
"""build model from json representation
"""
graph = json_to_graph(ir_model_json)
logging.debug(graph.operation_history)
model = graph.produce_torch_model()
return model | python | def build_graph_from_json(ir_model_json):
"""build model from json representation
"""
graph = json_to_graph(ir_model_json)
logging.debug(graph.operation_history)
model = graph.produce_torch_model()
return model | [
"def",
"build_graph_from_json",
"(",
"ir_model_json",
")",
":",
"graph",
"=",
"json_to_graph",
"(",
"ir_model_json",
")",
"logging",
".",
"debug",
"(",
"graph",
".",
"operation_history",
")",
"model",
"=",
"graph",
".",
"produce_torch_model",
"(",
")",
"return",... | build model from json representation | [
"build",
"model",
"from",
"json",
"representation"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/examples/trials/network_morphism/FashionMNIST/FashionMNIST_pytorch.py#L75-L81 |
27,235 | Microsoft/nni | examples/trials/network_morphism/FashionMNIST/FashionMNIST_pytorch.py | train | def train(epoch):
""" train model on each epoch in trainset
"""
global trainloader
global testloader
global net
global criterion
global optimizer
logger.debug("Epoch: %d", epoch)
net.train()
train_loss = 0
correct = 0
total = 0
for batch_idx, (inputs, targets) in e... | python | def train(epoch):
""" train model on each epoch in trainset
"""
global trainloader
global testloader
global net
global criterion
global optimizer
logger.debug("Epoch: %d", epoch)
net.train()
train_loss = 0
correct = 0
total = 0
for batch_idx, (inputs, targets) in e... | [
"def",
"train",
"(",
"epoch",
")",
":",
"global",
"trainloader",
"global",
"testloader",
"global",
"net",
"global",
"criterion",
"global",
"optimizer",
"logger",
".",
"debug",
"(",
"\"Epoch: %d\"",
",",
"epoch",
")",
"net",
".",
"train",
"(",
")",
"train_los... | train model on each epoch in trainset | [
"train",
"model",
"on",
"each",
"epoch",
"in",
"trainset"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/examples/trials/network_morphism/FashionMNIST/FashionMNIST_pytorch.py#L149-L188 |
27,236 | Microsoft/nni | examples/trials/kaggle-tgs-salt/models.py | UNetResNetV4.freeze_bn | def freeze_bn(self):
'''Freeze BatchNorm layers.'''
for layer in self.modules():
if isinstance(layer, nn.BatchNorm2d):
layer.eval() | python | def freeze_bn(self):
'''Freeze BatchNorm layers.'''
for layer in self.modules():
if isinstance(layer, nn.BatchNorm2d):
layer.eval() | [
"def",
"freeze_bn",
"(",
"self",
")",
":",
"for",
"layer",
"in",
"self",
".",
"modules",
"(",
")",
":",
"if",
"isinstance",
"(",
"layer",
",",
"nn",
".",
"BatchNorm2d",
")",
":",
"layer",
".",
"eval",
"(",
")"
] | Freeze BatchNorm layers. | [
"Freeze",
"BatchNorm",
"layers",
"."
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/examples/trials/kaggle-tgs-salt/models.py#L210-L214 |
27,237 | tensorpack/tensorpack | tensorpack/utils/nvml.py | NvidiaDevice.memory | def memory(self):
"""Memory information in bytes
Example:
>>> print(ctx.device(0).memory())
{'total': 4238016512L, 'used': 434831360L, 'free': 3803185152L}
Returns:
total/used/free memory in bytes
"""
class GpuMemoryInfo(Structure):
... | python | def memory(self):
"""Memory information in bytes
Example:
>>> print(ctx.device(0).memory())
{'total': 4238016512L, 'used': 434831360L, 'free': 3803185152L}
Returns:
total/used/free memory in bytes
"""
class GpuMemoryInfo(Structure):
... | [
"def",
"memory",
"(",
"self",
")",
":",
"class",
"GpuMemoryInfo",
"(",
"Structure",
")",
":",
"_fields_",
"=",
"[",
"(",
"'total'",
",",
"c_ulonglong",
")",
",",
"(",
"'free'",
",",
"c_ulonglong",
")",
",",
"(",
"'used'",
",",
"c_ulonglong",
")",
",",
... | Memory information in bytes
Example:
>>> print(ctx.device(0).memory())
{'total': 4238016512L, 'used': 434831360L, 'free': 3803185152L}
Returns:
total/used/free memory in bytes | [
"Memory",
"information",
"in",
"bytes"
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/nvml.py#L92-L113 |
27,238 | tensorpack/tensorpack | tensorpack/utils/nvml.py | NvidiaDevice.utilization | def utilization(self):
"""Percent of time over the past second was utilized.
Details:
Percent of time over the past second during which one or more kernels was executing on the GPU.
Percent of time over the past second during which global (device) memory was being read or written
... | python | def utilization(self):
"""Percent of time over the past second was utilized.
Details:
Percent of time over the past second during which one or more kernels was executing on the GPU.
Percent of time over the past second during which global (device) memory was being read or written
... | [
"def",
"utilization",
"(",
"self",
")",
":",
"class",
"GpuUtilizationInfo",
"(",
"Structure",
")",
":",
"_fields_",
"=",
"[",
"(",
"'gpu'",
",",
"c_uint",
")",
",",
"(",
"'memory'",
",",
"c_uint",
")",
",",
"]",
"c_util",
"=",
"GpuUtilizationInfo",
"(",
... | Percent of time over the past second was utilized.
Details:
Percent of time over the past second during which one or more kernels was executing on the GPU.
Percent of time over the past second during which global (device) memory was being read or written
Example:
>>>... | [
"Percent",
"of",
"time",
"over",
"the",
"past",
"second",
"was",
"utilized",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/nvml.py#L115-L138 |
27,239 | tensorpack/tensorpack | tensorpack/utils/nvml.py | NVMLContext.num_devices | def num_devices(self):
"""Get number of devices """
c_count = c_uint()
_check_return(_NVML.get_function(
"nvmlDeviceGetCount_v2")(byref(c_count)))
return c_count.value | python | def num_devices(self):
"""Get number of devices """
c_count = c_uint()
_check_return(_NVML.get_function(
"nvmlDeviceGetCount_v2")(byref(c_count)))
return c_count.value | [
"def",
"num_devices",
"(",
"self",
")",
":",
"c_count",
"=",
"c_uint",
"(",
")",
"_check_return",
"(",
"_NVML",
".",
"get_function",
"(",
"\"nvmlDeviceGetCount_v2\"",
")",
"(",
"byref",
"(",
"c_count",
")",
")",
")",
"return",
"c_count",
".",
"value"
] | Get number of devices | [
"Get",
"number",
"of",
"devices"
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/nvml.py#L171-L176 |
27,240 | tensorpack/tensorpack | tensorpack/utils/nvml.py | NVMLContext.device | def device(self, idx):
"""Get a specific GPU device
Args:
idx: index of device
Returns:
NvidiaDevice: single GPU device
"""
class GpuDevice(Structure):
pass
c_nvmlDevice_t = POINTER(GpuDevice)
c_index = c_uint(idx)
... | python | def device(self, idx):
"""Get a specific GPU device
Args:
idx: index of device
Returns:
NvidiaDevice: single GPU device
"""
class GpuDevice(Structure):
pass
c_nvmlDevice_t = POINTER(GpuDevice)
c_index = c_uint(idx)
... | [
"def",
"device",
"(",
"self",
",",
"idx",
")",
":",
"class",
"GpuDevice",
"(",
"Structure",
")",
":",
"pass",
"c_nvmlDevice_t",
"=",
"POINTER",
"(",
"GpuDevice",
")",
"c_index",
"=",
"c_uint",
"(",
"idx",
")",
"device",
"=",
"c_nvmlDevice_t",
"(",
")",
... | Get a specific GPU device
Args:
idx: index of device
Returns:
NvidiaDevice: single GPU device | [
"Get",
"a",
"specific",
"GPU",
"device"
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/nvml.py#L185-L204 |
27,241 | tensorpack/tensorpack | tensorpack/dataflow/dataset/cifar.py | maybe_download_and_extract | def maybe_download_and_extract(dest_directory, cifar_classnum):
"""Download and extract the tarball from Alex's website. Copied from tensorflow example """
assert cifar_classnum == 10 or cifar_classnum == 100
if cifar_classnum == 10:
cifar_foldername = 'cifar-10-batches-py'
else:
cifar_f... | python | def maybe_download_and_extract(dest_directory, cifar_classnum):
"""Download and extract the tarball from Alex's website. Copied from tensorflow example """
assert cifar_classnum == 10 or cifar_classnum == 100
if cifar_classnum == 10:
cifar_foldername = 'cifar-10-batches-py'
else:
cifar_f... | [
"def",
"maybe_download_and_extract",
"(",
"dest_directory",
",",
"cifar_classnum",
")",
":",
"assert",
"cifar_classnum",
"==",
"10",
"or",
"cifar_classnum",
"==",
"100",
"if",
"cifar_classnum",
"==",
"10",
":",
"cifar_foldername",
"=",
"'cifar-10-batches-py'",
"else",... | Download and extract the tarball from Alex's website. Copied from tensorflow example | [
"Download",
"and",
"extract",
"the",
"tarball",
"from",
"Alex",
"s",
"website",
".",
"Copied",
"from",
"tensorflow",
"example"
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/dataflow/dataset/cifar.py#L24-L39 |
27,242 | tensorpack/tensorpack | tensorpack/graph_builder/model_desc.py | build_or_reuse_placeholder | def build_or_reuse_placeholder(tensor_spec):
"""
Build a tf.placeholder from the metadata in the given tensor spec, or return an existing one.
Args:
tensor_spec (tf.TensorSpec):
Returns:
tf.Tensor:
"""
g = tfv1.get_default_graph()
name = tensor_spec.name
try:
te... | python | def build_or_reuse_placeholder(tensor_spec):
"""
Build a tf.placeholder from the metadata in the given tensor spec, or return an existing one.
Args:
tensor_spec (tf.TensorSpec):
Returns:
tf.Tensor:
"""
g = tfv1.get_default_graph()
name = tensor_spec.name
try:
te... | [
"def",
"build_or_reuse_placeholder",
"(",
"tensor_spec",
")",
":",
"g",
"=",
"tfv1",
".",
"get_default_graph",
"(",
")",
"name",
"=",
"tensor_spec",
".",
"name",
"try",
":",
"tensor",
"=",
"g",
".",
"get_tensor_by_name",
"(",
"name",
"+",
"':0'",
")",
"ass... | Build a tf.placeholder from the metadata in the given tensor spec, or return an existing one.
Args:
tensor_spec (tf.TensorSpec):
Returns:
tf.Tensor: | [
"Build",
"a",
"tf",
".",
"placeholder",
"from",
"the",
"metadata",
"in",
"the",
"given",
"tensor",
"spec",
"or",
"return",
"an",
"existing",
"one",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/graph_builder/model_desc.py#L19-L41 |
27,243 | tensorpack/tensorpack | tensorpack/tfutils/dependency.py | dependency_of_targets | def dependency_of_targets(targets, op):
"""
Check that op is in the subgraph induced by the dependencies of targets.
The result is memoized.
This is useful if some SessionRunHooks should be run only together with certain ops.
Args:
targets: a tuple of ops or tensors. The targets to find de... | python | def dependency_of_targets(targets, op):
"""
Check that op is in the subgraph induced by the dependencies of targets.
The result is memoized.
This is useful if some SessionRunHooks should be run only together with certain ops.
Args:
targets: a tuple of ops or tensors. The targets to find de... | [
"def",
"dependency_of_targets",
"(",
"targets",
",",
"op",
")",
":",
"# TODO tensorarray? sparsetensor?",
"if",
"isinstance",
"(",
"op",
",",
"tf",
".",
"Tensor",
")",
":",
"op",
"=",
"op",
".",
"op",
"assert",
"isinstance",
"(",
"op",
",",
"tf",
".",
"O... | Check that op is in the subgraph induced by the dependencies of targets.
The result is memoized.
This is useful if some SessionRunHooks should be run only together with certain ops.
Args:
targets: a tuple of ops or tensors. The targets to find dependencies of.
op (tf.Operation or tf.Tensor... | [
"Check",
"that",
"op",
"is",
"in",
"the",
"subgraph",
"induced",
"by",
"the",
"dependencies",
"of",
"targets",
".",
"The",
"result",
"is",
"memoized",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/tfutils/dependency.py#L16-L38 |
27,244 | tensorpack/tensorpack | tensorpack/tfutils/dependency.py | dependency_of_fetches | def dependency_of_fetches(fetches, op):
"""
Check that op is in the subgraph induced by the dependencies of fetches.
fetches may have more general structure.
Args:
fetches: An argument to `sess.run`. Nested structure will affect performance.
op (tf.Operation or tf.Tensor):
Returns:... | python | def dependency_of_fetches(fetches, op):
"""
Check that op is in the subgraph induced by the dependencies of fetches.
fetches may have more general structure.
Args:
fetches: An argument to `sess.run`. Nested structure will affect performance.
op (tf.Operation or tf.Tensor):
Returns:... | [
"def",
"dependency_of_fetches",
"(",
"fetches",
",",
"op",
")",
":",
"try",
":",
"from",
"tensorflow",
".",
"python",
".",
"client",
".",
"session",
"import",
"_FetchHandler",
"as",
"FetchHandler",
"# use the graph of the op, so that this function can be called without be... | Check that op is in the subgraph induced by the dependencies of fetches.
fetches may have more general structure.
Args:
fetches: An argument to `sess.run`. Nested structure will affect performance.
op (tf.Operation or tf.Tensor):
Returns:
bool: True if any of `fetches` depend on `o... | [
"Check",
"that",
"op",
"is",
"in",
"the",
"subgraph",
"induced",
"by",
"the",
"dependencies",
"of",
"fetches",
".",
"fetches",
"may",
"have",
"more",
"general",
"structure",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/tfutils/dependency.py#L41-L66 |
27,245 | tensorpack/tensorpack | tensorpack/tfutils/summary.py | add_tensor_summary | def add_tensor_summary(x, types, name=None, collections=None,
main_tower_only=True):
"""
Summarize a tensor by different methods.
Args:
x (tf.Tensor): a tensor to summarize
types (list[str]): summary types, can be scalar/histogram/sparsity/mean/rms
name (str):... | python | def add_tensor_summary(x, types, name=None, collections=None,
main_tower_only=True):
"""
Summarize a tensor by different methods.
Args:
x (tf.Tensor): a tensor to summarize
types (list[str]): summary types, can be scalar/histogram/sparsity/mean/rms
name (str):... | [
"def",
"add_tensor_summary",
"(",
"x",
",",
"types",
",",
"name",
"=",
"None",
",",
"collections",
"=",
"None",
",",
"main_tower_only",
"=",
"True",
")",
":",
"types",
"=",
"set",
"(",
"types",
")",
"if",
"name",
"is",
"None",
":",
"name",
"=",
"x",
... | Summarize a tensor by different methods.
Args:
x (tf.Tensor): a tensor to summarize
types (list[str]): summary types, can be scalar/histogram/sparsity/mean/rms
name (str): summary name. Defaults to be the op name.
collections (list[str]): collections of the summary ops.
main... | [
"Summarize",
"a",
"tensor",
"by",
"different",
"methods",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/tfutils/summary.py#L95-L137 |
27,246 | tensorpack/tensorpack | tensorpack/tfutils/summary.py | add_param_summary | def add_param_summary(*summary_lists, **kwargs):
"""
Add summary ops for all trainable variables matching the regex, under a
reused 'param-summary' name scope.
This function is a no-op if not calling from main training tower.
Args:
summary_lists (list): each is (regex, [list of summary type... | python | def add_param_summary(*summary_lists, **kwargs):
"""
Add summary ops for all trainable variables matching the regex, under a
reused 'param-summary' name scope.
This function is a no-op if not calling from main training tower.
Args:
summary_lists (list): each is (regex, [list of summary type... | [
"def",
"add_param_summary",
"(",
"*",
"summary_lists",
",",
"*",
"*",
"kwargs",
")",
":",
"collections",
"=",
"kwargs",
".",
"pop",
"(",
"'collections'",
",",
"None",
")",
"assert",
"len",
"(",
"kwargs",
")",
"==",
"0",
",",
"\"Unknown kwargs: \"",
"+",
... | Add summary ops for all trainable variables matching the regex, under a
reused 'param-summary' name scope.
This function is a no-op if not calling from main training tower.
Args:
summary_lists (list): each is (regex, [list of summary type]).
Summary type is defined in :func:`add_tensor_... | [
"Add",
"summary",
"ops",
"for",
"all",
"trainable",
"variables",
"matching",
"the",
"regex",
"under",
"a",
"reused",
"param",
"-",
"summary",
"name",
"scope",
".",
"This",
"function",
"is",
"a",
"no",
"-",
"op",
"if",
"not",
"calling",
"from",
"main",
"t... | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/tfutils/summary.py#L161-L195 |
27,247 | tensorpack/tensorpack | tensorpack/tfutils/summary.py | add_moving_summary | def add_moving_summary(*args, **kwargs):
"""
Summarize the moving average for scalar tensors.
This function is a no-op if not calling from main training tower.
Args:
args: scalar tensors to summarize
decay (float): the decay rate. Defaults to 0.95.
collection (str or None): the ... | python | def add_moving_summary(*args, **kwargs):
"""
Summarize the moving average for scalar tensors.
This function is a no-op if not calling from main training tower.
Args:
args: scalar tensors to summarize
decay (float): the decay rate. Defaults to 0.95.
collection (str or None): the ... | [
"def",
"add_moving_summary",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"decay",
"=",
"kwargs",
".",
"pop",
"(",
"'decay'",
",",
"0.95",
")",
"coll",
"=",
"kwargs",
".",
"pop",
"(",
"'collection'",
",",
"MOVING_SUMMARY_OPS_KEY",
")",
"summ_coll... | Summarize the moving average for scalar tensors.
This function is a no-op if not calling from main training tower.
Args:
args: scalar tensors to summarize
decay (float): the decay rate. Defaults to 0.95.
collection (str or None): the name of the collection to add EMA-maintaining ops.
... | [
"Summarize",
"the",
"moving",
"average",
"for",
"scalar",
"tensors",
".",
"This",
"function",
"is",
"a",
"no",
"-",
"op",
"if",
"not",
"calling",
"from",
"main",
"training",
"tower",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/tfutils/summary.py#L198-L270 |
27,248 | tensorpack/tensorpack | examples/basics/export-model.py | export_serving | def export_serving(model_path):
"""Export trained model to use it in TensorFlow Serving or cloudML. """
pred_config = PredictConfig(
session_init=get_model_loader(model_path),
model=InferenceOnlyModel(),
input_names=['input_img_bytes'],
output_names=['prediction_img_bytes'])
... | python | def export_serving(model_path):
"""Export trained model to use it in TensorFlow Serving or cloudML. """
pred_config = PredictConfig(
session_init=get_model_loader(model_path),
model=InferenceOnlyModel(),
input_names=['input_img_bytes'],
output_names=['prediction_img_bytes'])
... | [
"def",
"export_serving",
"(",
"model_path",
")",
":",
"pred_config",
"=",
"PredictConfig",
"(",
"session_init",
"=",
"get_model_loader",
"(",
"model_path",
")",
",",
"model",
"=",
"InferenceOnlyModel",
"(",
")",
",",
"input_names",
"=",
"[",
"'input_img_bytes'",
... | Export trained model to use it in TensorFlow Serving or cloudML. | [
"Export",
"trained",
"model",
"to",
"use",
"it",
"in",
"TensorFlow",
"Serving",
"or",
"cloudML",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/basics/export-model.py#L106-L113 |
27,249 | tensorpack/tensorpack | examples/basics/export-model.py | export_compact | def export_compact(model_path):
"""Export trained model to use it as a frozen and pruned inference graph in
mobile applications. """
pred_config = PredictConfig(
session_init=get_model_loader(model_path),
model=Model(),
input_names=['input_img'],
output_names=['prediction_... | python | def export_compact(model_path):
"""Export trained model to use it as a frozen and pruned inference graph in
mobile applications. """
pred_config = PredictConfig(
session_init=get_model_loader(model_path),
model=Model(),
input_names=['input_img'],
output_names=['prediction_... | [
"def",
"export_compact",
"(",
"model_path",
")",
":",
"pred_config",
"=",
"PredictConfig",
"(",
"session_init",
"=",
"get_model_loader",
"(",
"model_path",
")",
",",
"model",
"=",
"Model",
"(",
")",
",",
"input_names",
"=",
"[",
"'input_img'",
"]",
",",
"out... | Export trained model to use it as a frozen and pruned inference graph in
mobile applications. | [
"Export",
"trained",
"model",
"to",
"use",
"it",
"as",
"a",
"frozen",
"and",
"pruned",
"inference",
"graph",
"in",
"mobile",
"applications",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/basics/export-model.py#L116-L124 |
27,250 | tensorpack/tensorpack | examples/basics/export-model.py | apply | def apply(model_path):
"""Run inference from a training model checkpoint. """
pred_config = PredictConfig(
session_init=get_model_loader(model_path),
model=Model(),
input_names=['input_img'],
output_names=['prediction_img'])
pred = OfflinePredictor(pred_config)
img = cv2... | python | def apply(model_path):
"""Run inference from a training model checkpoint. """
pred_config = PredictConfig(
session_init=get_model_loader(model_path),
model=Model(),
input_names=['input_img'],
output_names=['prediction_img'])
pred = OfflinePredictor(pred_config)
img = cv2... | [
"def",
"apply",
"(",
"model_path",
")",
":",
"pred_config",
"=",
"PredictConfig",
"(",
"session_init",
"=",
"get_model_loader",
"(",
"model_path",
")",
",",
"model",
"=",
"Model",
"(",
")",
",",
"input_names",
"=",
"[",
"'input_img'",
"]",
",",
"output_names... | Run inference from a training model checkpoint. | [
"Run",
"inference",
"from",
"a",
"training",
"model",
"checkpoint",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/basics/export-model.py#L127-L138 |
27,251 | tensorpack/tensorpack | examples/basics/export-model.py | apply_inference_graph | def apply_inference_graph(model_path):
"""Run inference from a different graph, which receives encoded images buffers. """
pred_config = PredictConfig(
session_init=get_model_loader(model_path),
model=InferenceOnlyModel(),
input_names=['input_img_bytes'],
output_names=['predictio... | python | def apply_inference_graph(model_path):
"""Run inference from a different graph, which receives encoded images buffers. """
pred_config = PredictConfig(
session_init=get_model_loader(model_path),
model=InferenceOnlyModel(),
input_names=['input_img_bytes'],
output_names=['predictio... | [
"def",
"apply_inference_graph",
"(",
"model_path",
")",
":",
"pred_config",
"=",
"PredictConfig",
"(",
"session_init",
"=",
"get_model_loader",
"(",
"model_path",
")",
",",
"model",
"=",
"InferenceOnlyModel",
"(",
")",
",",
"input_names",
"=",
"[",
"'input_img_byt... | Run inference from a different graph, which receives encoded images buffers. | [
"Run",
"inference",
"from",
"a",
"different",
"graph",
"which",
"receives",
"encoded",
"images",
"buffers",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/basics/export-model.py#L141-L153 |
27,252 | tensorpack/tensorpack | examples/basics/export-model.py | apply_compact | def apply_compact(graph_path):
"""Run the pruned and frozen inference graph. """
with tf.Session(config=tf.ConfigProto(allow_soft_placement=True)) as sess:
# Note, we just load the graph and do *not* need to initialize anything.
with tf.gfile.GFile(graph_path, "rb") as f:
graph_def =... | python | def apply_compact(graph_path):
"""Run the pruned and frozen inference graph. """
with tf.Session(config=tf.ConfigProto(allow_soft_placement=True)) as sess:
# Note, we just load the graph and do *not* need to initialize anything.
with tf.gfile.GFile(graph_path, "rb") as f:
graph_def =... | [
"def",
"apply_compact",
"(",
"graph_path",
")",
":",
"with",
"tf",
".",
"Session",
"(",
"config",
"=",
"tf",
".",
"ConfigProto",
"(",
"allow_soft_placement",
"=",
"True",
")",
")",
"as",
"sess",
":",
"# Note, we just load the graph and do *not* need to initialize an... | Run the pruned and frozen inference graph. | [
"Run",
"the",
"pruned",
"and",
"frozen",
"inference",
"graph",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/basics/export-model.py#L156-L169 |
27,253 | tensorpack/tensorpack | tensorpack/dataflow/common.py | PrintData._analyze_input_data | def _analyze_input_data(self, entry, k, depth=1, max_depth=3, max_list=3):
"""
Gather useful debug information from a datapoint.
Args:
entry: the datapoint component
k (int): index of this component in current datapoint
depth (int, optional): recursion depth
... | python | def _analyze_input_data(self, entry, k, depth=1, max_depth=3, max_list=3):
"""
Gather useful debug information from a datapoint.
Args:
entry: the datapoint component
k (int): index of this component in current datapoint
depth (int, optional): recursion depth
... | [
"def",
"_analyze_input_data",
"(",
"self",
",",
"entry",
",",
"k",
",",
"depth",
"=",
"1",
",",
"max_depth",
"=",
"3",
",",
"max_list",
"=",
"3",
")",
":",
"class",
"_elementInfo",
"(",
"object",
")",
":",
"def",
"__init__",
"(",
"self",
",",
"el",
... | Gather useful debug information from a datapoint.
Args:
entry: the datapoint component
k (int): index of this component in current datapoint
depth (int, optional): recursion depth
max_depth, max_list: same as in :meth:`__init__`.
Returns:
str... | [
"Gather",
"useful",
"debug",
"information",
"from",
"a",
"datapoint",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/dataflow/common.py#L745-L804 |
27,254 | tensorpack/tensorpack | tensorpack/tfutils/optimizer.py | apply_grad_processors | def apply_grad_processors(opt, gradprocs):
"""
Wrapper around optimizers to apply gradient processors.
Args:
opt (tf.train.Optimizer):
gradprocs (list[GradientProcessor]): gradient processors to add to the
optimizer.
Returns:
a :class:`tf.train.Optimizer` instance w... | python | def apply_grad_processors(opt, gradprocs):
"""
Wrapper around optimizers to apply gradient processors.
Args:
opt (tf.train.Optimizer):
gradprocs (list[GradientProcessor]): gradient processors to add to the
optimizer.
Returns:
a :class:`tf.train.Optimizer` instance w... | [
"def",
"apply_grad_processors",
"(",
"opt",
",",
"gradprocs",
")",
":",
"assert",
"isinstance",
"(",
"gradprocs",
",",
"(",
"list",
",",
"tuple",
")",
")",
",",
"gradprocs",
"for",
"gp",
"in",
"gradprocs",
":",
"assert",
"isinstance",
"(",
"gp",
",",
"Gr... | Wrapper around optimizers to apply gradient processors.
Args:
opt (tf.train.Optimizer):
gradprocs (list[GradientProcessor]): gradient processors to add to the
optimizer.
Returns:
a :class:`tf.train.Optimizer` instance which runs the gradient
processors before updati... | [
"Wrapper",
"around",
"optimizers",
"to",
"apply",
"gradient",
"processors",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/tfutils/optimizer.py#L44-L76 |
27,255 | tensorpack/tensorpack | examples/FasterRCNN/eval.py | multithread_predict_dataflow | def multithread_predict_dataflow(dataflows, model_funcs):
"""
Running multiple `predict_dataflow` in multiple threads, and aggregate the results.
Args:
dataflows: a list of DataFlow to be used in :func:`predict_dataflow`
model_funcs: a list of callable to be used in :func:`predict_dataflow`... | python | def multithread_predict_dataflow(dataflows, model_funcs):
"""
Running multiple `predict_dataflow` in multiple threads, and aggregate the results.
Args:
dataflows: a list of DataFlow to be used in :func:`predict_dataflow`
model_funcs: a list of callable to be used in :func:`predict_dataflow`... | [
"def",
"multithread_predict_dataflow",
"(",
"dataflows",
",",
"model_funcs",
")",
":",
"num_worker",
"=",
"len",
"(",
"model_funcs",
")",
"assert",
"len",
"(",
"dataflows",
")",
"==",
"num_worker",
"if",
"num_worker",
"==",
"1",
":",
"return",
"predict_dataflow"... | Running multiple `predict_dataflow` in multiple threads, and aggregate the results.
Args:
dataflows: a list of DataFlow to be used in :func:`predict_dataflow`
model_funcs: a list of callable to be used in :func:`predict_dataflow`
Returns:
list of dict, in the format used by
`De... | [
"Running",
"multiple",
"predict_dataflow",
"in",
"multiple",
"threads",
"and",
"aggregate",
"the",
"results",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/eval.py#L149-L172 |
27,256 | tensorpack/tensorpack | tensorpack/models/fc.py | batch_flatten | def batch_flatten(x):
"""
Flatten the tensor except the first dimension.
"""
shape = x.get_shape().as_list()[1:]
if None not in shape:
return tf.reshape(x, [-1, int(np.prod(shape))])
return tf.reshape(x, tf.stack([tf.shape(x)[0], -1])) | python | def batch_flatten(x):
"""
Flatten the tensor except the first dimension.
"""
shape = x.get_shape().as_list()[1:]
if None not in shape:
return tf.reshape(x, [-1, int(np.prod(shape))])
return tf.reshape(x, tf.stack([tf.shape(x)[0], -1])) | [
"def",
"batch_flatten",
"(",
"x",
")",
":",
"shape",
"=",
"x",
".",
"get_shape",
"(",
")",
".",
"as_list",
"(",
")",
"[",
"1",
":",
"]",
"if",
"None",
"not",
"in",
"shape",
":",
"return",
"tf",
".",
"reshape",
"(",
"x",
",",
"[",
"-",
"1",
",... | Flatten the tensor except the first dimension. | [
"Flatten",
"the",
"tensor",
"except",
"the",
"first",
"dimension",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/models/fc.py#L15-L22 |
27,257 | tensorpack/tensorpack | tensorpack/predict/concurrency.py | MultiProcessPredictWorker._init_runtime | def _init_runtime(self):
""" Call _init_runtime under different CUDA_VISIBLE_DEVICES, you'll
have workers that run on multiGPUs
"""
if self.idx != 0:
from tensorpack.models.registry import disable_layer_logging
disable_layer_logging()
self.predictor = ... | python | def _init_runtime(self):
""" Call _init_runtime under different CUDA_VISIBLE_DEVICES, you'll
have workers that run on multiGPUs
"""
if self.idx != 0:
from tensorpack.models.registry import disable_layer_logging
disable_layer_logging()
self.predictor = ... | [
"def",
"_init_runtime",
"(",
"self",
")",
":",
"if",
"self",
".",
"idx",
"!=",
"0",
":",
"from",
"tensorpack",
".",
"models",
".",
"registry",
"import",
"disable_layer_logging",
"disable_layer_logging",
"(",
")",
"self",
".",
"predictor",
"=",
"OfflinePredicto... | Call _init_runtime under different CUDA_VISIBLE_DEVICES, you'll
have workers that run on multiGPUs | [
"Call",
"_init_runtime",
"under",
"different",
"CUDA_VISIBLE_DEVICES",
"you",
"ll",
"have",
"workers",
"that",
"run",
"on",
"multiGPUs"
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/predict/concurrency.py#L35-L45 |
27,258 | tensorpack/tensorpack | tensorpack/predict/concurrency.py | PredictorWorkerThread.fetch_batch | def fetch_batch(self):
""" Fetch a batch of data without waiting"""
inp, f = self.queue.get()
nr_input_var = len(inp)
batched, futures = [[] for _ in range(nr_input_var)], []
for k in range(nr_input_var):
batched[k].append(inp[k])
futures.append(f)
whi... | python | def fetch_batch(self):
""" Fetch a batch of data without waiting"""
inp, f = self.queue.get()
nr_input_var = len(inp)
batched, futures = [[] for _ in range(nr_input_var)], []
for k in range(nr_input_var):
batched[k].append(inp[k])
futures.append(f)
whi... | [
"def",
"fetch_batch",
"(",
"self",
")",
":",
"inp",
",",
"f",
"=",
"self",
".",
"queue",
".",
"get",
"(",
")",
"nr_input_var",
"=",
"len",
"(",
"inp",
")",
"batched",
",",
"futures",
"=",
"[",
"[",
"]",
"for",
"_",
"in",
"range",
"(",
"nr_input_v... | Fetch a batch of data without waiting | [
"Fetch",
"a",
"batch",
"of",
"data",
"without",
"waiting"
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/predict/concurrency.py#L110-L129 |
27,259 | tensorpack/tensorpack | examples/GAN/DCGAN.py | Model.generator | def generator(self, z):
""" return an image generated from z"""
nf = 64
l = FullyConnected('fc0', z, nf * 8 * 4 * 4, activation=tf.identity)
l = tf.reshape(l, [-1, 4, 4, nf * 8])
l = BNReLU(l)
with argscope(Conv2DTranspose, activation=BNReLU, kernel_size=4, strides=2):
... | python | def generator(self, z):
""" return an image generated from z"""
nf = 64
l = FullyConnected('fc0', z, nf * 8 * 4 * 4, activation=tf.identity)
l = tf.reshape(l, [-1, 4, 4, nf * 8])
l = BNReLU(l)
with argscope(Conv2DTranspose, activation=BNReLU, kernel_size=4, strides=2):
... | [
"def",
"generator",
"(",
"self",
",",
"z",
")",
":",
"nf",
"=",
"64",
"l",
"=",
"FullyConnected",
"(",
"'fc0'",
",",
"z",
",",
"nf",
"*",
"8",
"*",
"4",
"*",
"4",
",",
"activation",
"=",
"tf",
".",
"identity",
")",
"l",
"=",
"tf",
".",
"resha... | return an image generated from z | [
"return",
"an",
"image",
"generated",
"from",
"z"
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/GAN/DCGAN.py#L46-L58 |
27,260 | tensorpack/tensorpack | tensorpack/models/nonlin.py | BNReLU | def BNReLU(x, name=None):
"""
A shorthand of BatchNormalization + ReLU.
"""
x = BatchNorm('bn', x)
x = tf.nn.relu(x, name=name)
return x | python | def BNReLU(x, name=None):
"""
A shorthand of BatchNormalization + ReLU.
"""
x = BatchNorm('bn', x)
x = tf.nn.relu(x, name=name)
return x | [
"def",
"BNReLU",
"(",
"x",
",",
"name",
"=",
"None",
")",
":",
"x",
"=",
"BatchNorm",
"(",
"'bn'",
",",
"x",
")",
"x",
"=",
"tf",
".",
"nn",
".",
"relu",
"(",
"x",
",",
"name",
"=",
"name",
")",
"return",
"x"
] | A shorthand of BatchNormalization + ReLU. | [
"A",
"shorthand",
"of",
"BatchNormalization",
"+",
"ReLU",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/models/nonlin.py#L64-L70 |
27,261 | tensorpack/tensorpack | tensorpack/utils/develop.py | create_dummy_class | def create_dummy_class(klass, dependency):
"""
When a dependency of a class is not available, create a dummy class which throws ImportError when used.
Args:
klass (str): name of the class.
dependency (str): name of the dependency.
Returns:
class: a class object
"""
asse... | python | def create_dummy_class(klass, dependency):
"""
When a dependency of a class is not available, create a dummy class which throws ImportError when used.
Args:
klass (str): name of the class.
dependency (str): name of the dependency.
Returns:
class: a class object
"""
asse... | [
"def",
"create_dummy_class",
"(",
"klass",
",",
"dependency",
")",
":",
"assert",
"not",
"building_rtfd",
"(",
")",
"class",
"_DummyMetaClass",
"(",
"type",
")",
":",
"# throw error on class attribute access",
"def",
"__getattr__",
"(",
"_",
",",
"__",
")",
":",... | When a dependency of a class is not available, create a dummy class which throws ImportError when used.
Args:
klass (str): name of the class.
dependency (str): name of the dependency.
Returns:
class: a class object | [
"When",
"a",
"dependency",
"of",
"a",
"class",
"is",
"not",
"available",
"create",
"a",
"dummy",
"class",
"which",
"throws",
"ImportError",
"when",
"used",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/develop.py#L21-L45 |
27,262 | tensorpack/tensorpack | tensorpack/utils/develop.py | create_dummy_func | def create_dummy_func(func, dependency):
"""
When a dependency of a function is not available, create a dummy function which throws ImportError when used.
Args:
func (str): name of the function.
dependency (str or list[str]): name(s) of the dependency.
Returns:
function: a func... | python | def create_dummy_func(func, dependency):
"""
When a dependency of a function is not available, create a dummy function which throws ImportError when used.
Args:
func (str): name of the function.
dependency (str or list[str]): name(s) of the dependency.
Returns:
function: a func... | [
"def",
"create_dummy_func",
"(",
"func",
",",
"dependency",
")",
":",
"assert",
"not",
"building_rtfd",
"(",
")",
"if",
"isinstance",
"(",
"dependency",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"dependency",
"=",
"','",
".",
"join",
"(",
"dependenc... | When a dependency of a function is not available, create a dummy function which throws ImportError when used.
Args:
func (str): name of the function.
dependency (str or list[str]): name(s) of the dependency.
Returns:
function: a function object | [
"When",
"a",
"dependency",
"of",
"a",
"function",
"is",
"not",
"available",
"create",
"a",
"dummy",
"function",
"which",
"throws",
"ImportError",
"when",
"used",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/develop.py#L48-L66 |
27,263 | tensorpack/tensorpack | tensorpack/utils/develop.py | log_deprecated | def log_deprecated(name="", text="", eos=""):
"""
Log deprecation warning.
Args:
name (str): name of the deprecated item.
text (str, optional): information about the deprecation.
eos (str, optional): end of service date such as "YYYY-MM-DD".
"""
assert name or text
if eo... | python | def log_deprecated(name="", text="", eos=""):
"""
Log deprecation warning.
Args:
name (str): name of the deprecated item.
text (str, optional): information about the deprecation.
eos (str, optional): end of service date such as "YYYY-MM-DD".
"""
assert name or text
if eo... | [
"def",
"log_deprecated",
"(",
"name",
"=",
"\"\"",
",",
"text",
"=",
"\"\"",
",",
"eos",
"=",
"\"\"",
")",
":",
"assert",
"name",
"or",
"text",
"if",
"eos",
":",
"eos",
"=",
"\"after \"",
"+",
"datetime",
"(",
"*",
"map",
"(",
"int",
",",
"eos",
... | Log deprecation warning.
Args:
name (str): name of the deprecated item.
text (str, optional): information about the deprecation.
eos (str, optional): end of service date such as "YYYY-MM-DD". | [
"Log",
"deprecation",
"warning",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/develop.py#L78-L99 |
27,264 | tensorpack/tensorpack | tensorpack/input_source/input_source.py | QueueInput._create_ema_callback | def _create_ema_callback(self):
"""
Create a hook-only callback which maintain EMA of the queue size.
Also tf.summary.scalar the EMA.
"""
with self.cached_name_scope():
# in TF there is no API to get queue capacity, so we can only summary the size
size = t... | python | def _create_ema_callback(self):
"""
Create a hook-only callback which maintain EMA of the queue size.
Also tf.summary.scalar the EMA.
"""
with self.cached_name_scope():
# in TF there is no API to get queue capacity, so we can only summary the size
size = t... | [
"def",
"_create_ema_callback",
"(",
"self",
")",
":",
"with",
"self",
".",
"cached_name_scope",
"(",
")",
":",
"# in TF there is no API to get queue capacity, so we can only summary the size",
"size",
"=",
"tf",
".",
"cast",
"(",
"self",
".",
"queue",
".",
"size",
"... | Create a hook-only callback which maintain EMA of the queue size.
Also tf.summary.scalar the EMA. | [
"Create",
"a",
"hook",
"-",
"only",
"callback",
"which",
"maintain",
"EMA",
"of",
"the",
"queue",
"size",
".",
"Also",
"tf",
".",
"summary",
".",
"scalar",
"the",
"EMA",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/input_source/input_source.py#L248-L263 |
27,265 | tensorpack/tensorpack | tensorpack/input_source/input_source.py | BatchQueueInput._setup | def _setup(self, inputs):
logger.info("Setting up the queue for CPU prefetching ...")
self.input_placehdrs = [build_or_reuse_placeholder(v) for v in inputs]
assert len(self.input_placehdrs) > 0, \
"BatchQueueInput has to be used with some input signature!"
# prepare placehol... | python | def _setup(self, inputs):
logger.info("Setting up the queue for CPU prefetching ...")
self.input_placehdrs = [build_or_reuse_placeholder(v) for v in inputs]
assert len(self.input_placehdrs) > 0, \
"BatchQueueInput has to be used with some input signature!"
# prepare placehol... | [
"def",
"_setup",
"(",
"self",
",",
"inputs",
")",
":",
"logger",
".",
"info",
"(",
"\"Setting up the queue for CPU prefetching ...\"",
")",
"self",
".",
"input_placehdrs",
"=",
"[",
"build_or_reuse_placeholder",
"(",
"v",
")",
"for",
"v",
"in",
"inputs",
"]",
... | shapes except for the batch dimension | [
"shapes",
"except",
"for",
"the",
"batch",
"dimension"
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/input_source/input_source.py#L301-L331 |
27,266 | tensorpack/tensorpack | tensorpack/input_source/input_source.py | TFDatasetInput.dataflow_to_dataset | def dataflow_to_dataset(df, types):
"""
Wrap a dataflow to tf.data.Dataset.
This function will also reset the dataflow.
If the dataflow itself is finite, the returned dataset is also finite.
Therefore, if used for training, you'll need to add `.repeat()` on the returned
... | python | def dataflow_to_dataset(df, types):
"""
Wrap a dataflow to tf.data.Dataset.
This function will also reset the dataflow.
If the dataflow itself is finite, the returned dataset is also finite.
Therefore, if used for training, you'll need to add `.repeat()` on the returned
... | [
"def",
"dataflow_to_dataset",
"(",
"df",
",",
"types",
")",
":",
"# TODO theoretically it can support dict",
"assert",
"isinstance",
"(",
"df",
",",
"DataFlow",
")",
",",
"df",
"assert",
"isinstance",
"(",
"types",
",",
"(",
"list",
",",
"tuple",
")",
")",
"... | Wrap a dataflow to tf.data.Dataset.
This function will also reset the dataflow.
If the dataflow itself is finite, the returned dataset is also finite.
Therefore, if used for training, you'll need to add `.repeat()` on the returned
dataset.
Args:
df (DataFlow): a dat... | [
"Wrap",
"a",
"dataflow",
"to",
"tf",
".",
"data",
".",
"Dataset",
".",
"This",
"function",
"will",
"also",
"reset",
"the",
"dataflow",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/input_source/input_source.py#L496-L519 |
27,267 | tensorpack/tensorpack | examples/FasterRCNN/utils/np_box_ops.py | ioa | def ioa(boxes1, boxes2):
"""Computes pairwise intersection-over-area between box collections.
Intersection-over-area (ioa) between two boxes box1 and box2 is defined as
their intersection area over box2's area. Note that ioa is not symmetric,
that is, IOA(box1, box2) != IOA(box2, box1).
Args:
boxes1: a ... | python | def ioa(boxes1, boxes2):
"""Computes pairwise intersection-over-area between box collections.
Intersection-over-area (ioa) between two boxes box1 and box2 is defined as
their intersection area over box2's area. Note that ioa is not symmetric,
that is, IOA(box1, box2) != IOA(box2, box1).
Args:
boxes1: a ... | [
"def",
"ioa",
"(",
"boxes1",
",",
"boxes2",
")",
":",
"intersect",
"=",
"intersection",
"(",
"boxes1",
",",
"boxes2",
")",
"inv_areas",
"=",
"np",
".",
"expand_dims",
"(",
"1.0",
"/",
"area",
"(",
"boxes2",
")",
",",
"axis",
"=",
"0",
")",
"return",
... | Computes pairwise intersection-over-area between box collections.
Intersection-over-area (ioa) between two boxes box1 and box2 is defined as
their intersection area over box2's area. Note that ioa is not symmetric,
that is, IOA(box1, box2) != IOA(box2, box1).
Args:
boxes1: a numpy array with shape [N, 4] ... | [
"Computes",
"pairwise",
"intersection",
"-",
"over",
"-",
"area",
"between",
"box",
"collections",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/utils/np_box_ops.py#L81-L97 |
27,268 | tensorpack/tensorpack | tensorpack/dataflow/dataset/caltech101.py | maybe_download | def maybe_download(url, work_directory):
"""Download the data from Marlin's website, unless it's already here."""
filename = url.split("/")[-1]
filepath = os.path.join(work_directory, filename)
if not os.path.exists(filepath):
logger.info("Downloading to {}...".format(filepath))
download... | python | def maybe_download(url, work_directory):
"""Download the data from Marlin's website, unless it's already here."""
filename = url.split("/")[-1]
filepath = os.path.join(work_directory, filename)
if not os.path.exists(filepath):
logger.info("Downloading to {}...".format(filepath))
download... | [
"def",
"maybe_download",
"(",
"url",
",",
"work_directory",
")",
":",
"filename",
"=",
"url",
".",
"split",
"(",
"\"/\"",
")",
"[",
"-",
"1",
"]",
"filepath",
"=",
"os",
".",
"path",
".",
"join",
"(",
"work_directory",
",",
"filename",
")",
"if",
"no... | Download the data from Marlin's website, unless it's already here. | [
"Download",
"the",
"data",
"from",
"Marlin",
"s",
"website",
"unless",
"it",
"s",
"already",
"here",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/dataflow/dataset/caltech101.py#L15-L22 |
27,269 | tensorpack/tensorpack | tensorpack/dataflow/dataset/ilsvrc.py | ILSVRCMeta.guess_dir_structure | def guess_dir_structure(dir):
"""
Return the directory structure of "dir".
Args:
dir(str): something like '/path/to/imagenet/val'
Returns:
either 'train' or 'original'
"""
subdir = os.listdir(dir)[0]
# find a subdir starting with 'n'
... | python | def guess_dir_structure(dir):
"""
Return the directory structure of "dir".
Args:
dir(str): something like '/path/to/imagenet/val'
Returns:
either 'train' or 'original'
"""
subdir = os.listdir(dir)[0]
# find a subdir starting with 'n'
... | [
"def",
"guess_dir_structure",
"(",
"dir",
")",
":",
"subdir",
"=",
"os",
".",
"listdir",
"(",
"dir",
")",
"[",
"0",
"]",
"# find a subdir starting with 'n'",
"if",
"subdir",
".",
"startswith",
"(",
"'n'",
")",
"and",
"os",
".",
"path",
".",
"isdir",
"(",... | Return the directory structure of "dir".
Args:
dir(str): something like '/path/to/imagenet/val'
Returns:
either 'train' or 'original' | [
"Return",
"the",
"directory",
"structure",
"of",
"dir",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/dataflow/dataset/ilsvrc.py#L109-L129 |
27,270 | tensorpack/tensorpack | examples/FasterRCNN/dataset.py | COCODetection._use_absolute_file_name | def _use_absolute_file_name(self, img):
"""
Change relative filename to abosolute file name.
"""
img['file_name'] = os.path.join(
self._imgdir, img['file_name'])
assert os.path.isfile(img['file_name']), img['file_name'] | python | def _use_absolute_file_name(self, img):
"""
Change relative filename to abosolute file name.
"""
img['file_name'] = os.path.join(
self._imgdir, img['file_name'])
assert os.path.isfile(img['file_name']), img['file_name'] | [
"def",
"_use_absolute_file_name",
"(",
"self",
",",
"img",
")",
":",
"img",
"[",
"'file_name'",
"]",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"_imgdir",
",",
"img",
"[",
"'file_name'",
"]",
")",
"assert",
"os",
".",
"path",
".",
"isfile... | Change relative filename to abosolute file name. | [
"Change",
"relative",
"filename",
"to",
"abosolute",
"file",
"name",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/dataset.py#L104-L110 |
27,271 | tensorpack/tensorpack | examples/FasterRCNN/dataset.py | COCODetection._add_detection_gt | def _add_detection_gt(self, img, add_mask):
"""
Add 'boxes', 'class', 'is_crowd' of this image to the dict, used by detection.
If add_mask is True, also add 'segmentation' in coco poly format.
"""
# ann_ids = self.coco.getAnnIds(imgIds=img['image_id'])
# objs = self.coco.... | python | def _add_detection_gt(self, img, add_mask):
"""
Add 'boxes', 'class', 'is_crowd' of this image to the dict, used by detection.
If add_mask is True, also add 'segmentation' in coco poly format.
"""
# ann_ids = self.coco.getAnnIds(imgIds=img['image_id'])
# objs = self.coco.... | [
"def",
"_add_detection_gt",
"(",
"self",
",",
"img",
",",
"add_mask",
")",
":",
"# ann_ids = self.coco.getAnnIds(imgIds=img['image_id'])",
"# objs = self.coco.loadAnns(ann_ids)",
"objs",
"=",
"self",
".",
"coco",
".",
"imgToAnns",
"[",
"img",
"[",
"'image_id'",
"]",
"... | Add 'boxes', 'class', 'is_crowd' of this image to the dict, used by detection.
If add_mask is True, also add 'segmentation' in coco poly format. | [
"Add",
"boxes",
"class",
"is_crowd",
"of",
"this",
"image",
"to",
"the",
"dict",
"used",
"by",
"detection",
".",
"If",
"add_mask",
"is",
"True",
"also",
"add",
"segmentation",
"in",
"coco",
"poly",
"format",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/dataset.py#L112-L170 |
27,272 | tensorpack/tensorpack | examples/FasterRCNN/dataset.py | COCODetection.load_many | def load_many(basedir, names, add_gt=True, add_mask=False):
"""
Load and merges several instance files together.
Returns the same format as :meth:`COCODetection.load`.
"""
if not isinstance(names, (list, tuple)):
names = [names]
ret = []
for n in name... | python | def load_many(basedir, names, add_gt=True, add_mask=False):
"""
Load and merges several instance files together.
Returns the same format as :meth:`COCODetection.load`.
"""
if not isinstance(names, (list, tuple)):
names = [names]
ret = []
for n in name... | [
"def",
"load_many",
"(",
"basedir",
",",
"names",
",",
"add_gt",
"=",
"True",
",",
"add_mask",
"=",
"False",
")",
":",
"if",
"not",
"isinstance",
"(",
"names",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"names",
"=",
"[",
"names",
"]",
"ret",
... | Load and merges several instance files together.
Returns the same format as :meth:`COCODetection.load`. | [
"Load",
"and",
"merges",
"several",
"instance",
"files",
"together",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/dataset.py#L173-L185 |
27,273 | tensorpack/tensorpack | tensorpack/utils/timer.py | timed_operation | def timed_operation(msg, log_start=False):
"""
Surround a context with a timer.
Args:
msg(str): the log to print.
log_start(bool): whether to print also at the beginning.
Example:
.. code-block:: python
with timed_operation('Good Stuff'):
time.sleep... | python | def timed_operation(msg, log_start=False):
"""
Surround a context with a timer.
Args:
msg(str): the log to print.
log_start(bool): whether to print also at the beginning.
Example:
.. code-block:: python
with timed_operation('Good Stuff'):
time.sleep... | [
"def",
"timed_operation",
"(",
"msg",
",",
"log_start",
"=",
"False",
")",
":",
"assert",
"len",
"(",
"msg",
")",
"if",
"log_start",
":",
"logger",
".",
"info",
"(",
"'Start {} ...'",
".",
"format",
"(",
"msg",
")",
")",
"start",
"=",
"timer",
"(",
"... | Surround a context with a timer.
Args:
msg(str): the log to print.
log_start(bool): whether to print also at the beginning.
Example:
.. code-block:: python
with timed_operation('Good Stuff'):
time.sleep(1)
Will print:
.. code-block:: pytho... | [
"Surround",
"a",
"context",
"with",
"a",
"timer",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/timer.py#L23-L50 |
27,274 | tensorpack/tensorpack | tensorpack/utils/timer.py | total_timer | def total_timer(msg):
""" A context which add the time spent inside to TotalTimer. """
start = timer()
yield
t = timer() - start
_TOTAL_TIMER_DATA[msg].feed(t) | python | def total_timer(msg):
""" A context which add the time spent inside to TotalTimer. """
start = timer()
yield
t = timer() - start
_TOTAL_TIMER_DATA[msg].feed(t) | [
"def",
"total_timer",
"(",
"msg",
")",
":",
"start",
"=",
"timer",
"(",
")",
"yield",
"t",
"=",
"timer",
"(",
")",
"-",
"start",
"_TOTAL_TIMER_DATA",
"[",
"msg",
"]",
".",
"feed",
"(",
"t",
")"
] | A context which add the time spent inside to TotalTimer. | [
"A",
"context",
"which",
"add",
"the",
"time",
"spent",
"inside",
"to",
"TotalTimer",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/timer.py#L57-L62 |
27,275 | tensorpack/tensorpack | tensorpack/utils/timer.py | print_total_timer | def print_total_timer():
"""
Print the content of the TotalTimer, if it's not empty. This function will automatically get
called when program exits.
"""
if len(_TOTAL_TIMER_DATA) == 0:
return
for k, v in six.iteritems(_TOTAL_TIMER_DATA):
logger.info("Total Time: {} -> {:.2f} sec,... | python | def print_total_timer():
"""
Print the content of the TotalTimer, if it's not empty. This function will automatically get
called when program exits.
"""
if len(_TOTAL_TIMER_DATA) == 0:
return
for k, v in six.iteritems(_TOTAL_TIMER_DATA):
logger.info("Total Time: {} -> {:.2f} sec,... | [
"def",
"print_total_timer",
"(",
")",
":",
"if",
"len",
"(",
"_TOTAL_TIMER_DATA",
")",
"==",
"0",
":",
"return",
"for",
"k",
",",
"v",
"in",
"six",
".",
"iteritems",
"(",
"_TOTAL_TIMER_DATA",
")",
":",
"logger",
".",
"info",
"(",
"\"Total Time: {} -> {:.2f... | Print the content of the TotalTimer, if it's not empty. This function will automatically get
called when program exits. | [
"Print",
"the",
"content",
"of",
"the",
"TotalTimer",
"if",
"it",
"s",
"not",
"empty",
".",
"This",
"function",
"will",
"automatically",
"get",
"called",
"when",
"program",
"exits",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/timer.py#L65-L74 |
27,276 | tensorpack/tensorpack | tensorpack/dataflow/imgaug/base.py | AugmentorList.reset_state | def reset_state(self):
""" Will reset state of each augmentor """
super(AugmentorList, self).reset_state()
for a in self.augmentors:
a.reset_state() | python | def reset_state(self):
""" Will reset state of each augmentor """
super(AugmentorList, self).reset_state()
for a in self.augmentors:
a.reset_state() | [
"def",
"reset_state",
"(",
"self",
")",
":",
"super",
"(",
"AugmentorList",
",",
"self",
")",
".",
"reset_state",
"(",
")",
"for",
"a",
"in",
"self",
".",
"augmentors",
":",
"a",
".",
"reset_state",
"(",
")"
] | Will reset state of each augmentor | [
"Will",
"reset",
"state",
"of",
"each",
"augmentor"
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/dataflow/imgaug/base.py#L224-L228 |
27,277 | tensorpack/tensorpack | tensorpack/utils/concurrency.py | ensure_proc_terminate | def ensure_proc_terminate(proc):
"""
Make sure processes terminate when main process exit.
Args:
proc (multiprocessing.Process or list)
"""
if isinstance(proc, list):
for p in proc:
ensure_proc_terminate(p)
return
def stop_proc_by_weak_ref(ref):
proc... | python | def ensure_proc_terminate(proc):
"""
Make sure processes terminate when main process exit.
Args:
proc (multiprocessing.Process or list)
"""
if isinstance(proc, list):
for p in proc:
ensure_proc_terminate(p)
return
def stop_proc_by_weak_ref(ref):
proc... | [
"def",
"ensure_proc_terminate",
"(",
"proc",
")",
":",
"if",
"isinstance",
"(",
"proc",
",",
"list",
")",
":",
"for",
"p",
"in",
"proc",
":",
"ensure_proc_terminate",
"(",
"p",
")",
"return",
"def",
"stop_proc_by_weak_ref",
"(",
"ref",
")",
":",
"proc",
... | Make sure processes terminate when main process exit.
Args:
proc (multiprocessing.Process or list) | [
"Make",
"sure",
"processes",
"terminate",
"when",
"main",
"process",
"exit",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/concurrency.py#L152-L174 |
27,278 | tensorpack/tensorpack | tensorpack/utils/concurrency.py | enable_death_signal | def enable_death_signal(_warn=True):
"""
Set the "death signal" of the current process, so that
the current process will be cleaned with guarantee
in case the parent dies accidentally.
"""
if platform.system() != 'Linux':
return
try:
import prctl # pip install python-prctl... | python | def enable_death_signal(_warn=True):
"""
Set the "death signal" of the current process, so that
the current process will be cleaned with guarantee
in case the parent dies accidentally.
"""
if platform.system() != 'Linux':
return
try:
import prctl # pip install python-prctl... | [
"def",
"enable_death_signal",
"(",
"_warn",
"=",
"True",
")",
":",
"if",
"platform",
".",
"system",
"(",
")",
"!=",
"'Linux'",
":",
"return",
"try",
":",
"import",
"prctl",
"# pip install python-prctl",
"except",
"ImportError",
":",
"if",
"_warn",
":",
"log_... | Set the "death signal" of the current process, so that
the current process will be cleaned with guarantee
in case the parent dies accidentally. | [
"Set",
"the",
"death",
"signal",
"of",
"the",
"current",
"process",
"so",
"that",
"the",
"current",
"process",
"will",
"be",
"cleaned",
"with",
"guarantee",
"in",
"case",
"the",
"parent",
"dies",
"accidentally",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/concurrency.py#L177-L196 |
27,279 | tensorpack/tensorpack | tensorpack/utils/concurrency.py | subproc_call | def subproc_call(cmd, timeout=None):
"""
Execute a command with timeout, and return STDOUT and STDERR
Args:
cmd(str): the command to execute.
timeout(float): timeout in seconds.
Returns:
output(bytes), retcode(int). If timeout, retcode is -1.
"""
try:
output = s... | python | def subproc_call(cmd, timeout=None):
"""
Execute a command with timeout, and return STDOUT and STDERR
Args:
cmd(str): the command to execute.
timeout(float): timeout in seconds.
Returns:
output(bytes), retcode(int). If timeout, retcode is -1.
"""
try:
output = s... | [
"def",
"subproc_call",
"(",
"cmd",
",",
"timeout",
"=",
"None",
")",
":",
"try",
":",
"output",
"=",
"subprocess",
".",
"check_output",
"(",
"cmd",
",",
"stderr",
"=",
"subprocess",
".",
"STDOUT",
",",
"shell",
"=",
"True",
",",
"timeout",
"=",
"timeou... | Execute a command with timeout, and return STDOUT and STDERR
Args:
cmd(str): the command to execute.
timeout(float): timeout in seconds.
Returns:
output(bytes), retcode(int). If timeout, retcode is -1. | [
"Execute",
"a",
"command",
"with",
"timeout",
"and",
"return",
"STDOUT",
"and",
"STDERR"
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/concurrency.py#L247-L273 |
27,280 | tensorpack/tensorpack | tensorpack/utils/concurrency.py | StoppableThread.queue_put_stoppable | def queue_put_stoppable(self, q, obj):
""" Put obj to queue, but will give up when the thread is stopped"""
while not self.stopped():
try:
q.put(obj, timeout=5)
break
except queue.Full:
pass | python | def queue_put_stoppable(self, q, obj):
""" Put obj to queue, but will give up when the thread is stopped"""
while not self.stopped():
try:
q.put(obj, timeout=5)
break
except queue.Full:
pass | [
"def",
"queue_put_stoppable",
"(",
"self",
",",
"q",
",",
"obj",
")",
":",
"while",
"not",
"self",
".",
"stopped",
"(",
")",
":",
"try",
":",
"q",
".",
"put",
"(",
"obj",
",",
"timeout",
"=",
"5",
")",
"break",
"except",
"queue",
".",
"Full",
":"... | Put obj to queue, but will give up when the thread is stopped | [
"Put",
"obj",
"to",
"queue",
"but",
"will",
"give",
"up",
"when",
"the",
"thread",
"is",
"stopped"
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/concurrency.py#L59-L66 |
27,281 | tensorpack/tensorpack | tensorpack/utils/concurrency.py | StoppableThread.queue_get_stoppable | def queue_get_stoppable(self, q):
""" Take obj from queue, but will give up when the thread is stopped"""
while not self.stopped():
try:
return q.get(timeout=5)
except queue.Empty:
pass | python | def queue_get_stoppable(self, q):
""" Take obj from queue, but will give up when the thread is stopped"""
while not self.stopped():
try:
return q.get(timeout=5)
except queue.Empty:
pass | [
"def",
"queue_get_stoppable",
"(",
"self",
",",
"q",
")",
":",
"while",
"not",
"self",
".",
"stopped",
"(",
")",
":",
"try",
":",
"return",
"q",
".",
"get",
"(",
"timeout",
"=",
"5",
")",
"except",
"queue",
".",
"Empty",
":",
"pass"
] | Take obj from queue, but will give up when the thread is stopped | [
"Take",
"obj",
"from",
"queue",
"but",
"will",
"give",
"up",
"when",
"the",
"thread",
"is",
"stopped"
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/concurrency.py#L68-L74 |
27,282 | tensorpack/tensorpack | examples/basics/mnist-visualizations.py | visualize_conv_weights | def visualize_conv_weights(filters, name):
"""Visualize use weights in convolution filters.
Args:
filters: tensor containing the weights [H,W,Cin,Cout]
name: label for tensorboard
Returns:
image of all weight
"""
with tf.name_scope('visualize_w_' + name):
filters = ... | python | def visualize_conv_weights(filters, name):
"""Visualize use weights in convolution filters.
Args:
filters: tensor containing the weights [H,W,Cin,Cout]
name: label for tensorboard
Returns:
image of all weight
"""
with tf.name_scope('visualize_w_' + name):
filters = ... | [
"def",
"visualize_conv_weights",
"(",
"filters",
",",
"name",
")",
":",
"with",
"tf",
".",
"name_scope",
"(",
"'visualize_w_'",
"+",
"name",
")",
":",
"filters",
"=",
"tf",
".",
"transpose",
"(",
"filters",
",",
"(",
"3",
",",
"2",
",",
"0",
",",
"1"... | Visualize use weights in convolution filters.
Args:
filters: tensor containing the weights [H,W,Cin,Cout]
name: label for tensorboard
Returns:
image of all weight | [
"Visualize",
"use",
"weights",
"in",
"convolution",
"filters",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/basics/mnist-visualizations.py#L17-L36 |
27,283 | tensorpack/tensorpack | examples/basics/mnist-visualizations.py | visualize_conv_activations | def visualize_conv_activations(activation, name):
"""Visualize activations for convolution layers.
Remarks:
This tries to place all activations into a square.
Args:
activation: tensor with the activation [B,H,W,C]
name: label for tensorboard
Returns:
image of almost al... | python | def visualize_conv_activations(activation, name):
"""Visualize activations for convolution layers.
Remarks:
This tries to place all activations into a square.
Args:
activation: tensor with the activation [B,H,W,C]
name: label for tensorboard
Returns:
image of almost al... | [
"def",
"visualize_conv_activations",
"(",
"activation",
",",
"name",
")",
":",
"import",
"math",
"with",
"tf",
".",
"name_scope",
"(",
"'visualize_act_'",
"+",
"name",
")",
":",
"_",
",",
"h",
",",
"w",
",",
"c",
"=",
"activation",
".",
"get_shape",
"(",... | Visualize activations for convolution layers.
Remarks:
This tries to place all activations into a square.
Args:
activation: tensor with the activation [B,H,W,C]
name: label for tensorboard
Returns:
image of almost all activations | [
"Visualize",
"activations",
"for",
"convolution",
"layers",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/basics/mnist-visualizations.py#L39-L64 |
27,284 | tensorpack/tensorpack | examples/GAN/InfoGAN-mnist.py | shapeless_placeholder | def shapeless_placeholder(x, axis, name):
"""
Make the static shape of a tensor less specific.
If you want to feed to a tensor, the shape of the feed value must match
the tensor's static shape. This function creates a placeholder which
defaults to x if not fed, but has a less specific static shape ... | python | def shapeless_placeholder(x, axis, name):
"""
Make the static shape of a tensor less specific.
If you want to feed to a tensor, the shape of the feed value must match
the tensor's static shape. This function creates a placeholder which
defaults to x if not fed, but has a less specific static shape ... | [
"def",
"shapeless_placeholder",
"(",
"x",
",",
"axis",
",",
"name",
")",
":",
"shp",
"=",
"x",
".",
"get_shape",
"(",
")",
".",
"as_list",
"(",
")",
"if",
"not",
"isinstance",
"(",
"axis",
",",
"list",
")",
":",
"axis",
"=",
"[",
"axis",
"]",
"fo... | Make the static shape of a tensor less specific.
If you want to feed to a tensor, the shape of the feed value must match
the tensor's static shape. This function creates a placeholder which
defaults to x if not fed, but has a less specific static shape than x.
See also `tensorflow#5680 <https://github.... | [
"Make",
"the",
"static",
"shape",
"of",
"a",
"tensor",
"less",
"specific",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/GAN/InfoGAN-mnist.py#L40-L66 |
27,285 | tensorpack/tensorpack | examples/GAN/InfoGAN-mnist.py | sample_prior | def sample_prior(batch_size):
cat, _ = get_distributions(DIST_PRIOR_PARAM[:NUM_CLASS], DIST_PRIOR_PARAM[NUM_CLASS:])
sample_cat = tf.one_hot(cat.sample(batch_size), NUM_CLASS)
"""
OpenAI official code actually models the "uniform" latent code as
a Gaussian distribution, but obtain the samples from ... | python | def sample_prior(batch_size):
cat, _ = get_distributions(DIST_PRIOR_PARAM[:NUM_CLASS], DIST_PRIOR_PARAM[NUM_CLASS:])
sample_cat = tf.one_hot(cat.sample(batch_size), NUM_CLASS)
"""
OpenAI official code actually models the "uniform" latent code as
a Gaussian distribution, but obtain the samples from ... | [
"def",
"sample_prior",
"(",
"batch_size",
")",
":",
"cat",
",",
"_",
"=",
"get_distributions",
"(",
"DIST_PRIOR_PARAM",
"[",
":",
"NUM_CLASS",
"]",
",",
"DIST_PRIOR_PARAM",
"[",
"NUM_CLASS",
":",
"]",
")",
"sample_cat",
"=",
"tf",
".",
"one_hot",
"(",
"cat... | OpenAI official code actually models the "uniform" latent code as
a Gaussian distribution, but obtain the samples from a uniform distribution. | [
"OpenAI",
"official",
"code",
"actually",
"models",
"the",
"uniform",
"latent",
"code",
"as",
"a",
"Gaussian",
"distribution",
"but",
"obtain",
"the",
"samples",
"from",
"a",
"uniform",
"distribution",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/GAN/InfoGAN-mnist.py#L94-L104 |
27,286 | tensorpack/tensorpack | examples/DynamicFilterNetwork/steering-filter.py | Model._parameter_net | def _parameter_net(self, theta, kernel_shape=9):
"""Estimate filters for convolution layers
Args:
theta: angle of filter
kernel_shape: size of each filter
Returns:
learned filter as [B, k, k, 1]
"""
with argscope(FullyConnected, nl=tf.nn.leak... | python | def _parameter_net(self, theta, kernel_shape=9):
"""Estimate filters for convolution layers
Args:
theta: angle of filter
kernel_shape: size of each filter
Returns:
learned filter as [B, k, k, 1]
"""
with argscope(FullyConnected, nl=tf.nn.leak... | [
"def",
"_parameter_net",
"(",
"self",
",",
"theta",
",",
"kernel_shape",
"=",
"9",
")",
":",
"with",
"argscope",
"(",
"FullyConnected",
",",
"nl",
"=",
"tf",
".",
"nn",
".",
"leaky_relu",
")",
":",
"net",
"=",
"FullyConnected",
"(",
"'fc1'",
",",
"thet... | Estimate filters for convolution layers
Args:
theta: angle of filter
kernel_shape: size of each filter
Returns:
learned filter as [B, k, k, 1] | [
"Estimate",
"filters",
"for",
"convolution",
"layers"
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/DynamicFilterNetwork/steering-filter.py#L103-L120 |
27,287 | tensorpack/tensorpack | examples/DynamicFilterNetwork/steering-filter.py | ThetaImages.filter_with_theta | def filter_with_theta(image, theta, sigma=1., filter_size=9):
"""Implements a steerable Gaussian filter.
This function can be used to evaluate the first
directional derivative of an image, using the
method outlined in
W. T. Freeman and E. H. Adelson, "The Design
... | python | def filter_with_theta(image, theta, sigma=1., filter_size=9):
"""Implements a steerable Gaussian filter.
This function can be used to evaluate the first
directional derivative of an image, using the
method outlined in
W. T. Freeman and E. H. Adelson, "The Design
... | [
"def",
"filter_with_theta",
"(",
"image",
",",
"theta",
",",
"sigma",
"=",
"1.",
",",
"filter_size",
"=",
"9",
")",
":",
"x",
"=",
"np",
".",
"arange",
"(",
"-",
"filter_size",
"//",
"2",
"+",
"1",
",",
"filter_size",
"//",
"2",
"+",
"1",
")",
"#... | Implements a steerable Gaussian filter.
This function can be used to evaluate the first
directional derivative of an image, using the
method outlined in
W. T. Freeman and E. H. Adelson, "The Design
and Use of Steerable Filters", IEEE PAMI, 1991.
It evaluates th... | [
"Implements",
"a",
"steerable",
"Gaussian",
"filter",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/DynamicFilterNetwork/steering-filter.py#L162-L204 |
27,288 | tensorpack/tensorpack | examples/GAN/GAN.py | GANModelDesc.collect_variables | def collect_variables(self, g_scope='gen', d_scope='discrim'):
"""
Assign `self.g_vars` to the parameters under scope `g_scope`,
and same with `self.d_vars`.
"""
self.g_vars = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, g_scope)
assert self.g_vars
self.d_v... | python | def collect_variables(self, g_scope='gen', d_scope='discrim'):
"""
Assign `self.g_vars` to the parameters under scope `g_scope`,
and same with `self.d_vars`.
"""
self.g_vars = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, g_scope)
assert self.g_vars
self.d_v... | [
"def",
"collect_variables",
"(",
"self",
",",
"g_scope",
"=",
"'gen'",
",",
"d_scope",
"=",
"'discrim'",
")",
":",
"self",
".",
"g_vars",
"=",
"tf",
".",
"get_collection",
"(",
"tf",
".",
"GraphKeys",
".",
"TRAINABLE_VARIABLES",
",",
"g_scope",
")",
"asser... | Assign `self.g_vars` to the parameters under scope `g_scope`,
and same with `self.d_vars`. | [
"Assign",
"self",
".",
"g_vars",
"to",
"the",
"parameters",
"under",
"scope",
"g_scope",
"and",
"same",
"with",
"self",
".",
"d_vars",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/GAN/GAN.py#L17-L25 |
27,289 | tensorpack/tensorpack | examples/GAN/GAN.py | GANModelDesc.build_losses | def build_losses(self, logits_real, logits_fake):
"""
Build standard GAN loss and set `self.g_loss` and `self.d_loss`.
D and G play two-player minimax game with value function V(G,D)
min_G max _D V(D, G) = IE_{x ~ p_data} [log D(x)] + IE_{z ~ p_fake} [log (1 - D(G(z)))]
Args... | python | def build_losses(self, logits_real, logits_fake):
"""
Build standard GAN loss and set `self.g_loss` and `self.d_loss`.
D and G play two-player minimax game with value function V(G,D)
min_G max _D V(D, G) = IE_{x ~ p_data} [log D(x)] + IE_{z ~ p_fake} [log (1 - D(G(z)))]
Args... | [
"def",
"build_losses",
"(",
"self",
",",
"logits_real",
",",
"logits_fake",
")",
":",
"with",
"tf",
".",
"name_scope",
"(",
"\"GAN_loss\"",
")",
":",
"score_real",
"=",
"tf",
".",
"sigmoid",
"(",
"logits_real",
")",
"score_fake",
"=",
"tf",
".",
"sigmoid",... | Build standard GAN loss and set `self.g_loss` and `self.d_loss`.
D and G play two-player minimax game with value function V(G,D)
min_G max _D V(D, G) = IE_{x ~ p_data} [log D(x)] + IE_{z ~ p_fake} [log (1 - D(G(z)))]
Args:
logits_real (tf.Tensor): discrim logits from real sample... | [
"Build",
"standard",
"GAN",
"loss",
"and",
"set",
"self",
".",
"g_loss",
"and",
"self",
".",
"d_loss",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/GAN/GAN.py#L27-L62 |
27,290 | tensorpack/tensorpack | examples/GAN/GAN.py | GANTrainer._build_gan_trainer | def _build_gan_trainer(self, input, model):
"""
We need to set tower_func because it's a TowerTrainer,
and only TowerTrainer supports automatic graph creation for inference during training.
If we don't care about inference during training, using tower_func is
not needed. Just ca... | python | def _build_gan_trainer(self, input, model):
"""
We need to set tower_func because it's a TowerTrainer,
and only TowerTrainer supports automatic graph creation for inference during training.
If we don't care about inference during training, using tower_func is
not needed. Just ca... | [
"def",
"_build_gan_trainer",
"(",
"self",
",",
"input",
",",
"model",
")",
":",
"# Build the graph",
"self",
".",
"tower_func",
"=",
"TowerFuncWrapper",
"(",
"model",
".",
"build_graph",
",",
"model",
".",
"get_input_signature",
"(",
")",
")",
"with",
"TowerCo... | We need to set tower_func because it's a TowerTrainer,
and only TowerTrainer supports automatic graph creation for inference during training.
If we don't care about inference during training, using tower_func is
not needed. Just calling model.build_graph directly is OK. | [
"We",
"need",
"to",
"set",
"tower_func",
"because",
"it",
"s",
"a",
"TowerTrainer",
"and",
"only",
"TowerTrainer",
"supports",
"automatic",
"graph",
"creation",
"for",
"inference",
"during",
"training",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/GAN/GAN.py#L99-L119 |
27,291 | tensorpack/tensorpack | tensorpack/models/regularize.py | regularize_cost_from_collection | def regularize_cost_from_collection(name='regularize_cost'):
"""
Get the cost from the regularizers in ``tf.GraphKeys.REGULARIZATION_LOSSES``.
If in replicated mode, will only regularize variables created within the current tower.
Args:
name (str): the name of the returned tensor
Returns:
... | python | def regularize_cost_from_collection(name='regularize_cost'):
"""
Get the cost from the regularizers in ``tf.GraphKeys.REGULARIZATION_LOSSES``.
If in replicated mode, will only regularize variables created within the current tower.
Args:
name (str): the name of the returned tensor
Returns:
... | [
"def",
"regularize_cost_from_collection",
"(",
"name",
"=",
"'regularize_cost'",
")",
":",
"ctx",
"=",
"get_current_tower_context",
"(",
")",
"if",
"not",
"ctx",
".",
"is_training",
":",
"# TODO Currently cannot build the wd_cost correctly at inference,",
"# because ths vs_na... | Get the cost from the regularizers in ``tf.GraphKeys.REGULARIZATION_LOSSES``.
If in replicated mode, will only regularize variables created within the current tower.
Args:
name (str): the name of the returned tensor
Returns:
tf.Tensor: a scalar, the total regularization cost. | [
"Get",
"the",
"cost",
"from",
"the",
"regularizers",
"in",
"tf",
".",
"GraphKeys",
".",
"REGULARIZATION_LOSSES",
".",
"If",
"in",
"replicated",
"mode",
"will",
"only",
"regularize",
"variables",
"created",
"within",
"the",
"current",
"tower",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/models/regularize.py#L103-L141 |
27,292 | tensorpack/tensorpack | tensorpack/models/regularize.py | Dropout | def Dropout(x, *args, **kwargs):
"""
Same as `tf.layers.dropout`.
However, for historical reasons, the first positional argument is
interpreted as keep_prob rather than drop_prob.
Explicitly use `rate=` keyword arguments to ensure things are consistent.
"""
if 'is_training' in kwargs:
... | python | def Dropout(x, *args, **kwargs):
"""
Same as `tf.layers.dropout`.
However, for historical reasons, the first positional argument is
interpreted as keep_prob rather than drop_prob.
Explicitly use `rate=` keyword arguments to ensure things are consistent.
"""
if 'is_training' in kwargs:
... | [
"def",
"Dropout",
"(",
"x",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"'is_training'",
"in",
"kwargs",
":",
"kwargs",
"[",
"'training'",
"]",
"=",
"kwargs",
".",
"pop",
"(",
"'is_training'",
")",
"if",
"len",
"(",
"args",
")",
">",... | Same as `tf.layers.dropout`.
However, for historical reasons, the first positional argument is
interpreted as keep_prob rather than drop_prob.
Explicitly use `rate=` keyword arguments to ensure things are consistent. | [
"Same",
"as",
"tf",
".",
"layers",
".",
"dropout",
".",
"However",
"for",
"historical",
"reasons",
"the",
"first",
"positional",
"argument",
"is",
"interpreted",
"as",
"keep_prob",
"rather",
"than",
"drop_prob",
".",
"Explicitly",
"use",
"rate",
"=",
"keyword"... | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/models/regularize.py#L145-L175 |
27,293 | tensorpack/tensorpack | tensorpack/dataflow/imgaug/paste.py | BackgroundFiller.fill | def fill(self, background_shape, img):
"""
Return a proper background image of background_shape, given img.
Args:
background_shape (tuple): a shape (h, w)
img: an image
Returns:
a background image
"""
background_shape = tuple(backgroun... | python | def fill(self, background_shape, img):
"""
Return a proper background image of background_shape, given img.
Args:
background_shape (tuple): a shape (h, w)
img: an image
Returns:
a background image
"""
background_shape = tuple(backgroun... | [
"def",
"fill",
"(",
"self",
",",
"background_shape",
",",
"img",
")",
":",
"background_shape",
"=",
"tuple",
"(",
"background_shape",
")",
"return",
"self",
".",
"_fill",
"(",
"background_shape",
",",
"img",
")"
] | Return a proper background image of background_shape, given img.
Args:
background_shape (tuple): a shape (h, w)
img: an image
Returns:
a background image | [
"Return",
"a",
"proper",
"background",
"image",
"of",
"background_shape",
"given",
"img",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/dataflow/imgaug/paste.py#L17-L28 |
27,294 | tensorpack/tensorpack | tensorpack/models/linearwrap.py | LinearWrap.apply | def apply(self, func, *args, **kwargs):
"""
Apply a function on the wrapped tensor.
Returns:
LinearWrap: ``LinearWrap(func(self.tensor(), *args, **kwargs))``.
"""
ret = func(self._t, *args, **kwargs)
return LinearWrap(ret) | python | def apply(self, func, *args, **kwargs):
"""
Apply a function on the wrapped tensor.
Returns:
LinearWrap: ``LinearWrap(func(self.tensor(), *args, **kwargs))``.
"""
ret = func(self._t, *args, **kwargs)
return LinearWrap(ret) | [
"def",
"apply",
"(",
"self",
",",
"func",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"ret",
"=",
"func",
"(",
"self",
".",
"_t",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"LinearWrap",
"(",
"ret",
")"
] | Apply a function on the wrapped tensor.
Returns:
LinearWrap: ``LinearWrap(func(self.tensor(), *args, **kwargs))``. | [
"Apply",
"a",
"function",
"on",
"the",
"wrapped",
"tensor",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/models/linearwrap.py#L68-L76 |
27,295 | tensorpack/tensorpack | tensorpack/models/linearwrap.py | LinearWrap.apply2 | def apply2(self, func, *args, **kwargs):
"""
Apply a function on the wrapped tensor. The tensor
will be the second argument of func.
This is because many symbolic functions
(such as tensorpack's layers) takes 'scope' as the first argument.
Returns:
LinearWra... | python | def apply2(self, func, *args, **kwargs):
"""
Apply a function on the wrapped tensor. The tensor
will be the second argument of func.
This is because many symbolic functions
(such as tensorpack's layers) takes 'scope' as the first argument.
Returns:
LinearWra... | [
"def",
"apply2",
"(",
"self",
",",
"func",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"ret",
"=",
"func",
"(",
"args",
"[",
"0",
"]",
",",
"self",
".",
"_t",
",",
"*",
"(",
"args",
"[",
"1",
":",
"]",
")",
",",
"*",
"*",
"kwargs... | Apply a function on the wrapped tensor. The tensor
will be the second argument of func.
This is because many symbolic functions
(such as tensorpack's layers) takes 'scope' as the first argument.
Returns:
LinearWrap: ``LinearWrap(func(args[0], self.tensor(), *args[1:], **kwa... | [
"Apply",
"a",
"function",
"on",
"the",
"wrapped",
"tensor",
".",
"The",
"tensor",
"will",
"be",
"the",
"second",
"argument",
"of",
"func",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/models/linearwrap.py#L78-L90 |
27,296 | tensorpack/tensorpack | tensorpack/callbacks/param.py | GraphVarParam.setup_graph | def setup_graph(self):
""" Will setup the assign operator for that variable. """
all_vars = tfv1.global_variables() + tfv1.local_variables()
for v in all_vars:
if v.name == self.var_name:
self.var = v
break
else:
raise ValueError("{... | python | def setup_graph(self):
""" Will setup the assign operator for that variable. """
all_vars = tfv1.global_variables() + tfv1.local_variables()
for v in all_vars:
if v.name == self.var_name:
self.var = v
break
else:
raise ValueError("{... | [
"def",
"setup_graph",
"(",
"self",
")",
":",
"all_vars",
"=",
"tfv1",
".",
"global_variables",
"(",
")",
"+",
"tfv1",
".",
"local_variables",
"(",
")",
"for",
"v",
"in",
"all_vars",
":",
"if",
"v",
".",
"name",
"==",
"self",
".",
"var_name",
":",
"se... | Will setup the assign operator for that variable. | [
"Will",
"setup",
"the",
"assign",
"operator",
"for",
"that",
"variable",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/callbacks/param.py#L68-L76 |
27,297 | tensorpack/tensorpack | tensorpack/callbacks/param.py | ScheduledHyperParamSetter._get_value_to_set_at_point | def _get_value_to_set_at_point(self, point):
"""
Using schedule, compute the value to be set at a given point.
"""
laste, lastv = None, None
for e, v in self.schedule:
if e == point:
return v # meet the exact boundary, return directly
if... | python | def _get_value_to_set_at_point(self, point):
"""
Using schedule, compute the value to be set at a given point.
"""
laste, lastv = None, None
for e, v in self.schedule:
if e == point:
return v # meet the exact boundary, return directly
if... | [
"def",
"_get_value_to_set_at_point",
"(",
"self",
",",
"point",
")",
":",
"laste",
",",
"lastv",
"=",
"None",
",",
"None",
"for",
"e",
",",
"v",
"in",
"self",
".",
"schedule",
":",
"if",
"e",
"==",
"point",
":",
"return",
"v",
"# meet the exact boundary,... | Using schedule, compute the value to be set at a given point. | [
"Using",
"schedule",
"compute",
"the",
"value",
"to",
"be",
"set",
"at",
"a",
"given",
"point",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/callbacks/param.py#L283-L301 |
27,298 | tensorpack/tensorpack | examples/ResNet/load-resnet.py | name_conversion | def name_conversion(caffe_layer_name):
""" Convert a caffe parameter name to a tensorflow parameter name as
defined in the above model """
# beginning & end mapping
NAME_MAP = {'bn_conv1/beta': 'conv0/bn/beta',
'bn_conv1/gamma': 'conv0/bn/gamma',
'bn_conv1/mean/EMA': ... | python | def name_conversion(caffe_layer_name):
""" Convert a caffe parameter name to a tensorflow parameter name as
defined in the above model """
# beginning & end mapping
NAME_MAP = {'bn_conv1/beta': 'conv0/bn/beta',
'bn_conv1/gamma': 'conv0/bn/gamma',
'bn_conv1/mean/EMA': ... | [
"def",
"name_conversion",
"(",
"caffe_layer_name",
")",
":",
"# beginning & end mapping",
"NAME_MAP",
"=",
"{",
"'bn_conv1/beta'",
":",
"'conv0/bn/beta'",
",",
"'bn_conv1/gamma'",
":",
"'conv0/bn/gamma'",
",",
"'bn_conv1/mean/EMA'",
":",
"'conv0/bn/mean/EMA'",
",",
"'bn_c... | Convert a caffe parameter name to a tensorflow parameter name as
defined in the above model | [
"Convert",
"a",
"caffe",
"parameter",
"name",
"to",
"a",
"tensorflow",
"parameter",
"name",
"as",
"defined",
"in",
"the",
"above",
"model"
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/ResNet/load-resnet.py#L101-L138 |
27,299 | tensorpack/tensorpack | tensorpack/tfutils/varreplace.py | remap_variables | def remap_variables(fn):
"""
Use fn to map the output of any variable getter.
Args:
fn (tf.Variable -> tf.Tensor)
Returns:
The current variable scope with a custom_getter that maps
all the variables by fn.
Example:
.. code-block:: python
with varreplac... | python | def remap_variables(fn):
"""
Use fn to map the output of any variable getter.
Args:
fn (tf.Variable -> tf.Tensor)
Returns:
The current variable scope with a custom_getter that maps
all the variables by fn.
Example:
.. code-block:: python
with varreplac... | [
"def",
"remap_variables",
"(",
"fn",
")",
":",
"def",
"custom_getter",
"(",
"getter",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"v",
"=",
"getter",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"fn",
"(",
"v",
")",
"return"... | Use fn to map the output of any variable getter.
Args:
fn (tf.Variable -> tf.Tensor)
Returns:
The current variable scope with a custom_getter that maps
all the variables by fn.
Example:
.. code-block:: python
with varreplace.remap_variables(lambda var: quantiz... | [
"Use",
"fn",
"to",
"map",
"the",
"output",
"of",
"any",
"variable",
"getter",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/tfutils/varreplace.py#L36-L56 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.