repo stringclasses 85
values | path stringlengths 8 121 | func_name stringlengths 1 82 | original_string stringlengths 112 65.5k | language stringclasses 1
value | code stringlengths 112 65.5k | code_tokens listlengths 20 4.09k | docstring stringlengths 3 46.3k | docstring_tokens listlengths 1 564 | sha stringclasses 85
values | url stringlengths 93 218 | partition stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|
tensorpack/tensorpack | tensorpack/tfutils/common.py | get_default_sess_config | def get_default_sess_config(mem_fraction=0.99):
"""
Return a tf.ConfigProto to use as default session config.
You can modify the returned config to fit your needs.
Args:
mem_fraction(float): see the `per_process_gpu_memory_fraction` option
in TensorFlow's GPUOptions protobuf:
... | python | def get_default_sess_config(mem_fraction=0.99):
"""
Return a tf.ConfigProto to use as default session config.
You can modify the returned config to fit your needs.
Args:
mem_fraction(float): see the `per_process_gpu_memory_fraction` option
in TensorFlow's GPUOptions protobuf:
... | [
"def",
"get_default_sess_config",
"(",
"mem_fraction",
"=",
"0.99",
")",
":",
"conf",
"=",
"tfv1",
".",
"ConfigProto",
"(",
")",
"conf",
".",
"allow_soft_placement",
"=",
"True",
"# conf.log_device_placement = True",
"conf",
".",
"intra_op_parallelism_threads",
"=",
... | Return a tf.ConfigProto to use as default session config.
You can modify the returned config to fit your needs.
Args:
mem_fraction(float): see the `per_process_gpu_memory_fraction` option
in TensorFlow's GPUOptions protobuf:
https://github.com/tensorflow/tensorflow/blob/master/t... | [
"Return",
"a",
"tf",
".",
"ConfigProto",
"to",
"use",
"as",
"default",
"session",
"config",
".",
"You",
"can",
"modify",
"the",
"returned",
"config",
"to",
"fit",
"your",
"needs",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/tfutils/common.py#L30-L68 | train |
tensorpack/tensorpack | tensorpack/tfutils/common.py | get_global_step_var | def get_global_step_var():
"""
Returns:
tf.Tensor: the global_step variable in the current graph. Create if doesn't exist.
"""
scope = tfv1.VariableScope(reuse=False, name='') # the root vs
with tfv1.variable_scope(scope):
var = tfv1.train.get_or_create_global_step()
return var | python | def get_global_step_var():
"""
Returns:
tf.Tensor: the global_step variable in the current graph. Create if doesn't exist.
"""
scope = tfv1.VariableScope(reuse=False, name='') # the root vs
with tfv1.variable_scope(scope):
var = tfv1.train.get_or_create_global_step()
return var | [
"def",
"get_global_step_var",
"(",
")",
":",
"scope",
"=",
"tfv1",
".",
"VariableScope",
"(",
"reuse",
"=",
"False",
",",
"name",
"=",
"''",
")",
"# the root vs",
"with",
"tfv1",
".",
"variable_scope",
"(",
"scope",
")",
":",
"var",
"=",
"tfv1",
".",
"... | Returns:
tf.Tensor: the global_step variable in the current graph. Create if doesn't exist. | [
"Returns",
":",
"tf",
".",
"Tensor",
":",
"the",
"global_step",
"variable",
"in",
"the",
"current",
"graph",
".",
"Create",
"if",
"doesn",
"t",
"exist",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/tfutils/common.py#L72-L80 | train |
tensorpack/tensorpack | tensorpack/tfutils/common.py | get_tensors_by_names | def get_tensors_by_names(names):
"""
Get a list of tensors in the default graph by a list of names.
Args:
names (list):
"""
ret = []
G = tfv1.get_default_graph()
for n in names:
opn, varn = get_op_tensor_name(n)
ret.append(G.get_tensor_by_name(varn))
return ret | python | def get_tensors_by_names(names):
"""
Get a list of tensors in the default graph by a list of names.
Args:
names (list):
"""
ret = []
G = tfv1.get_default_graph()
for n in names:
opn, varn = get_op_tensor_name(n)
ret.append(G.get_tensor_by_name(varn))
return ret | [
"def",
"get_tensors_by_names",
"(",
"names",
")",
":",
"ret",
"=",
"[",
"]",
"G",
"=",
"tfv1",
".",
"get_default_graph",
"(",
")",
"for",
"n",
"in",
"names",
":",
"opn",
",",
"varn",
"=",
"get_op_tensor_name",
"(",
"n",
")",
"ret",
".",
"append",
"("... | Get a list of tensors in the default graph by a list of names.
Args:
names (list): | [
"Get",
"a",
"list",
"of",
"tensors",
"in",
"the",
"default",
"graph",
"by",
"a",
"list",
"of",
"names",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/tfutils/common.py#L113-L125 | train |
tensorpack/tensorpack | tensorpack/tfutils/common.py | get_op_or_tensor_by_name | def get_op_or_tensor_by_name(name):
"""
Get either tf.Operation of tf.Tensor from names.
Args:
name (list[str] or str): names of operations or tensors.
Raises:
KeyError, if the name doesn't exist
"""
G = tfv1.get_default_graph()
def f(n):
if len(n) >= 3 and n[-2] =... | python | def get_op_or_tensor_by_name(name):
"""
Get either tf.Operation of tf.Tensor from names.
Args:
name (list[str] or str): names of operations or tensors.
Raises:
KeyError, if the name doesn't exist
"""
G = tfv1.get_default_graph()
def f(n):
if len(n) >= 3 and n[-2] =... | [
"def",
"get_op_or_tensor_by_name",
"(",
"name",
")",
":",
"G",
"=",
"tfv1",
".",
"get_default_graph",
"(",
")",
"def",
"f",
"(",
"n",
")",
":",
"if",
"len",
"(",
"n",
")",
">=",
"3",
"and",
"n",
"[",
"-",
"2",
"]",
"==",
"':'",
":",
"return",
"... | Get either tf.Operation of tf.Tensor from names.
Args:
name (list[str] or str): names of operations or tensors.
Raises:
KeyError, if the name doesn't exist | [
"Get",
"either",
"tf",
".",
"Operation",
"of",
"tf",
".",
"Tensor",
"from",
"names",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/tfutils/common.py#L128-L149 | train |
tensorpack/tensorpack | tensorpack/tfutils/common.py | collect_env_info | def collect_env_info():
"""
Returns:
str - a table contains important information about the environment
"""
data = []
data.append(("sys.platform", sys.platform))
data.append(("Python", sys.version.replace("\n", "")))
data.append(("Tensorpack", __git_version__))
data.append(("Nump... | python | def collect_env_info():
"""
Returns:
str - a table contains important information about the environment
"""
data = []
data.append(("sys.platform", sys.platform))
data.append(("Python", sys.version.replace("\n", "")))
data.append(("Tensorpack", __git_version__))
data.append(("Nump... | [
"def",
"collect_env_info",
"(",
")",
":",
"data",
"=",
"[",
"]",
"data",
".",
"append",
"(",
"(",
"\"sys.platform\"",
",",
"sys",
".",
"platform",
")",
")",
"data",
".",
"append",
"(",
"(",
"\"Python\"",
",",
"sys",
".",
"version",
".",
"replace",
"(... | Returns:
str - a table contains important information about the environment | [
"Returns",
":",
"str",
"-",
"a",
"table",
"contains",
"important",
"information",
"about",
"the",
"environment"
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/tfutils/common.py#L167-L245 | train |
tensorpack/tensorpack | tensorpack/graph_builder/distributed.py | DistributedBuilderBase._add_sync_queues_and_barrier | def _add_sync_queues_and_barrier(self, name, dependencies):
"""Adds ops to enqueue on all worker queues.
Args:
name: prefixed for the shared_name of ops.
dependencies: control dependency from ops.
Returns:
an op that should be used as control dependency befo... | python | def _add_sync_queues_and_barrier(self, name, dependencies):
"""Adds ops to enqueue on all worker queues.
Args:
name: prefixed for the shared_name of ops.
dependencies: control dependency from ops.
Returns:
an op that should be used as control dependency befo... | [
"def",
"_add_sync_queues_and_barrier",
"(",
"self",
",",
"name",
",",
"dependencies",
")",
":",
"self",
".",
"_sync_queue_counter",
"+=",
"1",
"with",
"tf",
".",
"device",
"(",
"self",
".",
"sync_queue_devices",
"[",
"self",
".",
"_sync_queue_counter",
"%",
"l... | Adds ops to enqueue on all worker queues.
Args:
name: prefixed for the shared_name of ops.
dependencies: control dependency from ops.
Returns:
an op that should be used as control dependency before starting next step. | [
"Adds",
"ops",
"to",
"enqueue",
"on",
"all",
"worker",
"queues",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/graph_builder/distributed.py#L30-L58 | train |
tensorpack/tensorpack | tensorpack/graph_builder/distributed.py | DistributedReplicatedBuilder._apply_shadow_vars | def _apply_shadow_vars(avg_grads):
"""
Create shadow variables on PS, and replace variables in avg_grads
by these shadow variables.
Args:
avg_grads: list of (grad, var) tuples
"""
ps_var_grads = []
for grad, var in avg_grads:
assert var.na... | python | def _apply_shadow_vars(avg_grads):
"""
Create shadow variables on PS, and replace variables in avg_grads
by these shadow variables.
Args:
avg_grads: list of (grad, var) tuples
"""
ps_var_grads = []
for grad, var in avg_grads:
assert var.na... | [
"def",
"_apply_shadow_vars",
"(",
"avg_grads",
")",
":",
"ps_var_grads",
"=",
"[",
"]",
"for",
"grad",
",",
"var",
"in",
"avg_grads",
":",
"assert",
"var",
".",
"name",
".",
"startswith",
"(",
"'tower'",
")",
",",
"var",
".",
"name",
"my_name",
"=",
"'... | Create shadow variables on PS, and replace variables in avg_grads
by these shadow variables.
Args:
avg_grads: list of (grad, var) tuples | [
"Create",
"shadow",
"variables",
"on",
"PS",
"and",
"replace",
"variables",
"in",
"avg_grads",
"by",
"these",
"shadow",
"variables",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/graph_builder/distributed.py#L205-L223 | train |
tensorpack/tensorpack | tensorpack/graph_builder/distributed.py | DistributedReplicatedBuilder._shadow_model_variables | def _shadow_model_variables(shadow_vars):
"""
Create shadow vars for model_variables as well, and add to the list of ``shadow_vars``.
Returns:
list of (shadow_model_var, local_model_var) used for syncing.
"""
G = tf.get_default_graph()
curr_shadow_vars = set(... | python | def _shadow_model_variables(shadow_vars):
"""
Create shadow vars for model_variables as well, and add to the list of ``shadow_vars``.
Returns:
list of (shadow_model_var, local_model_var) used for syncing.
"""
G = tf.get_default_graph()
curr_shadow_vars = set(... | [
"def",
"_shadow_model_variables",
"(",
"shadow_vars",
")",
":",
"G",
"=",
"tf",
".",
"get_default_graph",
"(",
")",
"curr_shadow_vars",
"=",
"set",
"(",
"[",
"v",
".",
"name",
"for",
"v",
"in",
"shadow_vars",
"]",
")",
"model_vars",
"=",
"tf",
".",
"mode... | Create shadow vars for model_variables as well, and add to the list of ``shadow_vars``.
Returns:
list of (shadow_model_var, local_model_var) used for syncing. | [
"Create",
"shadow",
"vars",
"for",
"model_variables",
"as",
"well",
"and",
"add",
"to",
"the",
"list",
"of",
"shadow_vars",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/graph_builder/distributed.py#L226-L255 | train |
tensorpack/tensorpack | tensorpack/graph_builder/distributed.py | DistributedReplicatedBuilder.build | def build(self, get_grad_fn, get_opt_fn):
"""
Args:
get_grad_fn (-> [(grad, var)]):
get_opt_fn (-> tf.train.Optimizer): callable which returns an optimizer
Returns:
(tf.Operation, tf.Operation, tf.Operation):
1. the training op.
2. t... | python | def build(self, get_grad_fn, get_opt_fn):
"""
Args:
get_grad_fn (-> [(grad, var)]):
get_opt_fn (-> tf.train.Optimizer): callable which returns an optimizer
Returns:
(tf.Operation, tf.Operation, tf.Operation):
1. the training op.
2. t... | [
"def",
"build",
"(",
"self",
",",
"get_grad_fn",
",",
"get_opt_fn",
")",
":",
"with",
"override_to_local_variable",
"(",
")",
":",
"get_global_step_var",
"(",
")",
"get_opt_fn",
"=",
"memoized",
"(",
"get_opt_fn",
")",
"# Build the optimizer first, before entering any... | Args:
get_grad_fn (-> [(grad, var)]):
get_opt_fn (-> tf.train.Optimizer): callable which returns an optimizer
Returns:
(tf.Operation, tf.Operation, tf.Operation):
1. the training op.
2. the op which sync all the local variables from PS.
... | [
"Args",
":",
"get_grad_fn",
"(",
"-",
">",
"[",
"(",
"grad",
"var",
")",
"]",
")",
":",
"get_opt_fn",
"(",
"-",
">",
"tf",
".",
"train",
".",
"Optimizer",
")",
":",
"callable",
"which",
"returns",
"an",
"optimizer"
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/graph_builder/distributed.py#L257-L311 | train |
tensorpack/tensorpack | tensorpack/graph_builder/distributed.py | DistributedReplicatedBuilder._apply_gradients_and_copy | def _apply_gradients_and_copy(self, opt, raw_grad_list, ps_var_grads):
"""
Apply averaged gradients to ps vars, and then copy the updated
variables back to each tower.
Args:
raw_grad_list: Ngpu x Nvar x 2 gradient list from all towers
ps_var_grads: Nvar x 2 (grad... | python | def _apply_gradients_and_copy(self, opt, raw_grad_list, ps_var_grads):
"""
Apply averaged gradients to ps vars, and then copy the updated
variables back to each tower.
Args:
raw_grad_list: Ngpu x Nvar x 2 gradient list from all towers
ps_var_grads: Nvar x 2 (grad... | [
"def",
"_apply_gradients_and_copy",
"(",
"self",
",",
"opt",
",",
"raw_grad_list",
",",
"ps_var_grads",
")",
":",
"# TODO do this for variables together?",
"with",
"tf",
".",
"name_scope",
"(",
"'apply_gradients'",
")",
":",
"var_update_ops",
"=",
"[",
"]",
"for",
... | Apply averaged gradients to ps vars, and then copy the updated
variables back to each tower.
Args:
raw_grad_list: Ngpu x Nvar x 2 gradient list from all towers
ps_var_grads: Nvar x 2 (grad, ps_var)
Returns:
list of copy ops | [
"Apply",
"averaged",
"gradients",
"to",
"ps",
"vars",
"and",
"then",
"copy",
"the",
"updated",
"variables",
"back",
"to",
"each",
"tower",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/graph_builder/distributed.py#L313-L339 | train |
tensorpack/tensorpack | tensorpack/graph_builder/distributed.py | DistributedReplicatedBuilder._get_initial_sync_op | def _get_initial_sync_op(self):
"""
Get the op to copy-initialized all local variables from PS.
"""
def strip_port(s):
if s.endswith(':0'):
return s[:-2]
return s
local_vars = tf.local_variables()
local_var_by_name = dict([(strip_po... | python | def _get_initial_sync_op(self):
"""
Get the op to copy-initialized all local variables from PS.
"""
def strip_port(s):
if s.endswith(':0'):
return s[:-2]
return s
local_vars = tf.local_variables()
local_var_by_name = dict([(strip_po... | [
"def",
"_get_initial_sync_op",
"(",
"self",
")",
":",
"def",
"strip_port",
"(",
"s",
")",
":",
"if",
"s",
".",
"endswith",
"(",
"':0'",
")",
":",
"return",
"s",
"[",
":",
"-",
"2",
"]",
"return",
"s",
"local_vars",
"=",
"tf",
".",
"local_variables",
... | Get the op to copy-initialized all local variables from PS. | [
"Get",
"the",
"op",
"to",
"copy",
"-",
"initialized",
"all",
"local",
"variables",
"from",
"PS",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/graph_builder/distributed.py#L341-L362 | train |
tensorpack/tensorpack | tensorpack/graph_builder/distributed.py | DistributedReplicatedBuilder._get_sync_model_vars_op | def _get_sync_model_vars_op(self):
"""
Get the op to sync local model_variables to PS.
"""
ops = []
for (shadow_v, local_v) in self._shadow_model_vars:
ops.append(shadow_v.assign(local_v.read_value()))
assert len(ops)
return tf.group(*ops, name='sync_{... | python | def _get_sync_model_vars_op(self):
"""
Get the op to sync local model_variables to PS.
"""
ops = []
for (shadow_v, local_v) in self._shadow_model_vars:
ops.append(shadow_v.assign(local_v.read_value()))
assert len(ops)
return tf.group(*ops, name='sync_{... | [
"def",
"_get_sync_model_vars_op",
"(",
"self",
")",
":",
"ops",
"=",
"[",
"]",
"for",
"(",
"shadow_v",
",",
"local_v",
")",
"in",
"self",
".",
"_shadow_model_vars",
":",
"ops",
".",
"append",
"(",
"shadow_v",
".",
"assign",
"(",
"local_v",
".",
"read_val... | Get the op to sync local model_variables to PS. | [
"Get",
"the",
"op",
"to",
"sync",
"local",
"model_variables",
"to",
"PS",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/graph_builder/distributed.py#L364-L372 | train |
tensorpack/tensorpack | tensorpack/input_source/input_source_base.py | get_tensors_inputs | def get_tensors_inputs(placeholders, tensors, names):
"""
Args:
placeholders (list[Tensor]):
tensors (list[Tensor]): list of tf.Tensor
names (list[str]): names matching the given tensors
Returns:
list[Tensor]: inputs to used for the tower function,
with the corre... | python | def get_tensors_inputs(placeholders, tensors, names):
"""
Args:
placeholders (list[Tensor]):
tensors (list[Tensor]): list of tf.Tensor
names (list[str]): names matching the given tensors
Returns:
list[Tensor]: inputs to used for the tower function,
with the corre... | [
"def",
"get_tensors_inputs",
"(",
"placeholders",
",",
"tensors",
",",
"names",
")",
":",
"assert",
"len",
"(",
"tensors",
")",
"==",
"len",
"(",
"names",
")",
",",
"\"Input tensors {} and input names {} have different length!\"",
".",
"format",
"(",
"tensors",
",... | Args:
placeholders (list[Tensor]):
tensors (list[Tensor]): list of tf.Tensor
names (list[str]): names matching the given tensors
Returns:
list[Tensor]: inputs to used for the tower function,
with the corresponding placeholders replaced by tensors. | [
"Args",
":",
"placeholders",
"(",
"list",
"[",
"Tensor",
"]",
")",
":",
"tensors",
"(",
"list",
"[",
"Tensor",
"]",
")",
":",
"list",
"of",
"tf",
".",
"Tensor",
"names",
"(",
"list",
"[",
"str",
"]",
")",
":",
"names",
"matching",
"the",
"given",
... | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/input_source/input_source_base.py#L20-L44 | train |
tensorpack/tensorpack | tensorpack/input_source/input_source_base.py | get_sublist_by_names | def get_sublist_by_names(lst, names):
"""
Args:
lst (list): list of objects with "name" property.
Returns:
list: a sublist of objects, matching names
"""
orig_names = [p.name for p in lst]
ret = []
for name in names:
try:
idx = orig_names.index(name)
... | python | def get_sublist_by_names(lst, names):
"""
Args:
lst (list): list of objects with "name" property.
Returns:
list: a sublist of objects, matching names
"""
orig_names = [p.name for p in lst]
ret = []
for name in names:
try:
idx = orig_names.index(name)
... | [
"def",
"get_sublist_by_names",
"(",
"lst",
",",
"names",
")",
":",
"orig_names",
"=",
"[",
"p",
".",
"name",
"for",
"p",
"in",
"lst",
"]",
"ret",
"=",
"[",
"]",
"for",
"name",
"in",
"names",
":",
"try",
":",
"idx",
"=",
"orig_names",
".",
"index",
... | Args:
lst (list): list of objects with "name" property.
Returns:
list: a sublist of objects, matching names | [
"Args",
":",
"lst",
"(",
"list",
")",
":",
"list",
"of",
"objects",
"with",
"name",
"property",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/input_source/input_source_base.py#L47-L65 | train |
tensorpack/tensorpack | tensorpack/input_source/input_source_base.py | remap_input_source | def remap_input_source(input, names):
"""
When you have some :class:`InputSource` which doesn't match the inputs of
your tower function, use `RemapInputSource`.
It produces placeholders for all the inputs in your model,
except that the corresponding ones are replaced with the tensor produced
by ... | python | def remap_input_source(input, names):
"""
When you have some :class:`InputSource` which doesn't match the inputs of
your tower function, use `RemapInputSource`.
It produces placeholders for all the inputs in your model,
except that the corresponding ones are replaced with the tensor produced
by ... | [
"def",
"remap_input_source",
"(",
"input",
",",
"names",
")",
":",
"def",
"__init__",
"(",
"self",
",",
"input",
",",
"names",
")",
":",
"ProxyInputSource",
".",
"__init__",
"(",
"self",
",",
"input",
")",
"assert",
"isinstance",
"(",
"names",
",",
"(",
... | When you have some :class:`InputSource` which doesn't match the inputs of
your tower function, use `RemapInputSource`.
It produces placeholders for all the inputs in your model,
except that the corresponding ones are replaced with the tensor produced
by the given :class:`InputSource`.
Args:
... | [
"When",
"you",
"have",
"some",
":",
"class",
":",
"InputSource",
"which",
"doesn",
"t",
"match",
"the",
"inputs",
"of",
"your",
"tower",
"function",
"use",
"RemapInputSource",
".",
"It",
"produces",
"placeholders",
"for",
"all",
"the",
"inputs",
"in",
"your"... | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/input_source/input_source_base.py#L207-L260 | train |
tensorpack/tensorpack | examples/FasterRCNN/model_rpn.py | rpn_head | def rpn_head(featuremap, channel, num_anchors):
"""
Returns:
label_logits: fHxfWxNA
box_logits: fHxfWxNAx4
"""
with argscope(Conv2D, data_format='channels_first',
kernel_initializer=tf.random_normal_initializer(stddev=0.01)):
hidden = Conv2D('conv0', featuremap,... | python | def rpn_head(featuremap, channel, num_anchors):
"""
Returns:
label_logits: fHxfWxNA
box_logits: fHxfWxNAx4
"""
with argscope(Conv2D, data_format='channels_first',
kernel_initializer=tf.random_normal_initializer(stddev=0.01)):
hidden = Conv2D('conv0', featuremap,... | [
"def",
"rpn_head",
"(",
"featuremap",
",",
"channel",
",",
"num_anchors",
")",
":",
"with",
"argscope",
"(",
"Conv2D",
",",
"data_format",
"=",
"'channels_first'",
",",
"kernel_initializer",
"=",
"tf",
".",
"random_normal_initializer",
"(",
"stddev",
"=",
"0.01"... | Returns:
label_logits: fHxfWxNA
box_logits: fHxfWxNAx4 | [
"Returns",
":",
"label_logits",
":",
"fHxfWxNA",
"box_logits",
":",
"fHxfWxNAx4"
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/model_rpn.py#L16-L36 | train |
tensorpack/tensorpack | examples/FasterRCNN/model_rpn.py | rpn_losses | def rpn_losses(anchor_labels, anchor_boxes, label_logits, box_logits):
"""
Args:
anchor_labels: fHxfWxNA
anchor_boxes: fHxfWxNAx4, encoded
label_logits: fHxfWxNA
box_logits: fHxfWxNAx4
Returns:
label_loss, box_loss
"""
with tf.device('/cpu:0'):
valid... | python | def rpn_losses(anchor_labels, anchor_boxes, label_logits, box_logits):
"""
Args:
anchor_labels: fHxfWxNA
anchor_boxes: fHxfWxNAx4, encoded
label_logits: fHxfWxNA
box_logits: fHxfWxNAx4
Returns:
label_loss, box_loss
"""
with tf.device('/cpu:0'):
valid... | [
"def",
"rpn_losses",
"(",
"anchor_labels",
",",
"anchor_boxes",
",",
"label_logits",
",",
"box_logits",
")",
":",
"with",
"tf",
".",
"device",
"(",
"'/cpu:0'",
")",
":",
"valid_mask",
"=",
"tf",
".",
"stop_gradient",
"(",
"tf",
".",
"not_equal",
"(",
"anch... | Args:
anchor_labels: fHxfWxNA
anchor_boxes: fHxfWxNAx4, encoded
label_logits: fHxfWxNA
box_logits: fHxfWxNAx4
Returns:
label_loss, box_loss | [
"Args",
":",
"anchor_labels",
":",
"fHxfWxNA",
"anchor_boxes",
":",
"fHxfWxNAx4",
"encoded",
"label_logits",
":",
"fHxfWxNA",
"box_logits",
":",
"fHxfWxNAx4"
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/model_rpn.py#L40-L100 | train |
tensorpack/tensorpack | examples/FasterRCNN/model_rpn.py | generate_rpn_proposals | def generate_rpn_proposals(boxes, scores, img_shape,
pre_nms_topk, post_nms_topk=None):
"""
Sample RPN proposals by the following steps:
1. Pick top k1 by scores
2. NMS them
3. Pick top k2 by scores. Default k2 == k1, i.e. does not filter the NMS output.
Args:
... | python | def generate_rpn_proposals(boxes, scores, img_shape,
pre_nms_topk, post_nms_topk=None):
"""
Sample RPN proposals by the following steps:
1. Pick top k1 by scores
2. NMS them
3. Pick top k2 by scores. Default k2 == k1, i.e. does not filter the NMS output.
Args:
... | [
"def",
"generate_rpn_proposals",
"(",
"boxes",
",",
"scores",
",",
"img_shape",
",",
"pre_nms_topk",
",",
"post_nms_topk",
"=",
"None",
")",
":",
"assert",
"boxes",
".",
"shape",
".",
"ndims",
"==",
"2",
",",
"boxes",
".",
"shape",
"if",
"post_nms_topk",
"... | Sample RPN proposals by the following steps:
1. Pick top k1 by scores
2. NMS them
3. Pick top k2 by scores. Default k2 == k1, i.e. does not filter the NMS output.
Args:
boxes: nx4 float dtype, the proposal boxes. Decoded to floatbox already
scores: n float, the logits
img_shape:... | [
"Sample",
"RPN",
"proposals",
"by",
"the",
"following",
"steps",
":",
"1",
".",
"Pick",
"top",
"k1",
"by",
"scores",
"2",
".",
"NMS",
"them",
"3",
".",
"Pick",
"top",
"k2",
"by",
"scores",
".",
"Default",
"k2",
"==",
"k1",
"i",
".",
"e",
".",
"do... | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/model_rpn.py#L104-L153 | train |
tensorpack/tensorpack | tensorpack/callbacks/summary.py | MergeAllSummaries | def MergeAllSummaries(period=0, run_alone=False, key=None):
"""
This callback is enabled by default.
Evaluate all summaries by ``tf.summary.merge_all``, and write them to logs.
Args:
period (int): by default the callback summarizes once every epoch.
This option (if not set to 0) mak... | python | def MergeAllSummaries(period=0, run_alone=False, key=None):
"""
This callback is enabled by default.
Evaluate all summaries by ``tf.summary.merge_all``, and write them to logs.
Args:
period (int): by default the callback summarizes once every epoch.
This option (if not set to 0) mak... | [
"def",
"MergeAllSummaries",
"(",
"period",
"=",
"0",
",",
"run_alone",
"=",
"False",
",",
"key",
"=",
"None",
")",
":",
"if",
"key",
"is",
"None",
":",
"key",
"=",
"tf",
".",
"GraphKeys",
".",
"SUMMARIES",
"period",
"=",
"int",
"(",
"period",
")",
... | This callback is enabled by default.
Evaluate all summaries by ``tf.summary.merge_all``, and write them to logs.
Args:
period (int): by default the callback summarizes once every epoch.
This option (if not set to 0) makes it additionally summarize every ``period`` steps.
run_alone (... | [
"This",
"callback",
"is",
"enabled",
"by",
"default",
".",
"Evaluate",
"all",
"summaries",
"by",
"tf",
".",
"summary",
".",
"merge_all",
"and",
"write",
"them",
"to",
"logs",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/callbacks/summary.py#L119-L142 | train |
tensorpack/tensorpack | examples/DeepQNetwork/expreplay.py | ReplayMemory.append | def append(self, exp):
"""
Args:
exp (Experience):
"""
if self._curr_size < self.max_size:
self._assign(self._curr_pos, exp)
self._curr_pos = (self._curr_pos + 1) % self.max_size
self._curr_size += 1
else:
self._assign(s... | python | def append(self, exp):
"""
Args:
exp (Experience):
"""
if self._curr_size < self.max_size:
self._assign(self._curr_pos, exp)
self._curr_pos = (self._curr_pos + 1) % self.max_size
self._curr_size += 1
else:
self._assign(s... | [
"def",
"append",
"(",
"self",
",",
"exp",
")",
":",
"if",
"self",
".",
"_curr_size",
"<",
"self",
".",
"max_size",
":",
"self",
".",
"_assign",
"(",
"self",
".",
"_curr_pos",
",",
"exp",
")",
"self",
".",
"_curr_pos",
"=",
"(",
"self",
".",
"_curr_... | Args:
exp (Experience): | [
"Args",
":",
"exp",
"(",
"Experience",
")",
":"
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/DeepQNetwork/expreplay.py#L53-L64 | train |
tensorpack/tensorpack | examples/DeepQNetwork/expreplay.py | ReplayMemory.sample | def sample(self, idx):
""" return a tuple of (s,r,a,o),
where s is of shape self._output_shape, which is
[H, W, (hist_len+1) * channel] if input is (H, W, channel)"""
idx = (self._curr_pos + idx) % self._curr_size
k = self.history_len + 1
if idx + k <= self._curr_... | python | def sample(self, idx):
""" return a tuple of (s,r,a,o),
where s is of shape self._output_shape, which is
[H, W, (hist_len+1) * channel] if input is (H, W, channel)"""
idx = (self._curr_pos + idx) % self._curr_size
k = self.history_len + 1
if idx + k <= self._curr_... | [
"def",
"sample",
"(",
"self",
",",
"idx",
")",
":",
"idx",
"=",
"(",
"self",
".",
"_curr_pos",
"+",
"idx",
")",
"%",
"self",
".",
"_curr_size",
"k",
"=",
"self",
".",
"history_len",
"+",
"1",
"if",
"idx",
"+",
"k",
"<=",
"self",
".",
"_curr_size"... | return a tuple of (s,r,a,o),
where s is of shape self._output_shape, which is
[H, W, (hist_len+1) * channel] if input is (H, W, channel) | [
"return",
"a",
"tuple",
"of",
"(",
"s",
"r",
"a",
"o",
")",
"where",
"s",
"is",
"of",
"shape",
"self",
".",
"_output_shape",
"which",
"is",
"[",
"H",
"W",
"(",
"hist_len",
"+",
"1",
")",
"*",
"channel",
"]",
"if",
"input",
"is",
"(",
"H",
"W",
... | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/DeepQNetwork/expreplay.py#L66-L84 | train |
tensorpack/tensorpack | examples/DeepQNetwork/expreplay.py | EnvRunner.step | def step(self, exploration):
"""
Run the environment for one step.
If the episode ends, store the entire episode to the replay memory.
"""
old_s = self._current_ob
if self.rng.rand() <= exploration:
act = self.rng.choice(range(self.num_actions))
else:
... | python | def step(self, exploration):
"""
Run the environment for one step.
If the episode ends, store the entire episode to the replay memory.
"""
old_s = self._current_ob
if self.rng.rand() <= exploration:
act = self.rng.choice(range(self.num_actions))
else:
... | [
"def",
"step",
"(",
"self",
",",
"exploration",
")",
":",
"old_s",
"=",
"self",
".",
"_current_ob",
"if",
"self",
".",
"rng",
".",
"rand",
"(",
")",
"<=",
"exploration",
":",
"act",
"=",
"self",
".",
"rng",
".",
"choice",
"(",
"range",
"(",
"self",... | Run the environment for one step.
If the episode ends, store the entire episode to the replay memory. | [
"Run",
"the",
"environment",
"for",
"one",
"step",
".",
"If",
"the",
"episode",
"ends",
"store",
"the",
"entire",
"episode",
"to",
"the",
"replay",
"memory",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/DeepQNetwork/expreplay.py#L143-L182 | train |
tensorpack/tensorpack | examples/DeepQNetwork/expreplay.py | EnvRunner.recent_state | def recent_state(self):
"""
Get the recent state (with stacked history) of the environment.
Returns:
a list of ``hist_len-1`` elements, each of shape ``self.state_shape``
"""
expected_len = self.history_len - 1
if len(self._current_episode) >= expected_len:
... | python | def recent_state(self):
"""
Get the recent state (with stacked history) of the environment.
Returns:
a list of ``hist_len-1`` elements, each of shape ``self.state_shape``
"""
expected_len = self.history_len - 1
if len(self._current_episode) >= expected_len:
... | [
"def",
"recent_state",
"(",
"self",
")",
":",
"expected_len",
"=",
"self",
".",
"history_len",
"-",
"1",
"if",
"len",
"(",
"self",
".",
"_current_episode",
")",
">=",
"expected_len",
":",
"return",
"[",
"k",
".",
"state",
"for",
"k",
"in",
"self",
".",... | Get the recent state (with stacked history) of the environment.
Returns:
a list of ``hist_len-1`` elements, each of shape ``self.state_shape`` | [
"Get",
"the",
"recent",
"state",
"(",
"with",
"stacked",
"history",
")",
"of",
"the",
"environment",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/DeepQNetwork/expreplay.py#L184-L197 | train |
tensorpack/tensorpack | examples/DeepQNetwork/expreplay.py | EnvRunnerManager.step | def step(self, exploration):
"""
Execute one step in any of the runners.
"""
if len(self._runners) > 1:
self._populate_job_queue.put(exploration)
else:
self._runners[0].step(exploration) | python | def step(self, exploration):
"""
Execute one step in any of the runners.
"""
if len(self._runners) > 1:
self._populate_job_queue.put(exploration)
else:
self._runners[0].step(exploration) | [
"def",
"step",
"(",
"self",
",",
"exploration",
")",
":",
"if",
"len",
"(",
"self",
".",
"_runners",
")",
">",
"1",
":",
"self",
".",
"_populate_job_queue",
".",
"put",
"(",
"exploration",
")",
"else",
":",
"self",
".",
"_runners",
"[",
"0",
"]",
"... | Execute one step in any of the runners. | [
"Execute",
"one",
"step",
"in",
"any",
"of",
"the",
"runners",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/DeepQNetwork/expreplay.py#L233-L240 | train |
tensorpack/tensorpack | examples/DeepQNetwork/expreplay.py | EnvRunnerManager.reset_stats | def reset_stats(self):
"""
Returns:
mean, max: two stats of the runners, to be added to backend
"""
scores = list(itertools.chain.from_iterable([v.total_scores for v in self._runners]))
for v in self._runners:
v.total_scores.clear()
try:
... | python | def reset_stats(self):
"""
Returns:
mean, max: two stats of the runners, to be added to backend
"""
scores = list(itertools.chain.from_iterable([v.total_scores for v in self._runners]))
for v in self._runners:
v.total_scores.clear()
try:
... | [
"def",
"reset_stats",
"(",
"self",
")",
":",
"scores",
"=",
"list",
"(",
"itertools",
".",
"chain",
".",
"from_iterable",
"(",
"[",
"v",
".",
"total_scores",
"for",
"v",
"in",
"self",
".",
"_runners",
"]",
")",
")",
"for",
"v",
"in",
"self",
".",
"... | Returns:
mean, max: two stats of the runners, to be added to backend | [
"Returns",
":",
"mean",
"max",
":",
"two",
"stats",
"of",
"the",
"runners",
"to",
"be",
"added",
"to",
"backend"
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/DeepQNetwork/expreplay.py#L242-L255 | train |
tensorpack/tensorpack | tensorpack/callbacks/group.py | CallbackTimeLogger.log | def log(self):
""" log the time of some heavy callbacks """
if self.tot < 3:
return
msgs = []
for name, t in self.times:
if t / self.tot > 0.3 and t > 1:
msgs.append(name + ": " + humanize_time_delta(t))
logger.info(
"Callbacks... | python | def log(self):
""" log the time of some heavy callbacks """
if self.tot < 3:
return
msgs = []
for name, t in self.times:
if t / self.tot > 0.3 and t > 1:
msgs.append(name + ": " + humanize_time_delta(t))
logger.info(
"Callbacks... | [
"def",
"log",
"(",
"self",
")",
":",
"if",
"self",
".",
"tot",
"<",
"3",
":",
"return",
"msgs",
"=",
"[",
"]",
"for",
"name",
",",
"t",
"in",
"self",
".",
"times",
":",
"if",
"t",
"/",
"self",
".",
"tot",
">",
"0.3",
"and",
"t",
">",
"1",
... | log the time of some heavy callbacks | [
"log",
"the",
"time",
"of",
"some",
"heavy",
"callbacks"
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/callbacks/group.py#L37-L48 | train |
tensorpack/tensorpack | tensorpack/tfutils/tower.py | TowerContext | def TowerContext(tower_name, is_training, vs_name=''):
"""
The context for a tower function, containing metadata about the current tower.
Tensorpack trainers use :class:`TowerContext` to manage tower function.
Many tensorpack layers have to be called under a :class:`TowerContext`.
Example:
.. ... | python | def TowerContext(tower_name, is_training, vs_name=''):
"""
The context for a tower function, containing metadata about the current tower.
Tensorpack trainers use :class:`TowerContext` to manage tower function.
Many tensorpack layers have to be called under a :class:`TowerContext`.
Example:
.. ... | [
"def",
"TowerContext",
"(",
"tower_name",
",",
"is_training",
",",
"vs_name",
"=",
"''",
")",
":",
"if",
"is_training",
":",
"return",
"TrainTowerContext",
"(",
"tower_name",
",",
"vs_name",
"=",
"vs_name",
")",
"else",
":",
"return",
"PredictTowerContext",
"(... | The context for a tower function, containing metadata about the current tower.
Tensorpack trainers use :class:`TowerContext` to manage tower function.
Many tensorpack layers have to be called under a :class:`TowerContext`.
Example:
.. code-block:: python
with TowerContext('', is_training=True... | [
"The",
"context",
"for",
"a",
"tower",
"function",
"containing",
"metadata",
"about",
"the",
"current",
"tower",
".",
"Tensorpack",
"trainers",
"use",
":",
"class",
":",
"TowerContext",
"to",
"manage",
"tower",
"function",
".",
"Many",
"tensorpack",
"layers",
... | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/tfutils/tower.py#L229-L245 | train |
tensorpack/tensorpack | tensorpack/tfutils/tower.py | TowerTensorHandles.training | def training(self):
"""
Returns:
A :class:`TowerTensorHandles`, containing only the training towers.
"""
handles = [h for h in self._handles if h.is_training]
return TowerTensorHandles(handles) | python | def training(self):
"""
Returns:
A :class:`TowerTensorHandles`, containing only the training towers.
"""
handles = [h for h in self._handles if h.is_training]
return TowerTensorHandles(handles) | [
"def",
"training",
"(",
"self",
")",
":",
"handles",
"=",
"[",
"h",
"for",
"h",
"in",
"self",
".",
"_handles",
"if",
"h",
".",
"is_training",
"]",
"return",
"TowerTensorHandles",
"(",
"handles",
")"
] | Returns:
A :class:`TowerTensorHandles`, containing only the training towers. | [
"Returns",
":",
"A",
":",
"class",
":",
"TowerTensorHandles",
"containing",
"only",
"the",
"training",
"towers",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/tfutils/tower.py#L338-L344 | train |
tensorpack/tensorpack | tensorpack/tfutils/tower.py | TowerTensorHandles.inference | def inference(self):
"""
Returns:
A :class:`TowerTensorHandles`, containing only the inference towers.
"""
handles = [h for h in self._handles if not h.is_training]
return TowerTensorHandles(handles) | python | def inference(self):
"""
Returns:
A :class:`TowerTensorHandles`, containing only the inference towers.
"""
handles = [h for h in self._handles if not h.is_training]
return TowerTensorHandles(handles) | [
"def",
"inference",
"(",
"self",
")",
":",
"handles",
"=",
"[",
"h",
"for",
"h",
"in",
"self",
".",
"_handles",
"if",
"not",
"h",
".",
"is_training",
"]",
"return",
"TowerTensorHandles",
"(",
"handles",
")"
] | Returns:
A :class:`TowerTensorHandles`, containing only the inference towers. | [
"Returns",
":",
"A",
":",
"class",
":",
"TowerTensorHandles",
"containing",
"only",
"the",
"inference",
"towers",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/tfutils/tower.py#L346-L352 | train |
tensorpack/tensorpack | tensorpack/tfutils/tower.py | TowerTensorHandle.get_tensor | def get_tensor(self, name):
"""
Get a tensor in this tower. The name can be:
1. The name of the tensor without any tower prefix.
2. A name in the input signature, if it is used when building the tower.
In the second case, this method will return the tensor that's used as the c... | python | def get_tensor(self, name):
"""
Get a tensor in this tower. The name can be:
1. The name of the tensor without any tower prefix.
2. A name in the input signature, if it is used when building the tower.
In the second case, this method will return the tensor that's used as the c... | [
"def",
"get_tensor",
"(",
"self",
",",
"name",
")",
":",
"name",
"=",
"get_op_tensor_name",
"(",
"name",
")",
"[",
"1",
"]",
"if",
"len",
"(",
"self",
".",
"ns_name",
")",
":",
"name_with_ns",
"=",
"self",
".",
"ns_name",
"+",
"\"/\"",
"+",
"name",
... | Get a tensor in this tower. The name can be:
1. The name of the tensor without any tower prefix.
2. A name in the input signature, if it is used when building the tower.
In the second case, this method will return the tensor that's used as the corresponding
input to the tower. Note th... | [
"Get",
"a",
"tensor",
"in",
"this",
"tower",
".",
"The",
"name",
"can",
"be",
":"
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/tfutils/tower.py#L384-L415 | train |
tensorpack/tensorpack | tensorpack/tfutils/tower.py | TowerTensorHandle.get_variable | def get_variable(self, name):
"""
Get a variable used in this tower.
The name should not contain the variable scope prefix of the tower.
When the tower has the same variable scope and name scope, this is equivalent to
:meth:`get_tensor`.
"""
name = get_op_tensor_... | python | def get_variable(self, name):
"""
Get a variable used in this tower.
The name should not contain the variable scope prefix of the tower.
When the tower has the same variable scope and name scope, this is equivalent to
:meth:`get_tensor`.
"""
name = get_op_tensor_... | [
"def",
"get_variable",
"(",
"self",
",",
"name",
")",
":",
"name",
"=",
"get_op_tensor_name",
"(",
"name",
")",
"[",
"1",
"]",
"if",
"len",
"(",
"self",
".",
"vs_name",
")",
":",
"name_with_vs",
"=",
"self",
".",
"vs_name",
"+",
"\"/\"",
"+",
"name",... | Get a variable used in this tower.
The name should not contain the variable scope prefix of the tower.
When the tower has the same variable scope and name scope, this is equivalent to
:meth:`get_tensor`. | [
"Get",
"a",
"variable",
"used",
"in",
"this",
"tower",
".",
"The",
"name",
"should",
"not",
"contain",
"the",
"variable",
"scope",
"prefix",
"of",
"the",
"tower",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/tfutils/tower.py#L429-L442 | train |
tensorpack/tensorpack | tensorpack/tfutils/tower.py | TowerTensorHandle.get_collection | def get_collection(self, key=None, name=None):
"""
See :meth:`BaseTowerContext.get_collection_in_tower`.
Args:
key (str): the key of the collection
name: deprecated
"""
if name is not None:
logger.warn("TowerTensorHandle.get_collection(name=..... | python | def get_collection(self, key=None, name=None):
"""
See :meth:`BaseTowerContext.get_collection_in_tower`.
Args:
key (str): the key of the collection
name: deprecated
"""
if name is not None:
logger.warn("TowerTensorHandle.get_collection(name=..... | [
"def",
"get_collection",
"(",
"self",
",",
"key",
"=",
"None",
",",
"name",
"=",
"None",
")",
":",
"if",
"name",
"is",
"not",
"None",
":",
"logger",
".",
"warn",
"(",
"\"TowerTensorHandle.get_collection(name=..) was renamed to (key=..) !\"",
")",
"key",
"=",
"... | See :meth:`BaseTowerContext.get_collection_in_tower`.
Args:
key (str): the key of the collection
name: deprecated | [
"See",
":",
"meth",
":",
"BaseTowerContext",
".",
"get_collection_in_tower",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/tfutils/tower.py#L450-L461 | train |
tensorpack/tensorpack | tensorpack/utils/fs.py | mkdir_p | def mkdir_p(dirname):
""" Like "mkdir -p", make a dir recursively, but do nothing if the dir exists
Args:
dirname(str):
"""
assert dirname is not None
if dirname == '' or os.path.isdir(dirname):
return
try:
os.makedirs(dirname)
except OSError as e:
if e.errno... | python | def mkdir_p(dirname):
""" Like "mkdir -p", make a dir recursively, but do nothing if the dir exists
Args:
dirname(str):
"""
assert dirname is not None
if dirname == '' or os.path.isdir(dirname):
return
try:
os.makedirs(dirname)
except OSError as e:
if e.errno... | [
"def",
"mkdir_p",
"(",
"dirname",
")",
":",
"assert",
"dirname",
"is",
"not",
"None",
"if",
"dirname",
"==",
"''",
"or",
"os",
".",
"path",
".",
"isdir",
"(",
"dirname",
")",
":",
"return",
"try",
":",
"os",
".",
"makedirs",
"(",
"dirname",
")",
"e... | Like "mkdir -p", make a dir recursively, but do nothing if the dir exists
Args:
dirname(str): | [
"Like",
"mkdir",
"-",
"p",
"make",
"a",
"dir",
"recursively",
"but",
"do",
"nothing",
"if",
"the",
"dir",
"exists"
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/fs.py#L16-L29 | train |
tensorpack/tensorpack | tensorpack/utils/fs.py | download | def download(url, dir, filename=None, expect_size=None):
"""
Download URL to a directory.
Will figure out the filename automatically from URL, if not given.
"""
mkdir_p(dir)
if filename is None:
filename = url.split('/')[-1]
fpath = os.path.join(dir, filename)
if os.path.isfile(... | python | def download(url, dir, filename=None, expect_size=None):
"""
Download URL to a directory.
Will figure out the filename automatically from URL, if not given.
"""
mkdir_p(dir)
if filename is None:
filename = url.split('/')[-1]
fpath = os.path.join(dir, filename)
if os.path.isfile(... | [
"def",
"download",
"(",
"url",
",",
"dir",
",",
"filename",
"=",
"None",
",",
"expect_size",
"=",
"None",
")",
":",
"mkdir_p",
"(",
"dir",
")",
"if",
"filename",
"is",
"None",
":",
"filename",
"=",
"url",
".",
"split",
"(",
"'/'",
")",
"[",
"-",
... | Download URL to a directory.
Will figure out the filename automatically from URL, if not given. | [
"Download",
"URL",
"to",
"a",
"directory",
".",
"Will",
"figure",
"out",
"the",
"filename",
"automatically",
"from",
"URL",
"if",
"not",
"given",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/fs.py#L32-L74 | train |
tensorpack/tensorpack | tensorpack/utils/fs.py | recursive_walk | def recursive_walk(rootdir):
"""
Yields:
str: All files in rootdir, recursively.
"""
for r, dirs, files in os.walk(rootdir):
for f in files:
yield os.path.join(r, f) | python | def recursive_walk(rootdir):
"""
Yields:
str: All files in rootdir, recursively.
"""
for r, dirs, files in os.walk(rootdir):
for f in files:
yield os.path.join(r, f) | [
"def",
"recursive_walk",
"(",
"rootdir",
")",
":",
"for",
"r",
",",
"dirs",
",",
"files",
"in",
"os",
".",
"walk",
"(",
"rootdir",
")",
":",
"for",
"f",
"in",
"files",
":",
"yield",
"os",
".",
"path",
".",
"join",
"(",
"r",
",",
"f",
")"
] | Yields:
str: All files in rootdir, recursively. | [
"Yields",
":",
"str",
":",
"All",
"files",
"in",
"rootdir",
"recursively",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/fs.py#L77-L84 | train |
tensorpack/tensorpack | tensorpack/utils/fs.py | get_dataset_path | def get_dataset_path(*args):
"""
Get the path to some dataset under ``$TENSORPACK_DATASET``.
Args:
args: strings to be joined to form path.
Returns:
str: path to the dataset.
"""
d = os.environ.get('TENSORPACK_DATASET', None)
if d is None:
d = os.path.join(os.path.e... | python | def get_dataset_path(*args):
"""
Get the path to some dataset under ``$TENSORPACK_DATASET``.
Args:
args: strings to be joined to form path.
Returns:
str: path to the dataset.
"""
d = os.environ.get('TENSORPACK_DATASET', None)
if d is None:
d = os.path.join(os.path.e... | [
"def",
"get_dataset_path",
"(",
"*",
"args",
")",
":",
"d",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"'TENSORPACK_DATASET'",
",",
"None",
")",
"if",
"d",
"is",
"None",
":",
"d",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",... | Get the path to some dataset under ``$TENSORPACK_DATASET``.
Args:
args: strings to be joined to form path.
Returns:
str: path to the dataset. | [
"Get",
"the",
"path",
"to",
"some",
"dataset",
"under",
"$TENSORPACK_DATASET",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/fs.py#L87-L106 | train |
tensorpack/tensorpack | tensorpack/tfutils/collection.py | backup_collection | def backup_collection(keys=None):
"""
Args:
keys (list): list of collection keys to backup.
Defaults to all keys in the graph.
Returns:
dict: the backup
"""
if keys is None:
keys = tf.get_default_graph().get_all_collection_keys()
ret = {}
assert isinstanc... | python | def backup_collection(keys=None):
"""
Args:
keys (list): list of collection keys to backup.
Defaults to all keys in the graph.
Returns:
dict: the backup
"""
if keys is None:
keys = tf.get_default_graph().get_all_collection_keys()
ret = {}
assert isinstanc... | [
"def",
"backup_collection",
"(",
"keys",
"=",
"None",
")",
":",
"if",
"keys",
"is",
"None",
":",
"keys",
"=",
"tf",
".",
"get_default_graph",
"(",
")",
".",
"get_all_collection_keys",
"(",
")",
"ret",
"=",
"{",
"}",
"assert",
"isinstance",
"(",
"keys",
... | Args:
keys (list): list of collection keys to backup.
Defaults to all keys in the graph.
Returns:
dict: the backup | [
"Args",
":",
"keys",
"(",
"list",
")",
":",
"list",
"of",
"collection",
"keys",
"to",
"backup",
".",
"Defaults",
"to",
"all",
"keys",
"in",
"the",
"graph",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/tfutils/collection.py#L19-L34 | train |
tensorpack/tensorpack | tensorpack/tfutils/collection.py | restore_collection | def restore_collection(backup):
"""
Restore from a collection backup.
Args:
backup (dict):
"""
for k, v in six.iteritems(backup):
del tf.get_collection_ref(k)[:]
tf.get_collection_ref(k).extend(v) | python | def restore_collection(backup):
"""
Restore from a collection backup.
Args:
backup (dict):
"""
for k, v in six.iteritems(backup):
del tf.get_collection_ref(k)[:]
tf.get_collection_ref(k).extend(v) | [
"def",
"restore_collection",
"(",
"backup",
")",
":",
"for",
"k",
",",
"v",
"in",
"six",
".",
"iteritems",
"(",
"backup",
")",
":",
"del",
"tf",
".",
"get_collection_ref",
"(",
"k",
")",
"[",
":",
"]",
"tf",
".",
"get_collection_ref",
"(",
"k",
")",
... | Restore from a collection backup.
Args:
backup (dict): | [
"Restore",
"from",
"a",
"collection",
"backup",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/tfutils/collection.py#L37-L46 | train |
tensorpack/tensorpack | tensorpack/tfutils/collection.py | CollectionGuard.get_collection_in_tower | def get_collection_in_tower(self, key):
"""
Get items from this collection that are added in the current tower.
"""
new = tf.get_collection(key)
old = set(self.original.get(key, []))
# persist the order in new
return [x for x in new if x not in old] | python | def get_collection_in_tower(self, key):
"""
Get items from this collection that are added in the current tower.
"""
new = tf.get_collection(key)
old = set(self.original.get(key, []))
# persist the order in new
return [x for x in new if x not in old] | [
"def",
"get_collection_in_tower",
"(",
"self",
",",
"key",
")",
":",
"new",
"=",
"tf",
".",
"get_collection",
"(",
"key",
")",
"old",
"=",
"set",
"(",
"self",
".",
"original",
".",
"get",
"(",
"key",
",",
"[",
"]",
")",
")",
"# persist the order in new... | Get items from this collection that are added in the current tower. | [
"Get",
"items",
"from",
"this",
"collection",
"that",
"are",
"added",
"in",
"the",
"current",
"tower",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/tfutils/collection.py#L168-L175 | train |
tensorpack/tensorpack | examples/PennTreebank/reader.py | ptb_producer | def ptb_producer(raw_data, batch_size, num_steps, name=None):
"""Iterate on the raw PTB data.
This chunks up raw_data into batches of examples and returns Tensors that
are drawn from these batches.
Args:
raw_data: one of the raw data outputs from ptb_raw_data.
batch_size: int, the batch size.
num_... | python | def ptb_producer(raw_data, batch_size, num_steps, name=None):
"""Iterate on the raw PTB data.
This chunks up raw_data into batches of examples and returns Tensors that
are drawn from these batches.
Args:
raw_data: one of the raw data outputs from ptb_raw_data.
batch_size: int, the batch size.
num_... | [
"def",
"ptb_producer",
"(",
"raw_data",
",",
"batch_size",
",",
"num_steps",
",",
"name",
"=",
"None",
")",
":",
"with",
"tf",
".",
"name_scope",
"(",
"name",
",",
"\"PTBProducer\"",
",",
"[",
"raw_data",
",",
"batch_size",
",",
"num_steps",
"]",
")",
":... | Iterate on the raw PTB data.
This chunks up raw_data into batches of examples and returns Tensors that
are drawn from these batches.
Args:
raw_data: one of the raw data outputs from ptb_raw_data.
batch_size: int, the batch size.
num_steps: int, the number of unrolls.
name: the name of this opera... | [
"Iterate",
"on",
"the",
"raw",
"PTB",
"data",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/PennTreebank/reader.py#L78-L119 | train |
tensorpack/tensorpack | tensorpack/utils/logger.py | set_logger_dir | def set_logger_dir(dirname, action=None):
"""
Set the directory for global logging.
Args:
dirname(str): log directory
action(str): an action of ["k","d","q"] to be performed
when the directory exists. Will ask user by default.
"d": delete the directory. Note tha... | python | def set_logger_dir(dirname, action=None):
"""
Set the directory for global logging.
Args:
dirname(str): log directory
action(str): an action of ["k","d","q"] to be performed
when the directory exists. Will ask user by default.
"d": delete the directory. Note tha... | [
"def",
"set_logger_dir",
"(",
"dirname",
",",
"action",
"=",
"None",
")",
":",
"global",
"LOG_DIR",
",",
"_FILE_HANDLER",
"if",
"_FILE_HANDLER",
":",
"# unload and close the old file handler, so that we may safely delete the logger directory",
"_logger",
".",
"removeHandler",... | Set the directory for global logging.
Args:
dirname(str): log directory
action(str): an action of ["k","d","q"] to be performed
when the directory exists. Will ask user by default.
"d": delete the directory. Note that the deletion may fail when
the direc... | [
"Set",
"the",
"directory",
"for",
"global",
"logging",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/logger.py#L93-L150 | train |
tensorpack/tensorpack | tensorpack/utils/logger.py | auto_set_dir | def auto_set_dir(action=None, name=None):
"""
Use :func:`logger.set_logger_dir` to set log directory to
"./train_log/{scriptname}:{name}". "scriptname" is the name of the main python file currently running"""
mod = sys.modules['__main__']
basename = os.path.basename(mod.__file__)
auto_dirname = ... | python | def auto_set_dir(action=None, name=None):
"""
Use :func:`logger.set_logger_dir` to set log directory to
"./train_log/{scriptname}:{name}". "scriptname" is the name of the main python file currently running"""
mod = sys.modules['__main__']
basename = os.path.basename(mod.__file__)
auto_dirname = ... | [
"def",
"auto_set_dir",
"(",
"action",
"=",
"None",
",",
"name",
"=",
"None",
")",
":",
"mod",
"=",
"sys",
".",
"modules",
"[",
"'__main__'",
"]",
"basename",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"mod",
".",
"__file__",
")",
"auto_dirname",
"... | Use :func:`logger.set_logger_dir` to set log directory to
"./train_log/{scriptname}:{name}". "scriptname" is the name of the main python file currently running | [
"Use",
":",
"func",
":",
"logger",
".",
"set_logger_dir",
"to",
"set",
"log",
"directory",
"to",
".",
"/",
"train_log",
"/",
"{",
"scriptname",
"}",
":",
"{",
"name",
"}",
".",
"scriptname",
"is",
"the",
"name",
"of",
"the",
"main",
"python",
"file",
... | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/logger.py#L153-L162 | train |
tensorpack/tensorpack | examples/HED/hed.py | class_balanced_sigmoid_cross_entropy | def class_balanced_sigmoid_cross_entropy(logits, label, name='cross_entropy_loss'):
"""
The class-balanced cross entropy loss,
as in `Holistically-Nested Edge Detection
<http://arxiv.org/abs/1504.06375>`_.
Args:
logits: of shape (b, ...).
label: of the same shape. the ground truth i... | python | def class_balanced_sigmoid_cross_entropy(logits, label, name='cross_entropy_loss'):
"""
The class-balanced cross entropy loss,
as in `Holistically-Nested Edge Detection
<http://arxiv.org/abs/1504.06375>`_.
Args:
logits: of shape (b, ...).
label: of the same shape. the ground truth i... | [
"def",
"class_balanced_sigmoid_cross_entropy",
"(",
"logits",
",",
"label",
",",
"name",
"=",
"'cross_entropy_loss'",
")",
":",
"with",
"tf",
".",
"name_scope",
"(",
"'class_balanced_sigmoid_cross_entropy'",
")",
":",
"y",
"=",
"tf",
".",
"cast",
"(",
"label",
"... | The class-balanced cross entropy loss,
as in `Holistically-Nested Edge Detection
<http://arxiv.org/abs/1504.06375>`_.
Args:
logits: of shape (b, ...).
label: of the same shape. the ground truth in {0,1}.
Returns:
class-balanced cross entropy loss. | [
"The",
"class",
"-",
"balanced",
"cross",
"entropy",
"loss",
"as",
"in",
"Holistically",
"-",
"Nested",
"Edge",
"Detection",
"<http",
":",
"//",
"arxiv",
".",
"org",
"/",
"abs",
"/",
"1504",
".",
"06375",
">",
"_",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/HED/hed.py#L21-L44 | train |
tensorpack/tensorpack | examples/HED/hed.py | CaffeBilinearUpSample | def CaffeBilinearUpSample(x, shape):
"""
Deterministic bilinearly-upsample the input images.
It is implemented by deconvolution with "BilinearFiller" in Caffe.
It is aimed to mimic caffe behavior.
Args:
x (tf.Tensor): a NCHW tensor
shape (int): the upsample factor
Returns:
... | python | def CaffeBilinearUpSample(x, shape):
"""
Deterministic bilinearly-upsample the input images.
It is implemented by deconvolution with "BilinearFiller" in Caffe.
It is aimed to mimic caffe behavior.
Args:
x (tf.Tensor): a NCHW tensor
shape (int): the upsample factor
Returns:
... | [
"def",
"CaffeBilinearUpSample",
"(",
"x",
",",
"shape",
")",
":",
"inp_shape",
"=",
"x",
".",
"shape",
".",
"as_list",
"(",
")",
"ch",
"=",
"inp_shape",
"[",
"1",
"]",
"assert",
"ch",
"==",
"1",
",",
"\"This layer only works for channel=1\"",
"# for a versio... | Deterministic bilinearly-upsample the input images.
It is implemented by deconvolution with "BilinearFiller" in Caffe.
It is aimed to mimic caffe behavior.
Args:
x (tf.Tensor): a NCHW tensor
shape (int): the upsample factor
Returns:
tf.Tensor: a NCHW tensor. | [
"Deterministic",
"bilinearly",
"-",
"upsample",
"the",
"input",
"images",
".",
"It",
"is",
"implemented",
"by",
"deconvolution",
"with",
"BilinearFiller",
"in",
"Caffe",
".",
"It",
"is",
"aimed",
"to",
"mimic",
"caffe",
"behavior",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/HED/hed.py#L48-L101 | train |
tensorpack/tensorpack | tensorpack/dataflow/parallel.py | _MultiProcessZMQDataFlow.reset_state | def reset_state(self):
"""
All forked dataflows should only be reset **once and only once** in spawned processes.
Subclasses should call this method with super.
"""
assert not self._reset_done, "reset_state() was called twice! This violates the API of DataFlow!"
self._res... | python | def reset_state(self):
"""
All forked dataflows should only be reset **once and only once** in spawned processes.
Subclasses should call this method with super.
"""
assert not self._reset_done, "reset_state() was called twice! This violates the API of DataFlow!"
self._res... | [
"def",
"reset_state",
"(",
"self",
")",
":",
"assert",
"not",
"self",
".",
"_reset_done",
",",
"\"reset_state() was called twice! This violates the API of DataFlow!\"",
"self",
".",
"_reset_done",
"=",
"True",
"# __del__ not guaranteed to get called at exit",
"atexit",
".",
... | All forked dataflows should only be reset **once and only once** in spawned processes.
Subclasses should call this method with super. | [
"All",
"forked",
"dataflows",
"should",
"only",
"be",
"reset",
"**",
"once",
"and",
"only",
"once",
"**",
"in",
"spawned",
"processes",
".",
"Subclasses",
"should",
"call",
"this",
"method",
"with",
"super",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/dataflow/parallel.py#L92-L101 | train |
tensorpack/tensorpack | tensorpack/compat/tensor_spec.py | TensorSpec.is_compatible_with | def is_compatible_with(self, spec_or_tensor):
"""Returns True if spec_or_tensor is compatible with this TensorSpec.
Two tensors are considered compatible if they have the same dtype
and their shapes are compatible (see `tf.TensorShape.is_compatible_with`).
Args:
spec_or_tensor: A tf.TensorSpec o... | python | def is_compatible_with(self, spec_or_tensor):
"""Returns True if spec_or_tensor is compatible with this TensorSpec.
Two tensors are considered compatible if they have the same dtype
and their shapes are compatible (see `tf.TensorShape.is_compatible_with`).
Args:
spec_or_tensor: A tf.TensorSpec o... | [
"def",
"is_compatible_with",
"(",
"self",
",",
"spec_or_tensor",
")",
":",
"return",
"(",
"self",
".",
"_dtype",
".",
"is_compatible_with",
"(",
"spec_or_tensor",
".",
"dtype",
")",
"and",
"self",
".",
"_shape",
".",
"is_compatible_with",
"(",
"spec_or_tensor",
... | Returns True if spec_or_tensor is compatible with this TensorSpec.
Two tensors are considered compatible if they have the same dtype
and their shapes are compatible (see `tf.TensorShape.is_compatible_with`).
Args:
spec_or_tensor: A tf.TensorSpec or a tf.Tensor
Returns:
True if spec_or_ten... | [
"Returns",
"True",
"if",
"spec_or_tensor",
"is",
"compatible",
"with",
"this",
"TensorSpec",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/compat/tensor_spec.py#L75-L88 | train |
tensorpack/tensorpack | tensorpack/tfutils/model_utils.py | describe_trainable_vars | def describe_trainable_vars():
"""
Print a description of the current model parameters.
Skip variables starting with "tower", as they are just duplicates built by data-parallel logic.
"""
train_vars = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES)
if len(train_vars) == 0:
logger.war... | python | def describe_trainable_vars():
"""
Print a description of the current model parameters.
Skip variables starting with "tower", as they are just duplicates built by data-parallel logic.
"""
train_vars = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES)
if len(train_vars) == 0:
logger.war... | [
"def",
"describe_trainable_vars",
"(",
")",
":",
"train_vars",
"=",
"tf",
".",
"get_collection",
"(",
"tf",
".",
"GraphKeys",
".",
"TRAINABLE_VARIABLES",
")",
"if",
"len",
"(",
"train_vars",
")",
"==",
"0",
":",
"logger",
".",
"warn",
"(",
"\"No trainable va... | Print a description of the current model parameters.
Skip variables starting with "tower", as they are just duplicates built by data-parallel logic. | [
"Print",
"a",
"description",
"of",
"the",
"current",
"model",
"parameters",
".",
"Skip",
"variables",
"starting",
"with",
"tower",
"as",
"they",
"are",
"just",
"duplicates",
"built",
"by",
"data",
"-",
"parallel",
"logic",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/tfutils/model_utils.py#L15-L67 | train |
tensorpack/tensorpack | tensorpack/tfutils/model_utils.py | get_shape_str | def get_shape_str(tensors):
"""
Internally used by layer registry, to print shapes of inputs/outputs of layers.
Args:
tensors (list or tf.Tensor): a tensor or a list of tensors
Returns:
str: a string to describe the shape
"""
if isinstance(tensors, (list, tuple)):
for v ... | python | def get_shape_str(tensors):
"""
Internally used by layer registry, to print shapes of inputs/outputs of layers.
Args:
tensors (list or tf.Tensor): a tensor or a list of tensors
Returns:
str: a string to describe the shape
"""
if isinstance(tensors, (list, tuple)):
for v ... | [
"def",
"get_shape_str",
"(",
"tensors",
")",
":",
"if",
"isinstance",
"(",
"tensors",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"for",
"v",
"in",
"tensors",
":",
"assert",
"isinstance",
"(",
"v",
",",
"(",
"tf",
".",
"Tensor",
",",
"tf",
".",
... | Internally used by layer registry, to print shapes of inputs/outputs of layers.
Args:
tensors (list or tf.Tensor): a tensor or a list of tensors
Returns:
str: a string to describe the shape | [
"Internally",
"used",
"by",
"layer",
"registry",
"to",
"print",
"shapes",
"of",
"inputs",
"/",
"outputs",
"of",
"layers",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/tfutils/model_utils.py#L70-L87 | train |
tensorpack/tensorpack | examples/SimilarityLearning/mnist-embeddings.py | contrastive_loss | def contrastive_loss(left, right, y, margin, extra=False, scope="constrastive_loss"):
r"""Loss for Siamese networks as described in the paper:
`Learning a Similarity Metric Discriminatively, with Application to Face
Verification <http://yann.lecun.com/exdb/publis/pdf/chopra-05.pdf>`_ by Chopra et al.
.... | python | def contrastive_loss(left, right, y, margin, extra=False, scope="constrastive_loss"):
r"""Loss for Siamese networks as described in the paper:
`Learning a Similarity Metric Discriminatively, with Application to Face
Verification <http://yann.lecun.com/exdb/publis/pdf/chopra-05.pdf>`_ by Chopra et al.
.... | [
"def",
"contrastive_loss",
"(",
"left",
",",
"right",
",",
"y",
",",
"margin",
",",
"extra",
"=",
"False",
",",
"scope",
"=",
"\"constrastive_loss\"",
")",
":",
"with",
"tf",
".",
"name_scope",
"(",
"scope",
")",
":",
"y",
"=",
"tf",
".",
"cast",
"("... | r"""Loss for Siamese networks as described in the paper:
`Learning a Similarity Metric Discriminatively, with Application to Face
Verification <http://yann.lecun.com/exdb/publis/pdf/chopra-05.pdf>`_ by Chopra et al.
.. math::
\frac{1}{2} [y \cdot d^2 + (1-y) \cdot \max(0, m - d)^2], d = \Vert l - r... | [
"r",
"Loss",
"for",
"Siamese",
"networks",
"as",
"described",
"in",
"the",
"paper",
":",
"Learning",
"a",
"Similarity",
"Metric",
"Discriminatively",
"with",
"Application",
"to",
"Face",
"Verification",
"<http",
":",
"//",
"yann",
".",
"lecun",
".",
"com",
"... | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/SimilarityLearning/mnist-embeddings.py#L25-L65 | train |
tensorpack/tensorpack | examples/SimilarityLearning/mnist-embeddings.py | siamese_cosine_loss | def siamese_cosine_loss(left, right, y, scope="cosine_loss"):
r"""Loss for Siamese networks (cosine version).
Same as :func:`contrastive_loss` but with different similarity measurement.
.. math::
[\frac{l \cdot r}{\lVert l\rVert \lVert r\rVert} - (2y-1)]^2
Args:
left (tf.Tensor): left ... | python | def siamese_cosine_loss(left, right, y, scope="cosine_loss"):
r"""Loss for Siamese networks (cosine version).
Same as :func:`contrastive_loss` but with different similarity measurement.
.. math::
[\frac{l \cdot r}{\lVert l\rVert \lVert r\rVert} - (2y-1)]^2
Args:
left (tf.Tensor): left ... | [
"def",
"siamese_cosine_loss",
"(",
"left",
",",
"right",
",",
"y",
",",
"scope",
"=",
"\"cosine_loss\"",
")",
":",
"def",
"l2_norm",
"(",
"t",
",",
"eps",
"=",
"1e-12",
")",
":",
"\"\"\"\n Returns:\n tf.Tensor: norm of 2D input tensor on axis 1\n ... | r"""Loss for Siamese networks (cosine version).
Same as :func:`contrastive_loss` but with different similarity measurement.
.. math::
[\frac{l \cdot r}{\lVert l\rVert \lVert r\rVert} - (2y-1)]^2
Args:
left (tf.Tensor): left feature vectors of shape [Batch, N].
right (tf.Tensor): ri... | [
"r",
"Loss",
"for",
"Siamese",
"networks",
"(",
"cosine",
"version",
")",
".",
"Same",
"as",
":",
"func",
":",
"contrastive_loss",
"but",
"with",
"different",
"similarity",
"measurement",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/SimilarityLearning/mnist-embeddings.py#L68-L96 | train |
tensorpack/tensorpack | examples/SimilarityLearning/mnist-embeddings.py | triplet_loss | def triplet_loss(anchor, positive, negative, margin, extra=False, scope="triplet_loss"):
r"""Loss for Triplet networks as described in the paper:
`FaceNet: A Unified Embedding for Face Recognition and Clustering
<https://arxiv.org/abs/1503.03832>`_
by Schroff et al.
Learn embeddings from an anchor ... | python | def triplet_loss(anchor, positive, negative, margin, extra=False, scope="triplet_loss"):
r"""Loss for Triplet networks as described in the paper:
`FaceNet: A Unified Embedding for Face Recognition and Clustering
<https://arxiv.org/abs/1503.03832>`_
by Schroff et al.
Learn embeddings from an anchor ... | [
"def",
"triplet_loss",
"(",
"anchor",
",",
"positive",
",",
"negative",
",",
"margin",
",",
"extra",
"=",
"False",
",",
"scope",
"=",
"\"triplet_loss\"",
")",
":",
"with",
"tf",
".",
"name_scope",
"(",
"scope",
")",
":",
"d_pos",
"=",
"tf",
".",
"reduc... | r"""Loss for Triplet networks as described in the paper:
`FaceNet: A Unified Embedding for Face Recognition and Clustering
<https://arxiv.org/abs/1503.03832>`_
by Schroff et al.
Learn embeddings from an anchor point and a similar input (positive) as
well as a not-similar input (negative).
Intui... | [
"r",
"Loss",
"for",
"Triplet",
"networks",
"as",
"described",
"in",
"the",
"paper",
":",
"FaceNet",
":",
"A",
"Unified",
"Embedding",
"for",
"Face",
"Recognition",
"and",
"Clustering",
"<https",
":",
"//",
"arxiv",
".",
"org",
"/",
"abs",
"/",
"1503",
".... | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/SimilarityLearning/mnist-embeddings.py#L99-L135 | train |
tensorpack/tensorpack | examples/SimilarityLearning/mnist-embeddings.py | soft_triplet_loss | def soft_triplet_loss(anchor, positive, negative, extra=True, scope="soft_triplet_loss"):
r"""Loss for triplet networks as described in the paper:
`Deep Metric Learning using Triplet Network
<https://arxiv.org/abs/1412.6622>`_ by Hoffer et al.
It is a softmax loss using :math:`(anchor-positive)^2` and
... | python | def soft_triplet_loss(anchor, positive, negative, extra=True, scope="soft_triplet_loss"):
r"""Loss for triplet networks as described in the paper:
`Deep Metric Learning using Triplet Network
<https://arxiv.org/abs/1412.6622>`_ by Hoffer et al.
It is a softmax loss using :math:`(anchor-positive)^2` and
... | [
"def",
"soft_triplet_loss",
"(",
"anchor",
",",
"positive",
",",
"negative",
",",
"extra",
"=",
"True",
",",
"scope",
"=",
"\"soft_triplet_loss\"",
")",
":",
"eps",
"=",
"1e-10",
"with",
"tf",
".",
"name_scope",
"(",
"scope",
")",
":",
"d_pos",
"=",
"tf"... | r"""Loss for triplet networks as described in the paper:
`Deep Metric Learning using Triplet Network
<https://arxiv.org/abs/1412.6622>`_ by Hoffer et al.
It is a softmax loss using :math:`(anchor-positive)^2` and
:math:`(anchor-negative)^2` as logits.
Args:
anchor (tf.Tensor): anchor featu... | [
"r",
"Loss",
"for",
"triplet",
"networks",
"as",
"described",
"in",
"the",
"paper",
":",
"Deep",
"Metric",
"Learning",
"using",
"Triplet",
"Network",
"<https",
":",
"//",
"arxiv",
".",
"org",
"/",
"abs",
"/",
"1412",
".",
"6622",
">",
"_",
"by",
"Hoffe... | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/SimilarityLearning/mnist-embeddings.py#L138-L171 | train |
tensorpack/tensorpack | examples/SimilarityLearning/mnist-embeddings.py | center_loss | def center_loss(embedding, label, num_classes, alpha=0.1, scope="center_loss"):
r"""Center-Loss as described in the paper
`A Discriminative Feature Learning Approach for Deep Face Recognition`
<http://ydwen.github.io/papers/WenECCV16.pdf> by Wen et al.
Args:
embedding (tf.Tensor): features prod... | python | def center_loss(embedding, label, num_classes, alpha=0.1, scope="center_loss"):
r"""Center-Loss as described in the paper
`A Discriminative Feature Learning Approach for Deep Face Recognition`
<http://ydwen.github.io/papers/WenECCV16.pdf> by Wen et al.
Args:
embedding (tf.Tensor): features prod... | [
"def",
"center_loss",
"(",
"embedding",
",",
"label",
",",
"num_classes",
",",
"alpha",
"=",
"0.1",
",",
"scope",
"=",
"\"center_loss\"",
")",
":",
"nrof_features",
"=",
"embedding",
".",
"get_shape",
"(",
")",
"[",
"1",
"]",
"centers",
"=",
"tf",
".",
... | r"""Center-Loss as described in the paper
`A Discriminative Feature Learning Approach for Deep Face Recognition`
<http://ydwen.github.io/papers/WenECCV16.pdf> by Wen et al.
Args:
embedding (tf.Tensor): features produced by the network
label (tf.Tensor): ground-truth label for each feature
... | [
"r",
"Center",
"-",
"Loss",
"as",
"described",
"in",
"the",
"paper",
"A",
"Discriminative",
"Feature",
"Learning",
"Approach",
"for",
"Deep",
"Face",
"Recognition",
"<http",
":",
"//",
"ydwen",
".",
"github",
".",
"io",
"/",
"papers",
"/",
"WenECCV16",
"."... | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/SimilarityLearning/mnist-embeddings.py#L174-L196 | train |
tensorpack/tensorpack | examples/SimilarityLearning/mnist-embeddings.py | EmbeddingModel.embed | def embed(self, x, nfeatures=2):
"""Embed all given tensors into an nfeatures-dim space. """
list_split = 0
if isinstance(x, list):
list_split = len(x)
x = tf.concat(x, 0)
# pre-process MNIST dataflow data
x = tf.expand_dims(x, 3)
x = x * 2 - 1
... | python | def embed(self, x, nfeatures=2):
"""Embed all given tensors into an nfeatures-dim space. """
list_split = 0
if isinstance(x, list):
list_split = len(x)
x = tf.concat(x, 0)
# pre-process MNIST dataflow data
x = tf.expand_dims(x, 3)
x = x * 2 - 1
... | [
"def",
"embed",
"(",
"self",
",",
"x",
",",
"nfeatures",
"=",
"2",
")",
":",
"list_split",
"=",
"0",
"if",
"isinstance",
"(",
"x",
",",
"list",
")",
":",
"list_split",
"=",
"len",
"(",
"x",
")",
"x",
"=",
"tf",
".",
"concat",
"(",
"x",
",",
"... | Embed all given tensors into an nfeatures-dim space. | [
"Embed",
"all",
"given",
"tensors",
"into",
"an",
"nfeatures",
"-",
"dim",
"space",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/SimilarityLearning/mnist-embeddings.py#L200-L224 | train |
tensorpack/tensorpack | examples/FasterRCNN/utils/generate_anchors.py | generate_anchors | def generate_anchors(base_size=16, ratios=[0.5, 1, 2],
scales=2**np.arange(3, 6)):
"""
Generate anchor (reference) windows by enumerating aspect ratios X
scales wrt a reference (0, 0, 15, 15) window.
"""
base_anchor = np.array([1, 1, base_size, base_size], dtype='float32') - 1
... | python | def generate_anchors(base_size=16, ratios=[0.5, 1, 2],
scales=2**np.arange(3, 6)):
"""
Generate anchor (reference) windows by enumerating aspect ratios X
scales wrt a reference (0, 0, 15, 15) window.
"""
base_anchor = np.array([1, 1, base_size, base_size], dtype='float32') - 1
... | [
"def",
"generate_anchors",
"(",
"base_size",
"=",
"16",
",",
"ratios",
"=",
"[",
"0.5",
",",
"1",
",",
"2",
"]",
",",
"scales",
"=",
"2",
"**",
"np",
".",
"arange",
"(",
"3",
",",
"6",
")",
")",
":",
"base_anchor",
"=",
"np",
".",
"array",
"(",... | Generate anchor (reference) windows by enumerating aspect ratios X
scales wrt a reference (0, 0, 15, 15) window. | [
"Generate",
"anchor",
"(",
"reference",
")",
"windows",
"by",
"enumerating",
"aspect",
"ratios",
"X",
"scales",
"wrt",
"a",
"reference",
"(",
"0",
"0",
"15",
"15",
")",
"window",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/utils/generate_anchors.py#L41-L52 | train |
tensorpack/tensorpack | examples/basics/mnist-tflayers.py | Model.build_graph | def build_graph(self, image, label):
"""This function should build the model which takes the input variables
and return cost at the end"""
# In tensorflow, inputs to convolution function are assumed to be
# NHWC. Add a single channel here.
image = tf.expand_dims(image, 3)
... | python | def build_graph(self, image, label):
"""This function should build the model which takes the input variables
and return cost at the end"""
# In tensorflow, inputs to convolution function are assumed to be
# NHWC. Add a single channel here.
image = tf.expand_dims(image, 3)
... | [
"def",
"build_graph",
"(",
"self",
",",
"image",
",",
"label",
")",
":",
"# In tensorflow, inputs to convolution function are assumed to be",
"# NHWC. Add a single channel here.",
"image",
"=",
"tf",
".",
"expand_dims",
"(",
"image",
",",
"3",
")",
"image",
"=",
"imag... | This function should build the model which takes the input variables
and return cost at the end | [
"This",
"function",
"should",
"build",
"the",
"model",
"which",
"takes",
"the",
"input",
"variables",
"and",
"return",
"cost",
"at",
"the",
"end"
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/basics/mnist-tflayers.py#L32-L83 | train |
tensorpack/tensorpack | examples/FasterRCNN/data.py | print_class_histogram | def print_class_histogram(roidbs):
"""
Args:
roidbs (list[dict]): the same format as the output of `load_training_roidbs`.
"""
dataset = DetectionDataset()
hist_bins = np.arange(dataset.num_classes + 1)
# Histogram of ground-truth objects
gt_hist = np.zeros((dataset.num_classes,), d... | python | def print_class_histogram(roidbs):
"""
Args:
roidbs (list[dict]): the same format as the output of `load_training_roidbs`.
"""
dataset = DetectionDataset()
hist_bins = np.arange(dataset.num_classes + 1)
# Histogram of ground-truth objects
gt_hist = np.zeros((dataset.num_classes,), d... | [
"def",
"print_class_histogram",
"(",
"roidbs",
")",
":",
"dataset",
"=",
"DetectionDataset",
"(",
")",
"hist_bins",
"=",
"np",
".",
"arange",
"(",
"dataset",
".",
"num_classes",
"+",
"1",
")",
"# Histogram of ground-truth objects",
"gt_hist",
"=",
"np",
".",
"... | Args:
roidbs (list[dict]): the same format as the output of `load_training_roidbs`. | [
"Args",
":",
"roidbs",
"(",
"list",
"[",
"dict",
"]",
")",
":",
"the",
"same",
"format",
"as",
"the",
"output",
"of",
"load_training_roidbs",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/data.py#L30-L50 | train |
tensorpack/tensorpack | examples/FasterRCNN/data.py | get_all_anchors | def get_all_anchors(stride=None, sizes=None):
"""
Get all anchors in the largest possible image, shifted, floatbox
Args:
stride (int): the stride of anchors.
sizes (tuple[int]): the sizes (sqrt area) of anchors
Returns:
anchors: SxSxNUM_ANCHORx4, where S == ceil(MAX_SIZE/STRIDE)... | python | def get_all_anchors(stride=None, sizes=None):
"""
Get all anchors in the largest possible image, shifted, floatbox
Args:
stride (int): the stride of anchors.
sizes (tuple[int]): the sizes (sqrt area) of anchors
Returns:
anchors: SxSxNUM_ANCHORx4, where S == ceil(MAX_SIZE/STRIDE)... | [
"def",
"get_all_anchors",
"(",
"stride",
"=",
"None",
",",
"sizes",
"=",
"None",
")",
":",
"if",
"stride",
"is",
"None",
":",
"stride",
"=",
"cfg",
".",
"RPN",
".",
"ANCHOR_STRIDE",
"if",
"sizes",
"is",
"None",
":",
"sizes",
"=",
"cfg",
".",
"RPN",
... | Get all anchors in the largest possible image, shifted, floatbox
Args:
stride (int): the stride of anchors.
sizes (tuple[int]): the sizes (sqrt area) of anchors
Returns:
anchors: SxSxNUM_ANCHORx4, where S == ceil(MAX_SIZE/STRIDE), floatbox
The layout in the NUM_ANCHOR dim is NUM... | [
"Get",
"all",
"anchors",
"in",
"the",
"largest",
"possible",
"image",
"shifted",
"floatbox",
"Args",
":",
"stride",
"(",
"int",
")",
":",
"the",
"stride",
"of",
"anchors",
".",
"sizes",
"(",
"tuple",
"[",
"int",
"]",
")",
":",
"the",
"sizes",
"(",
"s... | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/data.py#L54-L100 | train |
tensorpack/tensorpack | examples/FasterRCNN/data.py | get_all_anchors_fpn | def get_all_anchors_fpn(strides=None, sizes=None):
"""
Returns:
[anchors]: each anchors is a SxSx NUM_ANCHOR_RATIOS x4 array.
"""
if strides is None:
strides = cfg.FPN.ANCHOR_STRIDES
if sizes is None:
sizes = cfg.RPN.ANCHOR_SIZES
assert len(strides) == len(sizes)
foas... | python | def get_all_anchors_fpn(strides=None, sizes=None):
"""
Returns:
[anchors]: each anchors is a SxSx NUM_ANCHOR_RATIOS x4 array.
"""
if strides is None:
strides = cfg.FPN.ANCHOR_STRIDES
if sizes is None:
sizes = cfg.RPN.ANCHOR_SIZES
assert len(strides) == len(sizes)
foas... | [
"def",
"get_all_anchors_fpn",
"(",
"strides",
"=",
"None",
",",
"sizes",
"=",
"None",
")",
":",
"if",
"strides",
"is",
"None",
":",
"strides",
"=",
"cfg",
".",
"FPN",
".",
"ANCHOR_STRIDES",
"if",
"sizes",
"is",
"None",
":",
"sizes",
"=",
"cfg",
".",
... | Returns:
[anchors]: each anchors is a SxSx NUM_ANCHOR_RATIOS x4 array. | [
"Returns",
":",
"[",
"anchors",
"]",
":",
"each",
"anchors",
"is",
"a",
"SxSx",
"NUM_ANCHOR_RATIOS",
"x4",
"array",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/data.py#L104-L118 | train |
tensorpack/tensorpack | examples/FasterRCNN/data.py | get_anchor_labels | def get_anchor_labels(anchors, gt_boxes, crowd_boxes):
"""
Label each anchor as fg/bg/ignore.
Args:
anchors: Ax4 float
gt_boxes: Bx4 float, non-crowd
crowd_boxes: Cx4 float
Returns:
anchor_labels: (A,) int. Each element is {-1, 0, 1}
anchor_boxes: Ax4. Contains t... | python | def get_anchor_labels(anchors, gt_boxes, crowd_boxes):
"""
Label each anchor as fg/bg/ignore.
Args:
anchors: Ax4 float
gt_boxes: Bx4 float, non-crowd
crowd_boxes: Cx4 float
Returns:
anchor_labels: (A,) int. Each element is {-1, 0, 1}
anchor_boxes: Ax4. Contains t... | [
"def",
"get_anchor_labels",
"(",
"anchors",
",",
"gt_boxes",
",",
"crowd_boxes",
")",
":",
"# This function will modify labels and return the filtered inds",
"def",
"filter_box_label",
"(",
"labels",
",",
"value",
",",
"max_num",
")",
":",
"curr_inds",
"=",
"np",
".",... | Label each anchor as fg/bg/ignore.
Args:
anchors: Ax4 float
gt_boxes: Bx4 float, non-crowd
crowd_boxes: Cx4 float
Returns:
anchor_labels: (A,) int. Each element is {-1, 0, 1}
anchor_boxes: Ax4. Contains the target gt_box for each anchor when the anchor is fg. | [
"Label",
"each",
"anchor",
"as",
"fg",
"/",
"bg",
"/",
"ignore",
".",
"Args",
":",
"anchors",
":",
"Ax4",
"float",
"gt_boxes",
":",
"Bx4",
"float",
"non",
"-",
"crowd",
"crowd_boxes",
":",
"Cx4",
"float"
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/data.py#L121-L189 | train |
tensorpack/tensorpack | examples/FasterRCNN/data.py | get_rpn_anchor_input | def get_rpn_anchor_input(im, boxes, is_crowd):
"""
Args:
im: an image
boxes: nx4, floatbox, gt. shoudn't be changed
is_crowd: n,
Returns:
The anchor labels and target boxes for each pixel in the featuremap.
fm_labels: fHxfWxNA
fm_boxes: fHxfWxNAx4
NA ... | python | def get_rpn_anchor_input(im, boxes, is_crowd):
"""
Args:
im: an image
boxes: nx4, floatbox, gt. shoudn't be changed
is_crowd: n,
Returns:
The anchor labels and target boxes for each pixel in the featuremap.
fm_labels: fHxfWxNA
fm_boxes: fHxfWxNAx4
NA ... | [
"def",
"get_rpn_anchor_input",
"(",
"im",
",",
"boxes",
",",
"is_crowd",
")",
":",
"boxes",
"=",
"boxes",
".",
"copy",
"(",
")",
"all_anchors",
"=",
"np",
".",
"copy",
"(",
"get_all_anchors",
"(",
")",
")",
"# fHxfWxAx4 -> (-1, 4)",
"featuremap_anchors_flatten... | Args:
im: an image
boxes: nx4, floatbox, gt. shoudn't be changed
is_crowd: n,
Returns:
The anchor labels and target boxes for each pixel in the featuremap.
fm_labels: fHxfWxNA
fm_boxes: fHxfWxNAx4
NA will be NUM_ANCHOR_SIZES x NUM_ANCHOR_RATIOS | [
"Args",
":",
"im",
":",
"an",
"image",
"boxes",
":",
"nx4",
"floatbox",
"gt",
".",
"shoudn",
"t",
"be",
"changed",
"is_crowd",
":",
"n"
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/data.py#L192-L223 | train |
tensorpack/tensorpack | examples/FasterRCNN/data.py | get_multilevel_rpn_anchor_input | def get_multilevel_rpn_anchor_input(im, boxes, is_crowd):
"""
Args:
im: an image
boxes: nx4, floatbox, gt. shoudn't be changed
is_crowd: n,
Returns:
[(fm_labels, fm_boxes)]: Returns a tuple for each FPN level.
Each tuple contains the anchor labels and target boxes fo... | python | def get_multilevel_rpn_anchor_input(im, boxes, is_crowd):
"""
Args:
im: an image
boxes: nx4, floatbox, gt. shoudn't be changed
is_crowd: n,
Returns:
[(fm_labels, fm_boxes)]: Returns a tuple for each FPN level.
Each tuple contains the anchor labels and target boxes fo... | [
"def",
"get_multilevel_rpn_anchor_input",
"(",
"im",
",",
"boxes",
",",
"is_crowd",
")",
":",
"boxes",
"=",
"boxes",
".",
"copy",
"(",
")",
"anchors_per_level",
"=",
"get_all_anchors_fpn",
"(",
")",
"flatten_anchors_per_level",
"=",
"[",
"k",
".",
"reshape",
"... | Args:
im: an image
boxes: nx4, floatbox, gt. shoudn't be changed
is_crowd: n,
Returns:
[(fm_labels, fm_boxes)]: Returns a tuple for each FPN level.
Each tuple contains the anchor labels and target boxes for each pixel in the featuremap.
fm_labels: fHxfWx NUM_ANCHOR_... | [
"Args",
":",
"im",
":",
"an",
"image",
"boxes",
":",
"nx4",
"floatbox",
"gt",
".",
"shoudn",
"t",
"be",
"changed",
"is_crowd",
":",
"n"
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/data.py#L226-L268 | train |
tensorpack/tensorpack | examples/FasterRCNN/data.py | get_train_dataflow | def get_train_dataflow():
"""
Return a training dataflow. Each datapoint consists of the following:
An image: (h, w, 3),
1 or more pairs of (anchor_labels, anchor_boxes):
anchor_labels: (h', w', NA)
anchor_boxes: (h', w', NA, 4)
gt_boxes: (N, 4)
gt_labels: (N,)
If MODE_MASK, gt_m... | python | def get_train_dataflow():
"""
Return a training dataflow. Each datapoint consists of the following:
An image: (h, w, 3),
1 or more pairs of (anchor_labels, anchor_boxes):
anchor_labels: (h', w', NA)
anchor_boxes: (h', w', NA, 4)
gt_boxes: (N, 4)
gt_labels: (N,)
If MODE_MASK, gt_m... | [
"def",
"get_train_dataflow",
"(",
")",
":",
"roidbs",
"=",
"DetectionDataset",
"(",
")",
".",
"load_training_roidbs",
"(",
"cfg",
".",
"DATA",
".",
"TRAIN",
")",
"print_class_histogram",
"(",
"roidbs",
")",
"# Valid training images should have at least one fg box.",
"... | Return a training dataflow. Each datapoint consists of the following:
An image: (h, w, 3),
1 or more pairs of (anchor_labels, anchor_boxes):
anchor_labels: (h', w', NA)
anchor_boxes: (h', w', NA, 4)
gt_boxes: (N, 4)
gt_labels: (N,)
If MODE_MASK, gt_masks: (N, h, w) | [
"Return",
"a",
"training",
"dataflow",
".",
"Each",
"datapoint",
"consists",
"of",
"the",
"following",
":"
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/data.py#L271-L380 | train |
tensorpack/tensorpack | examples/FasterRCNN/data.py | get_eval_dataflow | def get_eval_dataflow(name, shard=0, num_shards=1):
"""
Args:
name (str): name of the dataset to evaluate
shard, num_shards: to get subset of evaluation data
"""
roidbs = DetectionDataset().load_inference_roidbs(name)
num_imgs = len(roidbs)
img_per_shard = num_imgs // num_shards... | python | def get_eval_dataflow(name, shard=0, num_shards=1):
"""
Args:
name (str): name of the dataset to evaluate
shard, num_shards: to get subset of evaluation data
"""
roidbs = DetectionDataset().load_inference_roidbs(name)
num_imgs = len(roidbs)
img_per_shard = num_imgs // num_shards... | [
"def",
"get_eval_dataflow",
"(",
"name",
",",
"shard",
"=",
"0",
",",
"num_shards",
"=",
"1",
")",
":",
"roidbs",
"=",
"DetectionDataset",
"(",
")",
".",
"load_inference_roidbs",
"(",
"name",
")",
"num_imgs",
"=",
"len",
"(",
"roidbs",
")",
"img_per_shard"... | Args:
name (str): name of the dataset to evaluate
shard, num_shards: to get subset of evaluation data | [
"Args",
":",
"name",
"(",
"str",
")",
":",
"name",
"of",
"the",
"dataset",
"to",
"evaluate",
"shard",
"num_shards",
":",
"to",
"get",
"subset",
"of",
"evaluation",
"data"
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/data.py#L383-L404 | train |
tensorpack/tensorpack | tensorpack/graph_builder/utils.py | override_to_local_variable | def override_to_local_variable(enable=True):
"""
Returns:
a context where all variables will be created as local.
"""
if enable:
def custom_getter(getter, name, *args, **kwargs):
_replace_global_by_local(kwargs)
return getter(name, *args, **kwargs)
with ... | python | def override_to_local_variable(enable=True):
"""
Returns:
a context where all variables will be created as local.
"""
if enable:
def custom_getter(getter, name, *args, **kwargs):
_replace_global_by_local(kwargs)
return getter(name, *args, **kwargs)
with ... | [
"def",
"override_to_local_variable",
"(",
"enable",
"=",
"True",
")",
":",
"if",
"enable",
":",
"def",
"custom_getter",
"(",
"getter",
",",
"name",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"_replace_global_by_local",
"(",
"kwargs",
")",
"return... | Returns:
a context where all variables will be created as local. | [
"Returns",
":",
"a",
"context",
"where",
"all",
"variables",
"will",
"be",
"created",
"as",
"local",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/graph_builder/utils.py#L43-L57 | train |
tensorpack/tensorpack | tensorpack/graph_builder/utils.py | split_grad_list | def split_grad_list(grad_list):
"""
Args:
grad_list: K x N x 2
Returns:
K x N: gradients
K x N: variables
"""
g = []
v = []
for tower in grad_list:
g.append([x[0] for x in tower])
v.append([x[1] for x in tower])
return g, v | python | def split_grad_list(grad_list):
"""
Args:
grad_list: K x N x 2
Returns:
K x N: gradients
K x N: variables
"""
g = []
v = []
for tower in grad_list:
g.append([x[0] for x in tower])
v.append([x[1] for x in tower])
return g, v | [
"def",
"split_grad_list",
"(",
"grad_list",
")",
":",
"g",
"=",
"[",
"]",
"v",
"=",
"[",
"]",
"for",
"tower",
"in",
"grad_list",
":",
"g",
".",
"append",
"(",
"[",
"x",
"[",
"0",
"]",
"for",
"x",
"in",
"tower",
"]",
")",
"v",
".",
"append",
"... | Args:
grad_list: K x N x 2
Returns:
K x N: gradients
K x N: variables | [
"Args",
":",
"grad_list",
":",
"K",
"x",
"N",
"x",
"2"
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/graph_builder/utils.py#L109-L123 | train |
tensorpack/tensorpack | tensorpack/graph_builder/utils.py | merge_grad_list | def merge_grad_list(all_grads, all_vars):
"""
Args:
all_grads (K x N): gradients
all_vars(K x N): variables
Return:
K x N x 2: list of list of (grad, var) pairs
"""
return [list(zip(gs, vs)) for gs, vs in zip(all_grads, all_vars)] | python | def merge_grad_list(all_grads, all_vars):
"""
Args:
all_grads (K x N): gradients
all_vars(K x N): variables
Return:
K x N x 2: list of list of (grad, var) pairs
"""
return [list(zip(gs, vs)) for gs, vs in zip(all_grads, all_vars)] | [
"def",
"merge_grad_list",
"(",
"all_grads",
",",
"all_vars",
")",
":",
"return",
"[",
"list",
"(",
"zip",
"(",
"gs",
",",
"vs",
")",
")",
"for",
"gs",
",",
"vs",
"in",
"zip",
"(",
"all_grads",
",",
"all_vars",
")",
"]"
] | Args:
all_grads (K x N): gradients
all_vars(K x N): variables
Return:
K x N x 2: list of list of (grad, var) pairs | [
"Args",
":",
"all_grads",
"(",
"K",
"x",
"N",
")",
":",
"gradients",
"all_vars",
"(",
"K",
"x",
"N",
")",
":",
"variables"
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/graph_builder/utils.py#L126-L135 | train |
tensorpack/tensorpack | tensorpack/graph_builder/utils.py | allreduce_grads | def allreduce_grads(all_grads, average):
"""
All-reduce average the gradients among K devices. Results are broadcasted to all devices.
Args:
all_grads (K x N): List of list of gradients. N is the number of variables.
average (bool): average gradients or not.
Returns:
K x N: sam... | python | def allreduce_grads(all_grads, average):
"""
All-reduce average the gradients among K devices. Results are broadcasted to all devices.
Args:
all_grads (K x N): List of list of gradients. N is the number of variables.
average (bool): average gradients or not.
Returns:
K x N: sam... | [
"def",
"allreduce_grads",
"(",
"all_grads",
",",
"average",
")",
":",
"if",
"get_tf_version_tuple",
"(",
")",
"<=",
"(",
"1",
",",
"12",
")",
":",
"from",
"tensorflow",
".",
"contrib",
"import",
"nccl",
"else",
":",
"from",
"tensorflow",
".",
"python",
"... | All-reduce average the gradients among K devices. Results are broadcasted to all devices.
Args:
all_grads (K x N): List of list of gradients. N is the number of variables.
average (bool): average gradients or not.
Returns:
K x N: same as input, but each grad is replaced by the average ... | [
"All",
"-",
"reduce",
"average",
"the",
"gradients",
"among",
"K",
"devices",
".",
"Results",
"are",
"broadcasted",
"to",
"all",
"devices",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/graph_builder/utils.py#L139-L173 | train |
tensorpack/tensorpack | tensorpack/graph_builder/utils.py | allreduce_grads_hierarchical | def allreduce_grads_hierarchical(all_grads, devices, average=False):
"""
Hierarchical allreduce for DGX-1 system.
Args:
all_grads (K x N): List of list of gradients. N is the number of variables.
devices ([str]): K str for the K devices.
average (bool): average gradients or not.
... | python | def allreduce_grads_hierarchical(all_grads, devices, average=False):
"""
Hierarchical allreduce for DGX-1 system.
Args:
all_grads (K x N): List of list of gradients. N is the number of variables.
devices ([str]): K str for the K devices.
average (bool): average gradients or not.
... | [
"def",
"allreduce_grads_hierarchical",
"(",
"all_grads",
",",
"devices",
",",
"average",
"=",
"False",
")",
":",
"num_gpu",
"=",
"len",
"(",
"devices",
")",
"assert",
"num_gpu",
"==",
"8",
",",
"num_gpu",
"assert",
"len",
"(",
"all_grads",
")",
"==",
"num_... | Hierarchical allreduce for DGX-1 system.
Args:
all_grads (K x N): List of list of gradients. N is the number of variables.
devices ([str]): K str for the K devices.
average (bool): average gradients or not.
Returns:
(K x N): same as input, but each grad is replaced by the avera... | [
"Hierarchical",
"allreduce",
"for",
"DGX",
"-",
"1",
"system",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/graph_builder/utils.py#L177-L235 | train |
tensorpack/tensorpack | tensorpack/graph_builder/utils.py | aggregate_grads | def aggregate_grads(all_grads,
colocation=False,
devices=None,
average=True):
"""
Average the gradients.
Args:
all_grads (K x N x 2): A list of K lists. Each of the list is a list of N (grad, var) tuples.
The variables have to ... | python | def aggregate_grads(all_grads,
colocation=False,
devices=None,
average=True):
"""
Average the gradients.
Args:
all_grads (K x N x 2): A list of K lists. Each of the list is a list of N (grad, var) tuples.
The variables have to ... | [
"def",
"aggregate_grads",
"(",
"all_grads",
",",
"colocation",
"=",
"False",
",",
"devices",
"=",
"None",
",",
"average",
"=",
"True",
")",
":",
"assert",
"not",
"(",
"devices",
"is",
"not",
"None",
"and",
"colocation",
")",
"if",
"devices",
"is",
"not",... | Average the gradients.
Args:
all_grads (K x N x 2): A list of K lists. Each of the list is a list of N (grad, var) tuples.
The variables have to be the same across the K lists.
colocation (bool): colocate gradient averaging on the device of the variable.
devices (list[str]): ass... | [
"Average",
"the",
"gradients",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/graph_builder/utils.py#L239-L287 | train |
tensorpack/tensorpack | tensorpack/graph_builder/utils.py | GradientPacker.compute_strategy | def compute_strategy(self, grads):
"""
Returns:
bool - False if grads cannot be packed due to various reasons.
"""
for g in grads:
assert g.shape.is_fully_defined(), "Shape of {} is {}!".format(g.name, g.shape)
self._shapes = [g.shape for g in grads]
... | python | def compute_strategy(self, grads):
"""
Returns:
bool - False if grads cannot be packed due to various reasons.
"""
for g in grads:
assert g.shape.is_fully_defined(), "Shape of {} is {}!".format(g.name, g.shape)
self._shapes = [g.shape for g in grads]
... | [
"def",
"compute_strategy",
"(",
"self",
",",
"grads",
")",
":",
"for",
"g",
"in",
"grads",
":",
"assert",
"g",
".",
"shape",
".",
"is_fully_defined",
"(",
")",
",",
"\"Shape of {} is {}!\"",
".",
"format",
"(",
"g",
".",
"name",
",",
"g",
".",
"shape",... | Returns:
bool - False if grads cannot be packed due to various reasons. | [
"Returns",
":",
"bool",
"-",
"False",
"if",
"grads",
"cannot",
"be",
"packed",
"due",
"to",
"various",
"reasons",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/graph_builder/utils.py#L337-L364 | train |
tensorpack/tensorpack | tensorpack/graph_builder/utils.py | GradientPacker.pack | def pack(self, grads):
"""
Args:
grads (list): list of gradient tensors
Returns:
packed list of gradient tensors to be aggregated.
"""
for i, g in enumerate(grads):
assert g.shape == self._shapes[i]
with cached_name_scope("GradientPac... | python | def pack(self, grads):
"""
Args:
grads (list): list of gradient tensors
Returns:
packed list of gradient tensors to be aggregated.
"""
for i, g in enumerate(grads):
assert g.shape == self._shapes[i]
with cached_name_scope("GradientPac... | [
"def",
"pack",
"(",
"self",
",",
"grads",
")",
":",
"for",
"i",
",",
"g",
"in",
"enumerate",
"(",
"grads",
")",
":",
"assert",
"g",
".",
"shape",
"==",
"self",
".",
"_shapes",
"[",
"i",
"]",
"with",
"cached_name_scope",
"(",
"\"GradientPacker\"",
","... | Args:
grads (list): list of gradient tensors
Returns:
packed list of gradient tensors to be aggregated. | [
"Args",
":",
"grads",
"(",
"list",
")",
":",
"list",
"of",
"gradient",
"tensors"
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/graph_builder/utils.py#L366-L381 | train |
tensorpack/tensorpack | tensorpack/graph_builder/utils.py | GradientPacker.pack_all | def pack_all(self, all_grads, devices):
"""
Args:
all_grads: K x N, K lists of gradients to be packed
"""
ret = [] # #GPU x #split
for dev, grads in zip(devices, all_grads):
with tf.device(dev):
ret.append(self.pack(grads))
retur... | python | def pack_all(self, all_grads, devices):
"""
Args:
all_grads: K x N, K lists of gradients to be packed
"""
ret = [] # #GPU x #split
for dev, grads in zip(devices, all_grads):
with tf.device(dev):
ret.append(self.pack(grads))
retur... | [
"def",
"pack_all",
"(",
"self",
",",
"all_grads",
",",
"devices",
")",
":",
"ret",
"=",
"[",
"]",
"# #GPU x #split",
"for",
"dev",
",",
"grads",
"in",
"zip",
"(",
"devices",
",",
"all_grads",
")",
":",
"with",
"tf",
".",
"device",
"(",
"dev",
")",
... | Args:
all_grads: K x N, K lists of gradients to be packed | [
"Args",
":",
"all_grads",
":",
"K",
"x",
"N",
"K",
"lists",
"of",
"gradients",
"to",
"be",
"packed"
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/graph_builder/utils.py#L391-L400 | train |
tensorpack/tensorpack | tensorpack/graph_builder/utils.py | GradientPacker.unpack_all | def unpack_all(self, all_packed, devices):
"""
Args:
all_packed: K lists of packed gradients.
"""
all_grads = [] # #GPU x #Var
for dev, packed_grads_single_device in zip(devices, all_packed):
with tf.device(dev):
all_grads.append(self.unpa... | python | def unpack_all(self, all_packed, devices):
"""
Args:
all_packed: K lists of packed gradients.
"""
all_grads = [] # #GPU x #Var
for dev, packed_grads_single_device in zip(devices, all_packed):
with tf.device(dev):
all_grads.append(self.unpa... | [
"def",
"unpack_all",
"(",
"self",
",",
"all_packed",
",",
"devices",
")",
":",
"all_grads",
"=",
"[",
"]",
"# #GPU x #Var",
"for",
"dev",
",",
"packed_grads_single_device",
"in",
"zip",
"(",
"devices",
",",
"all_packed",
")",
":",
"with",
"tf",
".",
"devic... | Args:
all_packed: K lists of packed gradients. | [
"Args",
":",
"all_packed",
":",
"K",
"lists",
"of",
"packed",
"gradients",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/graph_builder/utils.py#L402-L411 | train |
tensorpack/tensorpack | examples/FasterRCNN/model_fpn.py | fpn_model | def fpn_model(features):
"""
Args:
features ([tf.Tensor]): ResNet features c2-c5
Returns:
[tf.Tensor]: FPN features p2-p6
"""
assert len(features) == 4, features
num_channel = cfg.FPN.NUM_CHANNEL
use_gn = cfg.FPN.NORM == 'GN'
def upsample2x(name, x):
return Fix... | python | def fpn_model(features):
"""
Args:
features ([tf.Tensor]): ResNet features c2-c5
Returns:
[tf.Tensor]: FPN features p2-p6
"""
assert len(features) == 4, features
num_channel = cfg.FPN.NUM_CHANNEL
use_gn = cfg.FPN.NORM == 'GN'
def upsample2x(name, x):
return Fix... | [
"def",
"fpn_model",
"(",
"features",
")",
":",
"assert",
"len",
"(",
"features",
")",
"==",
"4",
",",
"features",
"num_channel",
"=",
"cfg",
".",
"FPN",
".",
"NUM_CHANNEL",
"use_gn",
"=",
"cfg",
".",
"FPN",
".",
"NORM",
"==",
"'GN'",
"def",
"upsample2x... | Args:
features ([tf.Tensor]): ResNet features c2-c5
Returns:
[tf.Tensor]: FPN features p2-p6 | [
"Args",
":",
"features",
"(",
"[",
"tf",
".",
"Tensor",
"]",
")",
":",
"ResNet",
"features",
"c2",
"-",
"c5"
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/model_fpn.py#L21-L66 | train |
tensorpack/tensorpack | examples/FasterRCNN/model_fpn.py | fpn_map_rois_to_levels | def fpn_map_rois_to_levels(boxes):
"""
Assign boxes to level 2~5.
Args:
boxes (nx4):
Returns:
[tf.Tensor]: 4 tensors for level 2-5. Each tensor is a vector of indices of boxes in its level.
[tf.Tensor]: 4 tensors, the gathered boxes in each level.
Be careful that the retur... | python | def fpn_map_rois_to_levels(boxes):
"""
Assign boxes to level 2~5.
Args:
boxes (nx4):
Returns:
[tf.Tensor]: 4 tensors for level 2-5. Each tensor is a vector of indices of boxes in its level.
[tf.Tensor]: 4 tensors, the gathered boxes in each level.
Be careful that the retur... | [
"def",
"fpn_map_rois_to_levels",
"(",
"boxes",
")",
":",
"sqrtarea",
"=",
"tf",
".",
"sqrt",
"(",
"tf_area",
"(",
"boxes",
")",
")",
"level",
"=",
"tf",
".",
"cast",
"(",
"tf",
".",
"floor",
"(",
"4",
"+",
"tf",
".",
"log",
"(",
"sqrtarea",
"*",
... | Assign boxes to level 2~5.
Args:
boxes (nx4):
Returns:
[tf.Tensor]: 4 tensors for level 2-5. Each tensor is a vector of indices of boxes in its level.
[tf.Tensor]: 4 tensors, the gathered boxes in each level.
Be careful that the returned tensor could be empty. | [
"Assign",
"boxes",
"to",
"level",
"2~5",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/model_fpn.py#L70-L100 | train |
tensorpack/tensorpack | examples/FasterRCNN/model_fpn.py | multilevel_roi_align | def multilevel_roi_align(features, rcnn_boxes, resolution):
"""
Args:
features ([tf.Tensor]): 4 FPN feature level 2-5
rcnn_boxes (tf.Tensor): nx4 boxes
resolution (int): output spatial resolution
Returns:
NxC x res x res
"""
assert len(features) == 4, features
# R... | python | def multilevel_roi_align(features, rcnn_boxes, resolution):
"""
Args:
features ([tf.Tensor]): 4 FPN feature level 2-5
rcnn_boxes (tf.Tensor): nx4 boxes
resolution (int): output spatial resolution
Returns:
NxC x res x res
"""
assert len(features) == 4, features
# R... | [
"def",
"multilevel_roi_align",
"(",
"features",
",",
"rcnn_boxes",
",",
"resolution",
")",
":",
"assert",
"len",
"(",
"features",
")",
"==",
"4",
",",
"features",
"# Reassign rcnn_boxes to levels",
"level_ids",
",",
"level_boxes",
"=",
"fpn_map_rois_to_levels",
"(",... | Args:
features ([tf.Tensor]): 4 FPN feature level 2-5
rcnn_boxes (tf.Tensor): nx4 boxes
resolution (int): output spatial resolution
Returns:
NxC x res x res | [
"Args",
":",
"features",
"(",
"[",
"tf",
".",
"Tensor",
"]",
")",
":",
"4",
"FPN",
"feature",
"level",
"2",
"-",
"5",
"rcnn_boxes",
"(",
"tf",
".",
"Tensor",
")",
":",
"nx4",
"boxes",
"resolution",
"(",
"int",
")",
":",
"output",
"spatial",
"resolu... | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/model_fpn.py#L104-L130 | train |
tensorpack/tensorpack | examples/FasterRCNN/model_fpn.py | multilevel_rpn_losses | def multilevel_rpn_losses(
multilevel_anchors, multilevel_label_logits, multilevel_box_logits):
"""
Args:
multilevel_anchors: #lvl RPNAnchors
multilevel_label_logits: #lvl tensors of shape HxWxA
multilevel_box_logits: #lvl tensors of shape HxWxAx4
Returns:
label_loss... | python | def multilevel_rpn_losses(
multilevel_anchors, multilevel_label_logits, multilevel_box_logits):
"""
Args:
multilevel_anchors: #lvl RPNAnchors
multilevel_label_logits: #lvl tensors of shape HxWxA
multilevel_box_logits: #lvl tensors of shape HxWxAx4
Returns:
label_loss... | [
"def",
"multilevel_rpn_losses",
"(",
"multilevel_anchors",
",",
"multilevel_label_logits",
",",
"multilevel_box_logits",
")",
":",
"num_lvl",
"=",
"len",
"(",
"cfg",
".",
"FPN",
".",
"ANCHOR_STRIDES",
")",
"assert",
"len",
"(",
"multilevel_anchors",
")",
"==",
"nu... | Args:
multilevel_anchors: #lvl RPNAnchors
multilevel_label_logits: #lvl tensors of shape HxWxA
multilevel_box_logits: #lvl tensors of shape HxWxAx4
Returns:
label_loss, box_loss | [
"Args",
":",
"multilevel_anchors",
":",
"#lvl",
"RPNAnchors",
"multilevel_label_logits",
":",
"#lvl",
"tensors",
"of",
"shape",
"HxWxA",
"multilevel_box_logits",
":",
"#lvl",
"tensors",
"of",
"shape",
"HxWxAx4"
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/model_fpn.py#L133-L162 | train |
tensorpack/tensorpack | examples/FasterRCNN/model_fpn.py | generate_fpn_proposals | def generate_fpn_proposals(
multilevel_pred_boxes, multilevel_label_logits, image_shape2d):
"""
Args:
multilevel_pred_boxes: #lvl HxWxAx4 boxes
multilevel_label_logits: #lvl tensors of shape HxWxA
Returns:
boxes: kx4 float
scores: k logits
"""
num_lvl = len(c... | python | def generate_fpn_proposals(
multilevel_pred_boxes, multilevel_label_logits, image_shape2d):
"""
Args:
multilevel_pred_boxes: #lvl HxWxAx4 boxes
multilevel_label_logits: #lvl tensors of shape HxWxA
Returns:
boxes: kx4 float
scores: k logits
"""
num_lvl = len(c... | [
"def",
"generate_fpn_proposals",
"(",
"multilevel_pred_boxes",
",",
"multilevel_label_logits",
",",
"image_shape2d",
")",
":",
"num_lvl",
"=",
"len",
"(",
"cfg",
".",
"FPN",
".",
"ANCHOR_STRIDES",
")",
"assert",
"len",
"(",
"multilevel_pred_boxes",
")",
"==",
"num... | Args:
multilevel_pred_boxes: #lvl HxWxAx4 boxes
multilevel_label_logits: #lvl tensors of shape HxWxA
Returns:
boxes: kx4 float
scores: k logits | [
"Args",
":",
"multilevel_pred_boxes",
":",
"#lvl",
"HxWxAx4",
"boxes",
"multilevel_label_logits",
":",
"#lvl",
"tensors",
"of",
"shape",
"HxWxA"
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/model_fpn.py#L166-L219 | train |
tensorpack/tensorpack | tensorpack/models/layer_norm.py | LayerNorm | def LayerNorm(
x, epsilon=1e-5,
use_bias=True, use_scale=True,
gamma_init=None, data_format='channels_last'):
"""
Layer Normalization layer, as described in the paper:
`Layer Normalization <https://arxiv.org/abs/1607.06450>`_.
Args:
x (tf.Tensor): a 4D or 2D tensor. When... | python | def LayerNorm(
x, epsilon=1e-5,
use_bias=True, use_scale=True,
gamma_init=None, data_format='channels_last'):
"""
Layer Normalization layer, as described in the paper:
`Layer Normalization <https://arxiv.org/abs/1607.06450>`_.
Args:
x (tf.Tensor): a 4D or 2D tensor. When... | [
"def",
"LayerNorm",
"(",
"x",
",",
"epsilon",
"=",
"1e-5",
",",
"use_bias",
"=",
"True",
",",
"use_scale",
"=",
"True",
",",
"gamma_init",
"=",
"None",
",",
"data_format",
"=",
"'channels_last'",
")",
":",
"data_format",
"=",
"get_data_format",
"(",
"data_... | Layer Normalization layer, as described in the paper:
`Layer Normalization <https://arxiv.org/abs/1607.06450>`_.
Args:
x (tf.Tensor): a 4D or 2D tensor. When 4D, the layout should match data_format.
epsilon (float): epsilon to avoid divide-by-zero.
use_scale, use_bias (bool): whether to... | [
"Layer",
"Normalization",
"layer",
"as",
"described",
"in",
"the",
"paper",
":",
"Layer",
"Normalization",
"<https",
":",
"//",
"arxiv",
".",
"org",
"/",
"abs",
"/",
"1607",
".",
"06450",
">",
"_",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/models/layer_norm.py#L14-L63 | train |
tensorpack/tensorpack | tensorpack/models/layer_norm.py | InstanceNorm | def InstanceNorm(x, epsilon=1e-5, use_affine=True, gamma_init=None, data_format='channels_last'):
"""
Instance Normalization, as in the paper:
`Instance Normalization: The Missing Ingredient for Fast Stylization
<https://arxiv.org/abs/1607.08022>`_.
Args:
x (tf.Tensor): a 4D tensor.
... | python | def InstanceNorm(x, epsilon=1e-5, use_affine=True, gamma_init=None, data_format='channels_last'):
"""
Instance Normalization, as in the paper:
`Instance Normalization: The Missing Ingredient for Fast Stylization
<https://arxiv.org/abs/1607.08022>`_.
Args:
x (tf.Tensor): a 4D tensor.
... | [
"def",
"InstanceNorm",
"(",
"x",
",",
"epsilon",
"=",
"1e-5",
",",
"use_affine",
"=",
"True",
",",
"gamma_init",
"=",
"None",
",",
"data_format",
"=",
"'channels_last'",
")",
":",
"data_format",
"=",
"get_data_format",
"(",
"data_format",
",",
"keras_mode",
... | Instance Normalization, as in the paper:
`Instance Normalization: The Missing Ingredient for Fast Stylization
<https://arxiv.org/abs/1607.08022>`_.
Args:
x (tf.Tensor): a 4D tensor.
epsilon (float): avoid divide-by-zero
use_affine (bool): whether to apply learnable affine transforma... | [
"Instance",
"Normalization",
"as",
"in",
"the",
"paper",
":",
"Instance",
"Normalization",
":",
"The",
"Missing",
"Ingredient",
"for",
"Fast",
"Stylization",
"<https",
":",
"//",
"arxiv",
".",
"org",
"/",
"abs",
"/",
"1607",
".",
"08022",
">",
"_",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/models/layer_norm.py#L67-L109 | train |
tensorpack/tensorpack | examples/FasterRCNN/model_frcnn.py | proposal_metrics | def proposal_metrics(iou):
"""
Add summaries for RPN proposals.
Args:
iou: nxm, #proposal x #gt
"""
# find best roi for each gt, for summary only
best_iou = tf.reduce_max(iou, axis=0)
mean_best_iou = tf.reduce_mean(best_iou, name='best_iou_per_gt')
summaries = [mean_best_iou]
... | python | def proposal_metrics(iou):
"""
Add summaries for RPN proposals.
Args:
iou: nxm, #proposal x #gt
"""
# find best roi for each gt, for summary only
best_iou = tf.reduce_max(iou, axis=0)
mean_best_iou = tf.reduce_mean(best_iou, name='best_iou_per_gt')
summaries = [mean_best_iou]
... | [
"def",
"proposal_metrics",
"(",
"iou",
")",
":",
"# find best roi for each gt, for summary only",
"best_iou",
"=",
"tf",
".",
"reduce_max",
"(",
"iou",
",",
"axis",
"=",
"0",
")",
"mean_best_iou",
"=",
"tf",
".",
"reduce_mean",
"(",
"best_iou",
",",
"name",
"=... | Add summaries for RPN proposals.
Args:
iou: nxm, #proposal x #gt | [
"Add",
"summaries",
"for",
"RPN",
"proposals",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/model_frcnn.py#L20-L38 | train |
tensorpack/tensorpack | examples/FasterRCNN/model_frcnn.py | sample_fast_rcnn_targets | def sample_fast_rcnn_targets(boxes, gt_boxes, gt_labels):
"""
Sample some boxes from all proposals for training.
#fg is guaranteed to be > 0, because ground truth boxes will be added as proposals.
Args:
boxes: nx4 region proposals, floatbox
gt_boxes: mx4, floatbox
gt_labels: m, ... | python | def sample_fast_rcnn_targets(boxes, gt_boxes, gt_labels):
"""
Sample some boxes from all proposals for training.
#fg is guaranteed to be > 0, because ground truth boxes will be added as proposals.
Args:
boxes: nx4 region proposals, floatbox
gt_boxes: mx4, floatbox
gt_labels: m, ... | [
"def",
"sample_fast_rcnn_targets",
"(",
"boxes",
",",
"gt_boxes",
",",
"gt_labels",
")",
":",
"iou",
"=",
"pairwise_iou",
"(",
"boxes",
",",
"gt_boxes",
")",
"# nxm",
"proposal_metrics",
"(",
"iou",
")",
"# add ground truth as proposals as well",
"boxes",
"=",
"tf... | Sample some boxes from all proposals for training.
#fg is guaranteed to be > 0, because ground truth boxes will be added as proposals.
Args:
boxes: nx4 region proposals, floatbox
gt_boxes: mx4, floatbox
gt_labels: m, int32
Returns:
A BoxProposals instance.
sampled_b... | [
"Sample",
"some",
"boxes",
"from",
"all",
"proposals",
"for",
"training",
".",
"#fg",
"is",
"guaranteed",
"to",
"be",
">",
"0",
"because",
"ground",
"truth",
"boxes",
"will",
"be",
"added",
"as",
"proposals",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/model_frcnn.py#L42-L101 | train |
tensorpack/tensorpack | examples/FasterRCNN/model_frcnn.py | fastrcnn_outputs | def fastrcnn_outputs(feature, num_classes, class_agnostic_regression=False):
"""
Args:
feature (any shape):
num_classes(int): num_category + 1
class_agnostic_regression (bool): if True, regression to N x 1 x 4
Returns:
cls_logits: N x num_class classification logits
... | python | def fastrcnn_outputs(feature, num_classes, class_agnostic_regression=False):
"""
Args:
feature (any shape):
num_classes(int): num_category + 1
class_agnostic_regression (bool): if True, regression to N x 1 x 4
Returns:
cls_logits: N x num_class classification logits
... | [
"def",
"fastrcnn_outputs",
"(",
"feature",
",",
"num_classes",
",",
"class_agnostic_regression",
"=",
"False",
")",
":",
"classification",
"=",
"FullyConnected",
"(",
"'class'",
",",
"feature",
",",
"num_classes",
",",
"kernel_initializer",
"=",
"tf",
".",
"random... | Args:
feature (any shape):
num_classes(int): num_category + 1
class_agnostic_regression (bool): if True, regression to N x 1 x 4
Returns:
cls_logits: N x num_class classification logits
reg_logits: N x num_classx4 or Nx2x4 if class agnostic | [
"Args",
":",
"feature",
"(",
"any",
"shape",
")",
":",
"num_classes",
"(",
"int",
")",
":",
"num_category",
"+",
"1",
"class_agnostic_regression",
"(",
"bool",
")",
":",
"if",
"True",
"regression",
"to",
"N",
"x",
"1",
"x",
"4"
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/model_frcnn.py#L105-L124 | train |
tensorpack/tensorpack | examples/FasterRCNN/model_frcnn.py | fastrcnn_losses | def fastrcnn_losses(labels, label_logits, fg_boxes, fg_box_logits):
"""
Args:
labels: n,
label_logits: nxC
fg_boxes: nfgx4, encoded
fg_box_logits: nfgxCx4 or nfgx1x4 if class agnostic
Returns:
label_loss, box_loss
"""
label_loss = tf.nn.sparse_softmax_cross_e... | python | def fastrcnn_losses(labels, label_logits, fg_boxes, fg_box_logits):
"""
Args:
labels: n,
label_logits: nxC
fg_boxes: nfgx4, encoded
fg_box_logits: nfgxCx4 or nfgx1x4 if class agnostic
Returns:
label_loss, box_loss
"""
label_loss = tf.nn.sparse_softmax_cross_e... | [
"def",
"fastrcnn_losses",
"(",
"labels",
",",
"label_logits",
",",
"fg_boxes",
",",
"fg_box_logits",
")",
":",
"label_loss",
"=",
"tf",
".",
"nn",
".",
"sparse_softmax_cross_entropy_with_logits",
"(",
"labels",
"=",
"labels",
",",
"logits",
"=",
"label_logits",
... | Args:
labels: n,
label_logits: nxC
fg_boxes: nfgx4, encoded
fg_box_logits: nfgxCx4 or nfgx1x4 if class agnostic
Returns:
label_loss, box_loss | [
"Args",
":",
"labels",
":",
"n",
"label_logits",
":",
"nxC",
"fg_boxes",
":",
"nfgx4",
"encoded",
"fg_box_logits",
":",
"nfgxCx4",
"or",
"nfgx1x4",
"if",
"class",
"agnostic"
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/model_frcnn.py#L128-L172 | train |
tensorpack/tensorpack | examples/FasterRCNN/model_frcnn.py | fastrcnn_predictions | def fastrcnn_predictions(boxes, scores):
"""
Generate final results from predictions of all proposals.
Args:
boxes: n#classx4 floatbox in float32
scores: nx#class
Returns:
boxes: Kx4
scores: K
labels: K
"""
assert boxes.shape[1] == cfg.DATA.NUM_CLASS
... | python | def fastrcnn_predictions(boxes, scores):
"""
Generate final results from predictions of all proposals.
Args:
boxes: n#classx4 floatbox in float32
scores: nx#class
Returns:
boxes: Kx4
scores: K
labels: K
"""
assert boxes.shape[1] == cfg.DATA.NUM_CLASS
... | [
"def",
"fastrcnn_predictions",
"(",
"boxes",
",",
"scores",
")",
":",
"assert",
"boxes",
".",
"shape",
"[",
"1",
"]",
"==",
"cfg",
".",
"DATA",
".",
"NUM_CLASS",
"assert",
"scores",
".",
"shape",
"[",
"1",
"]",
"==",
"cfg",
".",
"DATA",
".",
"NUM_CLA... | Generate final results from predictions of all proposals.
Args:
boxes: n#classx4 floatbox in float32
scores: nx#class
Returns:
boxes: Kx4
scores: K
labels: K | [
"Generate",
"final",
"results",
"from",
"predictions",
"of",
"all",
"proposals",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/model_frcnn.py#L176-L247 | train |
tensorpack/tensorpack | examples/FasterRCNN/model_frcnn.py | fastrcnn_2fc_head | def fastrcnn_2fc_head(feature):
"""
Args:
feature (any shape):
Returns:
2D head feature
"""
dim = cfg.FPN.FRCNN_FC_HEAD_DIM
init = tf.variance_scaling_initializer()
hidden = FullyConnected('fc6', feature, dim, kernel_initializer=init, activation=tf.nn.relu)
hidden = Full... | python | def fastrcnn_2fc_head(feature):
"""
Args:
feature (any shape):
Returns:
2D head feature
"""
dim = cfg.FPN.FRCNN_FC_HEAD_DIM
init = tf.variance_scaling_initializer()
hidden = FullyConnected('fc6', feature, dim, kernel_initializer=init, activation=tf.nn.relu)
hidden = Full... | [
"def",
"fastrcnn_2fc_head",
"(",
"feature",
")",
":",
"dim",
"=",
"cfg",
".",
"FPN",
".",
"FRCNN_FC_HEAD_DIM",
"init",
"=",
"tf",
".",
"variance_scaling_initializer",
"(",
")",
"hidden",
"=",
"FullyConnected",
"(",
"'fc6'",
",",
"feature",
",",
"dim",
",",
... | Args:
feature (any shape):
Returns:
2D head feature | [
"Args",
":",
"feature",
"(",
"any",
"shape",
")",
":"
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/model_frcnn.py#L256-L268 | train |
tensorpack/tensorpack | examples/FasterRCNN/model_frcnn.py | fastrcnn_Xconv1fc_head | def fastrcnn_Xconv1fc_head(feature, num_convs, norm=None):
"""
Args:
feature (NCHW):
num_classes(int): num_category + 1
num_convs (int): number of conv layers
norm (str or None): either None or 'GN'
Returns:
2D head feature
"""
assert norm in [None, 'GN'], no... | python | def fastrcnn_Xconv1fc_head(feature, num_convs, norm=None):
"""
Args:
feature (NCHW):
num_classes(int): num_category + 1
num_convs (int): number of conv layers
norm (str or None): either None or 'GN'
Returns:
2D head feature
"""
assert norm in [None, 'GN'], no... | [
"def",
"fastrcnn_Xconv1fc_head",
"(",
"feature",
",",
"num_convs",
",",
"norm",
"=",
"None",
")",
":",
"assert",
"norm",
"in",
"[",
"None",
",",
"'GN'",
"]",
",",
"norm",
"l",
"=",
"feature",
"with",
"argscope",
"(",
"Conv2D",
",",
"data_format",
"=",
... | Args:
feature (NCHW):
num_classes(int): num_category + 1
num_convs (int): number of conv layers
norm (str or None): either None or 'GN'
Returns:
2D head feature | [
"Args",
":",
"feature",
"(",
"NCHW",
")",
":",
"num_classes",
"(",
"int",
")",
":",
"num_category",
"+",
"1",
"num_convs",
"(",
"int",
")",
":",
"number",
"of",
"conv",
"layers",
"norm",
"(",
"str",
"or",
"None",
")",
":",
"either",
"None",
"or",
"... | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/model_frcnn.py#L272-L295 | train |
tensorpack/tensorpack | examples/FasterRCNN/model_frcnn.py | FastRCNNHead.fg_box_logits | def fg_box_logits(self):
""" Returns: #fg x ? x 4 """
return tf.gather(self.box_logits, self.proposals.fg_inds(), name='fg_box_logits') | python | def fg_box_logits(self):
""" Returns: #fg x ? x 4 """
return tf.gather(self.box_logits, self.proposals.fg_inds(), name='fg_box_logits') | [
"def",
"fg_box_logits",
"(",
"self",
")",
":",
"return",
"tf",
".",
"gather",
"(",
"self",
".",
"box_logits",
",",
"self",
".",
"proposals",
".",
"fg_inds",
"(",
")",
",",
"name",
"=",
"'fg_box_logits'",
")"
] | Returns: #fg x ? x 4 | [
"Returns",
":",
"#fg",
"x",
"?",
"x",
"4"
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/model_frcnn.py#L358-L360 | train |
tensorpack/tensorpack | examples/FasterRCNN/model_frcnn.py | FastRCNNHead.decoded_output_boxes | def decoded_output_boxes(self):
""" Returns: N x #class x 4 """
anchors = tf.tile(tf.expand_dims(self.proposals.boxes, 1),
[1, cfg.DATA.NUM_CLASS, 1]) # N x #class x 4
decoded_boxes = decode_bbox_target(
self.box_logits / self.bbox_regression_weights,
... | python | def decoded_output_boxes(self):
""" Returns: N x #class x 4 """
anchors = tf.tile(tf.expand_dims(self.proposals.boxes, 1),
[1, cfg.DATA.NUM_CLASS, 1]) # N x #class x 4
decoded_boxes = decode_bbox_target(
self.box_logits / self.bbox_regression_weights,
... | [
"def",
"decoded_output_boxes",
"(",
"self",
")",
":",
"anchors",
"=",
"tf",
".",
"tile",
"(",
"tf",
".",
"expand_dims",
"(",
"self",
".",
"proposals",
".",
"boxes",
",",
"1",
")",
",",
"[",
"1",
",",
"cfg",
".",
"DATA",
".",
"NUM_CLASS",
",",
"1",
... | Returns: N x #class x 4 | [
"Returns",
":",
"N",
"x",
"#class",
"x",
"4"
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/model_frcnn.py#L373-L381 | train |
tensorpack/tensorpack | examples/FasterRCNN/model_frcnn.py | FastRCNNHead.decoded_output_boxes_class_agnostic | def decoded_output_boxes_class_agnostic(self):
""" Returns: Nx4 """
assert self._bbox_class_agnostic
box_logits = tf.reshape(self.box_logits, [-1, 4])
decoded = decode_bbox_target(
box_logits / self.bbox_regression_weights,
self.proposals.boxes
)
r... | python | def decoded_output_boxes_class_agnostic(self):
""" Returns: Nx4 """
assert self._bbox_class_agnostic
box_logits = tf.reshape(self.box_logits, [-1, 4])
decoded = decode_bbox_target(
box_logits / self.bbox_regression_weights,
self.proposals.boxes
)
r... | [
"def",
"decoded_output_boxes_class_agnostic",
"(",
"self",
")",
":",
"assert",
"self",
".",
"_bbox_class_agnostic",
"box_logits",
"=",
"tf",
".",
"reshape",
"(",
"self",
".",
"box_logits",
",",
"[",
"-",
"1",
",",
"4",
"]",
")",
"decoded",
"=",
"decode_bbox_... | Returns: Nx4 | [
"Returns",
":",
"Nx4"
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/model_frcnn.py#L408-L416 | train |
tensorpack/tensorpack | examples/FasterRCNN/model_frcnn.py | FastRCNNHead.output_scores | def output_scores(self, name=None):
""" Returns: N x #class scores, summed to one for each box."""
return tf.nn.softmax(self.label_logits, name=name) | python | def output_scores(self, name=None):
""" Returns: N x #class scores, summed to one for each box."""
return tf.nn.softmax(self.label_logits, name=name) | [
"def",
"output_scores",
"(",
"self",
",",
"name",
"=",
"None",
")",
":",
"return",
"tf",
".",
"nn",
".",
"softmax",
"(",
"self",
".",
"label_logits",
",",
"name",
"=",
"name",
")"
] | Returns: N x #class scores, summed to one for each box. | [
"Returns",
":",
"N",
"x",
"#class",
"scores",
"summed",
"to",
"one",
"for",
"each",
"box",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/model_frcnn.py#L419-L421 | train |
tensorpack/tensorpack | examples/A3C-Gym/train-atari.py | MySimulatorMaster._on_state | def _on_state(self, state, client):
"""
Launch forward prediction for the new state given by some client.
"""
def cb(outputs):
try:
distrib, value = outputs.result()
except CancelledError:
logger.info("Client {} cancelled.".format(c... | python | def _on_state(self, state, client):
"""
Launch forward prediction for the new state given by some client.
"""
def cb(outputs):
try:
distrib, value = outputs.result()
except CancelledError:
logger.info("Client {} cancelled.".format(c... | [
"def",
"_on_state",
"(",
"self",
",",
"state",
",",
"client",
")",
":",
"def",
"cb",
"(",
"outputs",
")",
":",
"try",
":",
"distrib",
",",
"value",
"=",
"outputs",
".",
"result",
"(",
")",
"except",
"CancelledError",
":",
"logger",
".",
"info",
"(",
... | Launch forward prediction for the new state given by some client. | [
"Launch",
"forward",
"prediction",
"for",
"the",
"new",
"state",
"given",
"by",
"some",
"client",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/A3C-Gym/train-atari.py#L159-L174 | train |
tensorpack/tensorpack | examples/A3C-Gym/train-atari.py | MySimulatorMaster._process_msg | def _process_msg(self, client, state, reward, isOver):
"""
Process a message sent from some client.
"""
# in the first message, only state is valid,
# reward&isOver should be discarded
if len(client.memory) > 0:
client.memory[-1].reward = reward
if... | python | def _process_msg(self, client, state, reward, isOver):
"""
Process a message sent from some client.
"""
# in the first message, only state is valid,
# reward&isOver should be discarded
if len(client.memory) > 0:
client.memory[-1].reward = reward
if... | [
"def",
"_process_msg",
"(",
"self",
",",
"client",
",",
"state",
",",
"reward",
",",
"isOver",
")",
":",
"# in the first message, only state is valid,",
"# reward&isOver should be discarded",
"if",
"len",
"(",
"client",
".",
"memory",
")",
">",
"0",
":",
"client",... | Process a message sent from some client. | [
"Process",
"a",
"message",
"sent",
"from",
"some",
"client",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/A3C-Gym/train-atari.py#L176-L192 | train |
tensorpack/tensorpack | examples/GAN/ConditionalGAN-mnist.py | Model.discriminator | def discriminator(self, imgs, y):
""" return a (b, 1) logits"""
yv = y
y = tf.reshape(y, [-1, 1, 1, 10])
with argscope(Conv2D, kernel_size=5, strides=1):
l = (LinearWrap(imgs)
.ConcatWith(tf.tile(y, [1, 28, 28, 1]), 3)
.Conv2D('conv0', 11)
... | python | def discriminator(self, imgs, y):
""" return a (b, 1) logits"""
yv = y
y = tf.reshape(y, [-1, 1, 1, 10])
with argscope(Conv2D, kernel_size=5, strides=1):
l = (LinearWrap(imgs)
.ConcatWith(tf.tile(y, [1, 28, 28, 1]), 3)
.Conv2D('conv0', 11)
... | [
"def",
"discriminator",
"(",
"self",
",",
"imgs",
",",
"y",
")",
":",
"yv",
"=",
"y",
"y",
"=",
"tf",
".",
"reshape",
"(",
"y",
",",
"[",
"-",
"1",
",",
"1",
",",
"1",
",",
"10",
"]",
")",
"with",
"argscope",
"(",
"Conv2D",
",",
"kernel_size"... | return a (b, 1) logits | [
"return",
"a",
"(",
"b",
"1",
")",
"logits"
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/GAN/ConditionalGAN-mnist.py#L62-L85 | train |
tensorpack/tensorpack | tensorpack/tfutils/export.py | ModelExporter.export_compact | def export_compact(self, filename, optimize=True, toco_compatible=False):
"""Create a self-contained inference-only graph and write final graph (in pb format) to disk.
Args:
filename (str): path to the output graph
optimize (bool): whether to use TensorFlow's `optimize_for_infer... | python | def export_compact(self, filename, optimize=True, toco_compatible=False):
"""Create a self-contained inference-only graph and write final graph (in pb format) to disk.
Args:
filename (str): path to the output graph
optimize (bool): whether to use TensorFlow's `optimize_for_infer... | [
"def",
"export_compact",
"(",
"self",
",",
"filename",
",",
"optimize",
"=",
"True",
",",
"toco_compatible",
"=",
"False",
")",
":",
"if",
"toco_compatible",
":",
"assert",
"optimize",
",",
"\"toco_compatible is only effective when optimize=True!\"",
"self",
".",
"g... | Create a self-contained inference-only graph and write final graph (in pb format) to disk.
Args:
filename (str): path to the output graph
optimize (bool): whether to use TensorFlow's `optimize_for_inference`
to prune and optimize the graph. This does not work on all type... | [
"Create",
"a",
"self",
"-",
"contained",
"inference",
"-",
"only",
"graph",
"and",
"write",
"final",
"graph",
"(",
"in",
"pb",
"format",
")",
"to",
"disk",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/tfutils/export.py#L38-L89 | train |
tensorpack/tensorpack | tensorpack/tfutils/export.py | ModelExporter.export_serving | def export_serving(self, filename,
tags=[tf.saved_model.SERVING if is_tfv2() else tf.saved_model.tag_constants.SERVING],
signature_name='prediction_pipeline'):
"""
Converts a checkpoint and graph to a servable for TensorFlow Serving.
Use TF's `SavedM... | python | def export_serving(self, filename,
tags=[tf.saved_model.SERVING if is_tfv2() else tf.saved_model.tag_constants.SERVING],
signature_name='prediction_pipeline'):
"""
Converts a checkpoint and graph to a servable for TensorFlow Serving.
Use TF's `SavedM... | [
"def",
"export_serving",
"(",
"self",
",",
"filename",
",",
"tags",
"=",
"[",
"tf",
".",
"saved_model",
".",
"SERVING",
"if",
"is_tfv2",
"(",
")",
"else",
"tf",
".",
"saved_model",
".",
"tag_constants",
".",
"SERVING",
"]",
",",
"signature_name",
"=",
"'... | Converts a checkpoint and graph to a servable for TensorFlow Serving.
Use TF's `SavedModelBuilder` to export a trained model without tensorpack dependency.
Args:
filename (str): path for export directory
tags (list): list of user specified tags
signature_name (str): ... | [
"Converts",
"a",
"checkpoint",
"and",
"graph",
"to",
"a",
"servable",
"for",
"TensorFlow",
"Serving",
".",
"Use",
"TF",
"s",
"SavedModelBuilder",
"to",
"export",
"a",
"trained",
"model",
"without",
"tensorpack",
"dependency",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/tfutils/export.py#L91-L146 | train |
modin-project/modin | modin/experimental/engines/pandas_on_ray/io_exp.py | _read_sql_with_offset_pandas_on_ray | def _read_sql_with_offset_pandas_on_ray(
partition_column,
start,
end,
num_splits,
sql,
con,
index_col=None,
coerce_float=True,
params=None,
parse_dates=None,
columns=None,
chunksize=None,
): # pragma: no cover
"""Use a Ray task to read a chunk of SQL source.
No... | python | def _read_sql_with_offset_pandas_on_ray(
partition_column,
start,
end,
num_splits,
sql,
con,
index_col=None,
coerce_float=True,
params=None,
parse_dates=None,
columns=None,
chunksize=None,
): # pragma: no cover
"""Use a Ray task to read a chunk of SQL source.
No... | [
"def",
"_read_sql_with_offset_pandas_on_ray",
"(",
"partition_column",
",",
"start",
",",
"end",
",",
"num_splits",
",",
"sql",
",",
"con",
",",
"index_col",
"=",
"None",
",",
"coerce_float",
"=",
"True",
",",
"params",
"=",
"None",
",",
"parse_dates",
"=",
... | Use a Ray task to read a chunk of SQL source.
Note: Ray functions are not detected by codecov (thus pragma: no cover) | [
"Use",
"a",
"Ray",
"task",
"to",
"read",
"a",
"chunk",
"of",
"SQL",
"source",
"."
] | 5b77d242596560c646b8405340c9ce64acb183cb | https://github.com/modin-project/modin/blob/5b77d242596560c646b8405340c9ce64acb183cb/modin/experimental/engines/pandas_on_ray/io_exp.py#L119-L152 | train |
modin-project/modin | modin/experimental/engines/pandas_on_ray/io_exp.py | ExperimentalPandasOnRayIO.read_sql | def read_sql(
cls,
sql,
con,
index_col=None,
coerce_float=True,
params=None,
parse_dates=None,
columns=None,
chunksize=None,
partition_column=None,
lower_bound=None,
upper_bound=None,
max_sessions=None,
):
... | python | def read_sql(
cls,
sql,
con,
index_col=None,
coerce_float=True,
params=None,
parse_dates=None,
columns=None,
chunksize=None,
partition_column=None,
lower_bound=None,
upper_bound=None,
max_sessions=None,
):
... | [
"def",
"read_sql",
"(",
"cls",
",",
"sql",
",",
"con",
",",
"index_col",
"=",
"None",
",",
"coerce_float",
"=",
"True",
",",
"params",
"=",
"None",
",",
"parse_dates",
"=",
"None",
",",
"columns",
"=",
"None",
",",
"chunksize",
"=",
"None",
",",
"par... | Read SQL query or database table into a DataFrame.
Args:
sql: string or SQLAlchemy Selectable (select or text object) SQL query to be executed or a table name.
con: SQLAlchemy connectable (engine/connection) or database string URI or DBAPI2 connection (fallback mode)
index_c... | [
"Read",
"SQL",
"query",
"or",
"database",
"table",
"into",
"a",
"DataFrame",
"."
] | 5b77d242596560c646b8405340c9ce64acb183cb | https://github.com/modin-project/modin/blob/5b77d242596560c646b8405340c9ce64acb183cb/modin/experimental/engines/pandas_on_ray/io_exp.py#L12-L115 | train |
modin-project/modin | modin/pandas/utils.py | _inherit_docstrings | def _inherit_docstrings(parent, excluded=[]):
"""Creates a decorator which overwrites a decorated class' __doc__
attribute with parent's __doc__ attribute. Also overwrites __doc__ of
methods and properties defined in the class with the __doc__ of matching
methods and properties in parent.
Args:
... | python | def _inherit_docstrings(parent, excluded=[]):
"""Creates a decorator which overwrites a decorated class' __doc__
attribute with parent's __doc__ attribute. Also overwrites __doc__ of
methods and properties defined in the class with the __doc__ of matching
methods and properties in parent.
Args:
... | [
"def",
"_inherit_docstrings",
"(",
"parent",
",",
"excluded",
"=",
"[",
"]",
")",
":",
"def",
"decorator",
"(",
"cls",
")",
":",
"if",
"parent",
"not",
"in",
"excluded",
":",
"cls",
".",
"__doc__",
"=",
"parent",
".",
"__doc__",
"for",
"attr",
",",
"... | Creates a decorator which overwrites a decorated class' __doc__
attribute with parent's __doc__ attribute. Also overwrites __doc__ of
methods and properties defined in the class with the __doc__ of matching
methods and properties in parent.
Args:
parent (object): Class from which the decorated ... | [
"Creates",
"a",
"decorator",
"which",
"overwrites",
"a",
"decorated",
"class",
"__doc__",
"attribute",
"with",
"parent",
"s",
"__doc__",
"attribute",
".",
"Also",
"overwrites",
"__doc__",
"of",
"methods",
"and",
"properties",
"defined",
"in",
"the",
"class",
"wi... | 5b77d242596560c646b8405340c9ce64acb183cb | https://github.com/modin-project/modin/blob/5b77d242596560c646b8405340c9ce64acb183cb/modin/pandas/utils.py#L33-L65 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.