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/models/nonlin.py | PReLU | def PReLU(x, init=0.001, name='output'):
"""
Parameterized ReLU as in the paper `Delving Deep into Rectifiers: Surpassing
Human-Level Performance on ImageNet Classification
<http://arxiv.org/abs/1502.01852>`_.
Args:
x (tf.Tensor): input
init (float): initial value for the learnable ... | python | def PReLU(x, init=0.001, name='output'):
"""
Parameterized ReLU as in the paper `Delving Deep into Rectifiers: Surpassing
Human-Level Performance on ImageNet Classification
<http://arxiv.org/abs/1502.01852>`_.
Args:
x (tf.Tensor): input
init (float): initial value for the learnable ... | [
"def",
"PReLU",
"(",
"x",
",",
"init",
"=",
"0.001",
",",
"name",
"=",
"'output'",
")",
":",
"init",
"=",
"tfv1",
".",
"constant_initializer",
"(",
"init",
")",
"alpha",
"=",
"tfv1",
".",
"get_variable",
"(",
"'alpha'",
",",
"[",
"]",
",",
"initializ... | Parameterized ReLU as in the paper `Delving Deep into Rectifiers: Surpassing
Human-Level Performance on ImageNet Classification
<http://arxiv.org/abs/1502.01852>`_.
Args:
x (tf.Tensor): input
init (float): initial value for the learnable slope.
name (str): name of the output.
V... | [
"Parameterized",
"ReLU",
"as",
"in",
"the",
"paper",
"Delving",
"Deep",
"into",
"Rectifiers",
":",
"Surpassing",
"Human",
"-",
"Level",
"Performance",
"on",
"ImageNet",
"Classification",
"<http",
":",
"//",
"arxiv",
".",
"org",
"/",
"abs",
"/",
"1502",
".",
... | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/models/nonlin.py#L39-L60 | train |
tensorpack/tensorpack | tensorpack/models/nonlin.py | BNReLU | def BNReLU(x, name=None):
"""
A shorthand of BatchNormalization + ReLU.
"""
x = BatchNorm('bn', x)
x = tf.nn.relu(x, name=name)
return x | python | def BNReLU(x, name=None):
"""
A shorthand of BatchNormalization + ReLU.
"""
x = BatchNorm('bn', x)
x = tf.nn.relu(x, name=name)
return x | [
"def",
"BNReLU",
"(",
"x",
",",
"name",
"=",
"None",
")",
":",
"x",
"=",
"BatchNorm",
"(",
"'bn'",
",",
"x",
")",
"x",
"=",
"tf",
".",
"nn",
".",
"relu",
"(",
"x",
",",
"name",
"=",
"name",
")",
"return",
"x"
] | A shorthand of BatchNormalization + ReLU. | [
"A",
"shorthand",
"of",
"BatchNormalization",
"+",
"ReLU",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/models/nonlin.py#L64-L70 | train |
tensorpack/tensorpack | examples/FasterRCNN/backbone.py | GroupNorm | def GroupNorm(x, group=32, gamma_initializer=tf.constant_initializer(1.)):
"""
More code that reproduces the paper can be found at https://github.com/ppwwyyxx/GroupNorm-reproduce/.
"""
shape = x.get_shape().as_list()
ndims = len(shape)
assert ndims == 4, shape
chan = shape[1]
assert chan... | python | def GroupNorm(x, group=32, gamma_initializer=tf.constant_initializer(1.)):
"""
More code that reproduces the paper can be found at https://github.com/ppwwyyxx/GroupNorm-reproduce/.
"""
shape = x.get_shape().as_list()
ndims = len(shape)
assert ndims == 4, shape
chan = shape[1]
assert chan... | [
"def",
"GroupNorm",
"(",
"x",
",",
"group",
"=",
"32",
",",
"gamma_initializer",
"=",
"tf",
".",
"constant_initializer",
"(",
"1.",
")",
")",
":",
"shape",
"=",
"x",
".",
"get_shape",
"(",
")",
".",
"as_list",
"(",
")",
"ndims",
"=",
"len",
"(",
"s... | More code that reproduces the paper can be found at https://github.com/ppwwyyxx/GroupNorm-reproduce/. | [
"More",
"code",
"that",
"reproduces",
"the",
"paper",
"can",
"be",
"found",
"at",
"https",
":",
"//",
"github",
".",
"com",
"/",
"ppwwyyxx",
"/",
"GroupNorm",
"-",
"reproduce",
"/",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/backbone.py#L17-L44 | train |
tensorpack/tensorpack | examples/FasterRCNN/backbone.py | backbone_scope | def backbone_scope(freeze):
"""
Args:
freeze (bool): whether to freeze all the variables under the scope
"""
def nonlin(x):
x = get_norm()(x)
return tf.nn.relu(x)
with argscope([Conv2D, MaxPooling, BatchNorm], data_format='channels_first'), \
argscope(Conv2D, use... | python | def backbone_scope(freeze):
"""
Args:
freeze (bool): whether to freeze all the variables under the scope
"""
def nonlin(x):
x = get_norm()(x)
return tf.nn.relu(x)
with argscope([Conv2D, MaxPooling, BatchNorm], data_format='channels_first'), \
argscope(Conv2D, use... | [
"def",
"backbone_scope",
"(",
"freeze",
")",
":",
"def",
"nonlin",
"(",
"x",
")",
":",
"x",
"=",
"get_norm",
"(",
")",
"(",
"x",
")",
"return",
"tf",
".",
"nn",
".",
"relu",
"(",
"x",
")",
"with",
"argscope",
"(",
"[",
"Conv2D",
",",
"MaxPooling"... | Args:
freeze (bool): whether to freeze all the variables under the scope | [
"Args",
":",
"freeze",
"(",
"bool",
")",
":",
"whether",
"to",
"freeze",
"all",
"the",
"variables",
"under",
"the",
"scope"
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/backbone.py#L66-L93 | train |
tensorpack/tensorpack | tensorpack/dataflow/dataset/mnist.py | extract_images | def extract_images(filename):
"""Extract the images into a 4D uint8 numpy array [index, y, x, depth]."""
with gzip.open(filename) as bytestream:
magic = _read32(bytestream)
if magic != 2051:
raise ValueError(
'Invalid magic number %d in MNIST image file: %s' %
... | python | def extract_images(filename):
"""Extract the images into a 4D uint8 numpy array [index, y, x, depth]."""
with gzip.open(filename) as bytestream:
magic = _read32(bytestream)
if magic != 2051:
raise ValueError(
'Invalid magic number %d in MNIST image file: %s' %
... | [
"def",
"extract_images",
"(",
"filename",
")",
":",
"with",
"gzip",
".",
"open",
"(",
"filename",
")",
"as",
"bytestream",
":",
"magic",
"=",
"_read32",
"(",
"bytestream",
")",
"if",
"magic",
"!=",
"2051",
":",
"raise",
"ValueError",
"(",
"'Invalid magic n... | Extract the images into a 4D uint8 numpy array [index, y, x, depth]. | [
"Extract",
"the",
"images",
"into",
"a",
"4D",
"uint8",
"numpy",
"array",
"[",
"index",
"y",
"x",
"depth",
"]",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/dataflow/dataset/mnist.py#L32-L47 | train |
tensorpack/tensorpack | tensorpack/dataflow/dataset/mnist.py | extract_labels | def extract_labels(filename):
"""Extract the labels into a 1D uint8 numpy array [index]."""
with gzip.open(filename) as bytestream:
magic = _read32(bytestream)
if magic != 2049:
raise ValueError(
'Invalid magic number %d in MNIST label file: %s' %
(mag... | python | def extract_labels(filename):
"""Extract the labels into a 1D uint8 numpy array [index]."""
with gzip.open(filename) as bytestream:
magic = _read32(bytestream)
if magic != 2049:
raise ValueError(
'Invalid magic number %d in MNIST label file: %s' %
(mag... | [
"def",
"extract_labels",
"(",
"filename",
")",
":",
"with",
"gzip",
".",
"open",
"(",
"filename",
")",
"as",
"bytestream",
":",
"magic",
"=",
"_read32",
"(",
"bytestream",
")",
"if",
"magic",
"!=",
"2049",
":",
"raise",
"ValueError",
"(",
"'Invalid magic n... | Extract the labels into a 1D uint8 numpy array [index]. | [
"Extract",
"the",
"labels",
"into",
"a",
"1D",
"uint8",
"numpy",
"array",
"[",
"index",
"]",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/dataflow/dataset/mnist.py#L50-L61 | train |
tensorpack/tensorpack | tensorpack/utils/develop.py | create_dummy_class | def create_dummy_class(klass, dependency):
"""
When a dependency of a class is not available, create a dummy class which throws ImportError when used.
Args:
klass (str): name of the class.
dependency (str): name of the dependency.
Returns:
class: a class object
"""
asse... | python | def create_dummy_class(klass, dependency):
"""
When a dependency of a class is not available, create a dummy class which throws ImportError when used.
Args:
klass (str): name of the class.
dependency (str): name of the dependency.
Returns:
class: a class object
"""
asse... | [
"def",
"create_dummy_class",
"(",
"klass",
",",
"dependency",
")",
":",
"assert",
"not",
"building_rtfd",
"(",
")",
"class",
"_DummyMetaClass",
"(",
"type",
")",
":",
"# throw error on class attribute access",
"def",
"__getattr__",
"(",
"_",
",",
"__",
")",
":",... | When a dependency of a class is not available, create a dummy class which throws ImportError when used.
Args:
klass (str): name of the class.
dependency (str): name of the dependency.
Returns:
class: a class object | [
"When",
"a",
"dependency",
"of",
"a",
"class",
"is",
"not",
"available",
"create",
"a",
"dummy",
"class",
"which",
"throws",
"ImportError",
"when",
"used",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/develop.py#L21-L45 | train |
tensorpack/tensorpack | tensorpack/utils/develop.py | create_dummy_func | def create_dummy_func(func, dependency):
"""
When a dependency of a function is not available, create a dummy function which throws ImportError when used.
Args:
func (str): name of the function.
dependency (str or list[str]): name(s) of the dependency.
Returns:
function: a func... | python | def create_dummy_func(func, dependency):
"""
When a dependency of a function is not available, create a dummy function which throws ImportError when used.
Args:
func (str): name of the function.
dependency (str or list[str]): name(s) of the dependency.
Returns:
function: a func... | [
"def",
"create_dummy_func",
"(",
"func",
",",
"dependency",
")",
":",
"assert",
"not",
"building_rtfd",
"(",
")",
"if",
"isinstance",
"(",
"dependency",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"dependency",
"=",
"','",
".",
"join",
"(",
"dependenc... | When a dependency of a function is not available, create a dummy function which throws ImportError when used.
Args:
func (str): name of the function.
dependency (str or list[str]): name(s) of the dependency.
Returns:
function: a function object | [
"When",
"a",
"dependency",
"of",
"a",
"function",
"is",
"not",
"available",
"create",
"a",
"dummy",
"function",
"which",
"throws",
"ImportError",
"when",
"used",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/develop.py#L48-L66 | train |
tensorpack/tensorpack | tensorpack/utils/develop.py | log_deprecated | def log_deprecated(name="", text="", eos=""):
"""
Log deprecation warning.
Args:
name (str): name of the deprecated item.
text (str, optional): information about the deprecation.
eos (str, optional): end of service date such as "YYYY-MM-DD".
"""
assert name or text
if eo... | python | def log_deprecated(name="", text="", eos=""):
"""
Log deprecation warning.
Args:
name (str): name of the deprecated item.
text (str, optional): information about the deprecation.
eos (str, optional): end of service date such as "YYYY-MM-DD".
"""
assert name or text
if eo... | [
"def",
"log_deprecated",
"(",
"name",
"=",
"\"\"",
",",
"text",
"=",
"\"\"",
",",
"eos",
"=",
"\"\"",
")",
":",
"assert",
"name",
"or",
"text",
"if",
"eos",
":",
"eos",
"=",
"\"after \"",
"+",
"datetime",
"(",
"*",
"map",
"(",
"int",
",",
"eos",
... | Log deprecation warning.
Args:
name (str): name of the deprecated item.
text (str, optional): information about the deprecation.
eos (str, optional): end of service date such as "YYYY-MM-DD". | [
"Log",
"deprecation",
"warning",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/develop.py#L78-L99 | train |
tensorpack/tensorpack | tensorpack/utils/develop.py | deprecated | def deprecated(text="", eos=""):
"""
Args:
text, eos: same as :func:`log_deprecated`.
Returns:
a decorator which deprecates the function.
Example:
.. code-block:: python
@deprecated("Explanation of what to do instead.", "2017-11-4")
def foo(...):
... | python | def deprecated(text="", eos=""):
"""
Args:
text, eos: same as :func:`log_deprecated`.
Returns:
a decorator which deprecates the function.
Example:
.. code-block:: python
@deprecated("Explanation of what to do instead.", "2017-11-4")
def foo(...):
... | [
"def",
"deprecated",
"(",
"text",
"=",
"\"\"",
",",
"eos",
"=",
"\"\"",
")",
":",
"def",
"get_location",
"(",
")",
":",
"import",
"inspect",
"frame",
"=",
"inspect",
".",
"currentframe",
"(",
")",
"if",
"frame",
":",
"callstack",
"=",
"inspect",
".",
... | Args:
text, eos: same as :func:`log_deprecated`.
Returns:
a decorator which deprecates the function.
Example:
.. code-block:: python
@deprecated("Explanation of what to do instead.", "2017-11-4")
def foo(...):
pass | [
"Args",
":",
"text",
"eos",
":",
"same",
"as",
":",
"func",
":",
"log_deprecated",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/develop.py#L102-L136 | train |
tensorpack/tensorpack | tensorpack/input_source/input_source.py | QueueInput.refill_queue | def refill_queue(self):
"""
Clear the queue, then call dataflow.__iter__() again and fill into the queue.
"""
self.thread.pause() # pause enqueue
opt = tfv1.RunOptions()
opt.timeout_in_ms = 2000 # 2s
sess = tfv1.get_default_session()
# dequeue until... | python | def refill_queue(self):
"""
Clear the queue, then call dataflow.__iter__() again and fill into the queue.
"""
self.thread.pause() # pause enqueue
opt = tfv1.RunOptions()
opt.timeout_in_ms = 2000 # 2s
sess = tfv1.get_default_session()
# dequeue until... | [
"def",
"refill_queue",
"(",
"self",
")",
":",
"self",
".",
"thread",
".",
"pause",
"(",
")",
"# pause enqueue",
"opt",
"=",
"tfv1",
".",
"RunOptions",
"(",
")",
"opt",
".",
"timeout_in_ms",
"=",
"2000",
"# 2s",
"sess",
"=",
"tfv1",
".",
"get_default_sess... | Clear the queue, then call dataflow.__iter__() again and fill into the queue. | [
"Clear",
"the",
"queue",
"then",
"call",
"dataflow",
".",
"__iter__",
"()",
"again",
"and",
"fill",
"into",
"the",
"queue",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/input_source/input_source.py#L228-L246 | train |
tensorpack/tensorpack | tensorpack/input_source/input_source.py | QueueInput._create_ema_callback | def _create_ema_callback(self):
"""
Create a hook-only callback which maintain EMA of the queue size.
Also tf.summary.scalar the EMA.
"""
with self.cached_name_scope():
# in TF there is no API to get queue capacity, so we can only summary the size
size = t... | python | def _create_ema_callback(self):
"""
Create a hook-only callback which maintain EMA of the queue size.
Also tf.summary.scalar the EMA.
"""
with self.cached_name_scope():
# in TF there is no API to get queue capacity, so we can only summary the size
size = t... | [
"def",
"_create_ema_callback",
"(",
"self",
")",
":",
"with",
"self",
".",
"cached_name_scope",
"(",
")",
":",
"# in TF there is no API to get queue capacity, so we can only summary the size",
"size",
"=",
"tf",
".",
"cast",
"(",
"self",
".",
"queue",
".",
"size",
"... | Create a hook-only callback which maintain EMA of the queue size.
Also tf.summary.scalar the EMA. | [
"Create",
"a",
"hook",
"-",
"only",
"callback",
"which",
"maintain",
"EMA",
"of",
"the",
"queue",
"size",
".",
"Also",
"tf",
".",
"summary",
".",
"scalar",
"the",
"EMA",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/input_source/input_source.py#L248-L263 | train |
tensorpack/tensorpack | tensorpack/input_source/input_source.py | BatchQueueInput._setup | def _setup(self, inputs):
logger.info("Setting up the queue for CPU prefetching ...")
self.input_placehdrs = [build_or_reuse_placeholder(v) for v in inputs]
assert len(self.input_placehdrs) > 0, \
"BatchQueueInput has to be used with some input signature!"
# prepare placehol... | python | def _setup(self, inputs):
logger.info("Setting up the queue for CPU prefetching ...")
self.input_placehdrs = [build_or_reuse_placeholder(v) for v in inputs]
assert len(self.input_placehdrs) > 0, \
"BatchQueueInput has to be used with some input signature!"
# prepare placehol... | [
"def",
"_setup",
"(",
"self",
",",
"inputs",
")",
":",
"logger",
".",
"info",
"(",
"\"Setting up the queue for CPU prefetching ...\"",
")",
"self",
".",
"input_placehdrs",
"=",
"[",
"build_or_reuse_placeholder",
"(",
"v",
")",
"for",
"v",
"in",
"inputs",
"]",
... | shapes except for the batch dimension | [
"shapes",
"except",
"for",
"the",
"batch",
"dimension"
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/input_source/input_source.py#L301-L331 | train |
tensorpack/tensorpack | tensorpack/input_source/input_source.py | TFDatasetInput.dataflow_to_dataset | def dataflow_to_dataset(df, types):
"""
Wrap a dataflow to tf.data.Dataset.
This function will also reset the dataflow.
If the dataflow itself is finite, the returned dataset is also finite.
Therefore, if used for training, you'll need to add `.repeat()` on the returned
... | python | def dataflow_to_dataset(df, types):
"""
Wrap a dataflow to tf.data.Dataset.
This function will also reset the dataflow.
If the dataflow itself is finite, the returned dataset is also finite.
Therefore, if used for training, you'll need to add `.repeat()` on the returned
... | [
"def",
"dataflow_to_dataset",
"(",
"df",
",",
"types",
")",
":",
"# TODO theoretically it can support dict",
"assert",
"isinstance",
"(",
"df",
",",
"DataFlow",
")",
",",
"df",
"assert",
"isinstance",
"(",
"types",
",",
"(",
"list",
",",
"tuple",
")",
")",
"... | Wrap a dataflow to tf.data.Dataset.
This function will also reset the dataflow.
If the dataflow itself is finite, the returned dataset is also finite.
Therefore, if used for training, you'll need to add `.repeat()` on the returned
dataset.
Args:
df (DataFlow): a dat... | [
"Wrap",
"a",
"dataflow",
"to",
"tf",
".",
"data",
".",
"Dataset",
".",
"This",
"function",
"will",
"also",
"reset",
"the",
"dataflow",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/input_source/input_source.py#L496-L519 | train |
tensorpack/tensorpack | tensorpack/predict/multigpu.py | MultiTowerOfflinePredictor.get_predictor | def get_predictor(self, n):
"""
Returns:
OnlinePredictor: the nth predictor on the nth tower.
"""
l = len(self.predictors)
if n >= l:
logger.warn("n > #towers, will assign predictor to GPU by round-robin")
return [self.predictors[k % l] for k in ra... | python | def get_predictor(self, n):
"""
Returns:
OnlinePredictor: the nth predictor on the nth tower.
"""
l = len(self.predictors)
if n >= l:
logger.warn("n > #towers, will assign predictor to GPU by round-robin")
return [self.predictors[k % l] for k in ra... | [
"def",
"get_predictor",
"(",
"self",
",",
"n",
")",
":",
"l",
"=",
"len",
"(",
"self",
".",
"predictors",
")",
"if",
"n",
">=",
"l",
":",
"logger",
".",
"warn",
"(",
"\"n > #towers, will assign predictor to GPU by round-robin\"",
")",
"return",
"[",
"self",
... | Returns:
OnlinePredictor: the nth predictor on the nth tower. | [
"Returns",
":",
"OnlinePredictor",
":",
"the",
"nth",
"predictor",
"on",
"the",
"nth",
"tower",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/predict/multigpu.py#L62-L70 | train |
tensorpack/tensorpack | examples/FasterRCNN/utils/np_box_ops.py | intersection | def intersection(boxes1, boxes2):
"""Compute pairwise intersection areas between boxes.
Args:
boxes1: a numpy array with shape [N, 4] holding N boxes
boxes2: a numpy array with shape [M, 4] holding M boxes
Returns:
a numpy array with shape [N*M] representing pairwise intersection area
"""
[y_min... | python | def intersection(boxes1, boxes2):
"""Compute pairwise intersection areas between boxes.
Args:
boxes1: a numpy array with shape [N, 4] holding N boxes
boxes2: a numpy array with shape [M, 4] holding M boxes
Returns:
a numpy array with shape [N*M] representing pairwise intersection area
"""
[y_min... | [
"def",
"intersection",
"(",
"boxes1",
",",
"boxes2",
")",
":",
"[",
"y_min1",
",",
"x_min1",
",",
"y_max1",
",",
"x_max1",
"]",
"=",
"np",
".",
"split",
"(",
"boxes1",
",",
"4",
",",
"axis",
"=",
"1",
")",
"[",
"y_min2",
",",
"x_min2",
",",
"y_ma... | Compute pairwise intersection areas between boxes.
Args:
boxes1: a numpy array with shape [N, 4] holding N boxes
boxes2: a numpy array with shape [M, 4] holding M boxes
Returns:
a numpy array with shape [N*M] representing pairwise intersection area | [
"Compute",
"pairwise",
"intersection",
"areas",
"between",
"boxes",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/utils/np_box_ops.py#L37-L60 | train |
tensorpack/tensorpack | examples/FasterRCNN/utils/np_box_ops.py | iou | def iou(boxes1, boxes2):
"""Computes pairwise intersection-over-union between box collections.
Args:
boxes1: a numpy array with shape [N, 4] holding N boxes.
boxes2: a numpy array with shape [M, 4] holding M boxes.
Returns:
a numpy array with shape [N, M] representing pairwise iou scores.
"""
in... | python | def iou(boxes1, boxes2):
"""Computes pairwise intersection-over-union between box collections.
Args:
boxes1: a numpy array with shape [N, 4] holding N boxes.
boxes2: a numpy array with shape [M, 4] holding M boxes.
Returns:
a numpy array with shape [N, M] representing pairwise iou scores.
"""
in... | [
"def",
"iou",
"(",
"boxes1",
",",
"boxes2",
")",
":",
"intersect",
"=",
"intersection",
"(",
"boxes1",
",",
"boxes2",
")",
"area1",
"=",
"area",
"(",
"boxes1",
")",
"area2",
"=",
"area",
"(",
"boxes2",
")",
"union",
"=",
"np",
".",
"expand_dims",
"("... | Computes pairwise intersection-over-union between box collections.
Args:
boxes1: a numpy array with shape [N, 4] holding N boxes.
boxes2: a numpy array with shape [M, 4] holding M boxes.
Returns:
a numpy array with shape [N, M] representing pairwise iou scores. | [
"Computes",
"pairwise",
"intersection",
"-",
"over",
"-",
"union",
"between",
"box",
"collections",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/utils/np_box_ops.py#L63-L78 | train |
tensorpack/tensorpack | examples/FasterRCNN/utils/np_box_ops.py | ioa | def ioa(boxes1, boxes2):
"""Computes pairwise intersection-over-area between box collections.
Intersection-over-area (ioa) between two boxes box1 and box2 is defined as
their intersection area over box2's area. Note that ioa is not symmetric,
that is, IOA(box1, box2) != IOA(box2, box1).
Args:
boxes1: a ... | python | def ioa(boxes1, boxes2):
"""Computes pairwise intersection-over-area between box collections.
Intersection-over-area (ioa) between two boxes box1 and box2 is defined as
their intersection area over box2's area. Note that ioa is not symmetric,
that is, IOA(box1, box2) != IOA(box2, box1).
Args:
boxes1: a ... | [
"def",
"ioa",
"(",
"boxes1",
",",
"boxes2",
")",
":",
"intersect",
"=",
"intersection",
"(",
"boxes1",
",",
"boxes2",
")",
"inv_areas",
"=",
"np",
".",
"expand_dims",
"(",
"1.0",
"/",
"area",
"(",
"boxes2",
")",
",",
"axis",
"=",
"0",
")",
"return",
... | Computes pairwise intersection-over-area between box collections.
Intersection-over-area (ioa) between two boxes box1 and box2 is defined as
their intersection area over box2's area. Note that ioa is not symmetric,
that is, IOA(box1, box2) != IOA(box2, box1).
Args:
boxes1: a numpy array with shape [N, 4] ... | [
"Computes",
"pairwise",
"intersection",
"-",
"over",
"-",
"area",
"between",
"box",
"collections",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/utils/np_box_ops.py#L81-L97 | train |
tensorpack/tensorpack | tensorpack/dataflow/dataset/caltech101.py | maybe_download | def maybe_download(url, work_directory):
"""Download the data from Marlin's website, unless it's already here."""
filename = url.split("/")[-1]
filepath = os.path.join(work_directory, filename)
if not os.path.exists(filepath):
logger.info("Downloading to {}...".format(filepath))
download... | python | def maybe_download(url, work_directory):
"""Download the data from Marlin's website, unless it's already here."""
filename = url.split("/")[-1]
filepath = os.path.join(work_directory, filename)
if not os.path.exists(filepath):
logger.info("Downloading to {}...".format(filepath))
download... | [
"def",
"maybe_download",
"(",
"url",
",",
"work_directory",
")",
":",
"filename",
"=",
"url",
".",
"split",
"(",
"\"/\"",
")",
"[",
"-",
"1",
"]",
"filepath",
"=",
"os",
".",
"path",
".",
"join",
"(",
"work_directory",
",",
"filename",
")",
"if",
"no... | Download the data from Marlin's website, unless it's already here. | [
"Download",
"the",
"data",
"from",
"Marlin",
"s",
"website",
"unless",
"it",
"s",
"already",
"here",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/dataflow/dataset/caltech101.py#L15-L22 | train |
tensorpack/tensorpack | tensorpack/dataflow/dataset/ilsvrc.py | ILSVRCMeta.get_synset_1000 | def get_synset_1000(self):
"""
Returns:
dict: {cls_number: synset_id}
"""
fname = os.path.join(self.dir, 'synsets.txt')
assert os.path.isfile(fname)
lines = [x.strip() for x in open(fname).readlines()]
return dict(enumerate(lines)) | python | def get_synset_1000(self):
"""
Returns:
dict: {cls_number: synset_id}
"""
fname = os.path.join(self.dir, 'synsets.txt')
assert os.path.isfile(fname)
lines = [x.strip() for x in open(fname).readlines()]
return dict(enumerate(lines)) | [
"def",
"get_synset_1000",
"(",
"self",
")",
":",
"fname",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"dir",
",",
"'synsets.txt'",
")",
"assert",
"os",
".",
"path",
".",
"isfile",
"(",
"fname",
")",
"lines",
"=",
"[",
"x",
".",
"strip",
... | Returns:
dict: {cls_number: synset_id} | [
"Returns",
":",
"dict",
":",
"{",
"cls_number",
":",
"synset_id",
"}"
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/dataflow/dataset/ilsvrc.py#L45-L53 | train |
tensorpack/tensorpack | tensorpack/dataflow/dataset/ilsvrc.py | ILSVRCMeta.get_image_list | def get_image_list(self, name, dir_structure='original'):
"""
Args:
name (str): 'train' or 'val' or 'test'
dir_structure (str): same as in :meth:`ILSVRC12.__init__()`.
Returns:
list: list of (image filename, label)
"""
assert name in ['train', ... | python | def get_image_list(self, name, dir_structure='original'):
"""
Args:
name (str): 'train' or 'val' or 'test'
dir_structure (str): same as in :meth:`ILSVRC12.__init__()`.
Returns:
list: list of (image filename, label)
"""
assert name in ['train', ... | [
"def",
"get_image_list",
"(",
"self",
",",
"name",
",",
"dir_structure",
"=",
"'original'",
")",
":",
"assert",
"name",
"in",
"[",
"'train'",
",",
"'val'",
",",
"'test'",
"]",
"assert",
"dir_structure",
"in",
"[",
"'original'",
",",
"'train'",
"]",
"add_la... | Args:
name (str): 'train' or 'val' or 'test'
dir_structure (str): same as in :meth:`ILSVRC12.__init__()`.
Returns:
list: list of (image filename, label) | [
"Args",
":",
"name",
"(",
"str",
")",
":",
"train",
"or",
"val",
"or",
"test",
"dir_structure",
"(",
"str",
")",
":",
"same",
"as",
"in",
":",
"meth",
":",
"ILSVRC12",
".",
"__init__",
"()",
".",
"Returns",
":",
"list",
":",
"list",
"of",
"(",
"i... | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/dataflow/dataset/ilsvrc.py#L59-L86 | train |
tensorpack/tensorpack | tensorpack/dataflow/dataset/ilsvrc.py | ILSVRCMeta.get_per_pixel_mean | def get_per_pixel_mean(self, size=None):
"""
Args:
size (tuple): image size in (h, w). Defaults to (256, 256).
Returns:
np.ndarray: per-pixel mean of shape (h, w, 3 (BGR)) in range [0, 255].
"""
if self.caffepb is None:
self.caffepb = get_caffe... | python | def get_per_pixel_mean(self, size=None):
"""
Args:
size (tuple): image size in (h, w). Defaults to (256, 256).
Returns:
np.ndarray: per-pixel mean of shape (h, w, 3 (BGR)) in range [0, 255].
"""
if self.caffepb is None:
self.caffepb = get_caffe... | [
"def",
"get_per_pixel_mean",
"(",
"self",
",",
"size",
"=",
"None",
")",
":",
"if",
"self",
".",
"caffepb",
"is",
"None",
":",
"self",
".",
"caffepb",
"=",
"get_caffe_pb",
"(",
")",
"obj",
"=",
"self",
".",
"caffepb",
".",
"BlobProto",
"(",
")",
"mea... | Args:
size (tuple): image size in (h, w). Defaults to (256, 256).
Returns:
np.ndarray: per-pixel mean of shape (h, w, 3 (BGR)) in range [0, 255]. | [
"Args",
":",
"size",
"(",
"tuple",
")",
":",
"image",
"size",
"in",
"(",
"h",
"w",
")",
".",
"Defaults",
"to",
"(",
"256",
"256",
")",
".",
"Returns",
":",
"np",
".",
"ndarray",
":",
"per",
"-",
"pixel",
"mean",
"of",
"shape",
"(",
"h",
"w",
... | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/dataflow/dataset/ilsvrc.py#L88-L106 | train |
tensorpack/tensorpack | tensorpack/dataflow/dataset/ilsvrc.py | ILSVRCMeta.guess_dir_structure | def guess_dir_structure(dir):
"""
Return the directory structure of "dir".
Args:
dir(str): something like '/path/to/imagenet/val'
Returns:
either 'train' or 'original'
"""
subdir = os.listdir(dir)[0]
# find a subdir starting with 'n'
... | python | def guess_dir_structure(dir):
"""
Return the directory structure of "dir".
Args:
dir(str): something like '/path/to/imagenet/val'
Returns:
either 'train' or 'original'
"""
subdir = os.listdir(dir)[0]
# find a subdir starting with 'n'
... | [
"def",
"guess_dir_structure",
"(",
"dir",
")",
":",
"subdir",
"=",
"os",
".",
"listdir",
"(",
"dir",
")",
"[",
"0",
"]",
"# find a subdir starting with 'n'",
"if",
"subdir",
".",
"startswith",
"(",
"'n'",
")",
"and",
"os",
".",
"path",
".",
"isdir",
"(",... | Return the directory structure of "dir".
Args:
dir(str): something like '/path/to/imagenet/val'
Returns:
either 'train' or 'original' | [
"Return",
"the",
"directory",
"structure",
"of",
"dir",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/dataflow/dataset/ilsvrc.py#L109-L129 | train |
tensorpack/tensorpack | examples/FasterRCNN/dataset.py | COCODetection.print_coco_metrics | def print_coco_metrics(self, json_file):
"""
Args:
json_file (str): path to the results json file in coco format
Returns:
dict: the evaluation metrics
"""
from pycocotools.cocoeval import COCOeval
ret = {}
cocoDt = self.coco.loadRes(json_fi... | python | def print_coco_metrics(self, json_file):
"""
Args:
json_file (str): path to the results json file in coco format
Returns:
dict: the evaluation metrics
"""
from pycocotools.cocoeval import COCOeval
ret = {}
cocoDt = self.coco.loadRes(json_fi... | [
"def",
"print_coco_metrics",
"(",
"self",
",",
"json_file",
")",
":",
"from",
"pycocotools",
".",
"cocoeval",
"import",
"COCOeval",
"ret",
"=",
"{",
"}",
"cocoDt",
"=",
"self",
".",
"coco",
".",
"loadRes",
"(",
"json_file",
")",
"cocoEval",
"=",
"COCOeval"... | Args:
json_file (str): path to the results json file in coco format
Returns:
dict: the evaluation metrics | [
"Args",
":",
"json_file",
"(",
"str",
")",
":",
"path",
"to",
"the",
"results",
"json",
"file",
"in",
"coco",
"format",
"Returns",
":",
"dict",
":",
"the",
"evaluation",
"metrics"
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/dataset.py#L49-L75 | train |
tensorpack/tensorpack | examples/FasterRCNN/dataset.py | COCODetection.load | def load(self, add_gt=True, add_mask=False):
"""
Args:
add_gt: whether to add ground truth bounding box annotations to the dicts
add_mask: whether to also add ground truth mask
Returns:
a list of dict, each has keys including:
'image_id', 'fil... | python | def load(self, add_gt=True, add_mask=False):
"""
Args:
add_gt: whether to add ground truth bounding box annotations to the dicts
add_mask: whether to also add ground truth mask
Returns:
a list of dict, each has keys including:
'image_id', 'fil... | [
"def",
"load",
"(",
"self",
",",
"add_gt",
"=",
"True",
",",
"add_mask",
"=",
"False",
")",
":",
"if",
"add_mask",
":",
"assert",
"add_gt",
"with",
"timed_operation",
"(",
"'Load Groundtruth Boxes for {}'",
".",
"format",
"(",
"self",
".",
"name",
")",
")"... | Args:
add_gt: whether to add ground truth bounding box annotations to the dicts
add_mask: whether to also add ground truth mask
Returns:
a list of dict, each has keys including:
'image_id', 'file_name',
and (if add_gt is True) 'boxes', 'class'... | [
"Args",
":",
"add_gt",
":",
"whether",
"to",
"add",
"ground",
"truth",
"bounding",
"box",
"annotations",
"to",
"the",
"dicts",
"add_mask",
":",
"whether",
"to",
"also",
"add",
"ground",
"truth",
"mask"
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/dataset.py#L77-L102 | train |
tensorpack/tensorpack | examples/FasterRCNN/dataset.py | COCODetection._use_absolute_file_name | def _use_absolute_file_name(self, img):
"""
Change relative filename to abosolute file name.
"""
img['file_name'] = os.path.join(
self._imgdir, img['file_name'])
assert os.path.isfile(img['file_name']), img['file_name'] | python | def _use_absolute_file_name(self, img):
"""
Change relative filename to abosolute file name.
"""
img['file_name'] = os.path.join(
self._imgdir, img['file_name'])
assert os.path.isfile(img['file_name']), img['file_name'] | [
"def",
"_use_absolute_file_name",
"(",
"self",
",",
"img",
")",
":",
"img",
"[",
"'file_name'",
"]",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"_imgdir",
",",
"img",
"[",
"'file_name'",
"]",
")",
"assert",
"os",
".",
"path",
".",
"isfile... | Change relative filename to abosolute file name. | [
"Change",
"relative",
"filename",
"to",
"abosolute",
"file",
"name",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/dataset.py#L104-L110 | train |
tensorpack/tensorpack | examples/FasterRCNN/dataset.py | COCODetection._add_detection_gt | def _add_detection_gt(self, img, add_mask):
"""
Add 'boxes', 'class', 'is_crowd' of this image to the dict, used by detection.
If add_mask is True, also add 'segmentation' in coco poly format.
"""
# ann_ids = self.coco.getAnnIds(imgIds=img['image_id'])
# objs = self.coco.... | python | def _add_detection_gt(self, img, add_mask):
"""
Add 'boxes', 'class', 'is_crowd' of this image to the dict, used by detection.
If add_mask is True, also add 'segmentation' in coco poly format.
"""
# ann_ids = self.coco.getAnnIds(imgIds=img['image_id'])
# objs = self.coco.... | [
"def",
"_add_detection_gt",
"(",
"self",
",",
"img",
",",
"add_mask",
")",
":",
"# ann_ids = self.coco.getAnnIds(imgIds=img['image_id'])",
"# objs = self.coco.loadAnns(ann_ids)",
"objs",
"=",
"self",
".",
"coco",
".",
"imgToAnns",
"[",
"img",
"[",
"'image_id'",
"]",
"... | Add 'boxes', 'class', 'is_crowd' of this image to the dict, used by detection.
If add_mask is True, also add 'segmentation' in coco poly format. | [
"Add",
"boxes",
"class",
"is_crowd",
"of",
"this",
"image",
"to",
"the",
"dict",
"used",
"by",
"detection",
".",
"If",
"add_mask",
"is",
"True",
"also",
"add",
"segmentation",
"in",
"coco",
"poly",
"format",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/dataset.py#L112-L170 | train |
tensorpack/tensorpack | examples/FasterRCNN/dataset.py | COCODetection.load_many | def load_many(basedir, names, add_gt=True, add_mask=False):
"""
Load and merges several instance files together.
Returns the same format as :meth:`COCODetection.load`.
"""
if not isinstance(names, (list, tuple)):
names = [names]
ret = []
for n in name... | python | def load_many(basedir, names, add_gt=True, add_mask=False):
"""
Load and merges several instance files together.
Returns the same format as :meth:`COCODetection.load`.
"""
if not isinstance(names, (list, tuple)):
names = [names]
ret = []
for n in name... | [
"def",
"load_many",
"(",
"basedir",
",",
"names",
",",
"add_gt",
"=",
"True",
",",
"add_mask",
"=",
"False",
")",
":",
"if",
"not",
"isinstance",
"(",
"names",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"names",
"=",
"[",
"names",
"]",
"ret",
... | Load and merges several instance files together.
Returns the same format as :meth:`COCODetection.load`. | [
"Load",
"and",
"merges",
"several",
"instance",
"files",
"together",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/dataset.py#L173-L185 | train |
tensorpack/tensorpack | examples/FasterRCNN/dataset.py | DetectionDataset.load_training_roidbs | def load_training_roidbs(self, names):
"""
Args:
names (list[str]): name of the training datasets, e.g. ['train2014', 'valminusminival2014']
Returns:
roidbs (list[dict]):
Produce "roidbs" as a list of dict, each dict corresponds to one image with k>=0 instances... | python | def load_training_roidbs(self, names):
"""
Args:
names (list[str]): name of the training datasets, e.g. ['train2014', 'valminusminival2014']
Returns:
roidbs (list[dict]):
Produce "roidbs" as a list of dict, each dict corresponds to one image with k>=0 instances... | [
"def",
"load_training_roidbs",
"(",
"self",
",",
"names",
")",
":",
"return",
"COCODetection",
".",
"load_many",
"(",
"cfg",
".",
"DATA",
".",
"BASEDIR",
",",
"names",
",",
"add_gt",
"=",
"True",
",",
"add_mask",
"=",
"cfg",
".",
"MODE_MASK",
")"
] | Args:
names (list[str]): name of the training datasets, e.g. ['train2014', 'valminusminival2014']
Returns:
roidbs (list[dict]):
Produce "roidbs" as a list of dict, each dict corresponds to one image with k>=0 instances.
and the following keys are expected for training:... | [
"Args",
":",
"names",
"(",
"list",
"[",
"str",
"]",
")",
":",
"name",
"of",
"the",
"training",
"datasets",
"e",
".",
"g",
".",
"[",
"train2014",
"valminusminival2014",
"]"
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/dataset.py#L203-L229 | train |
tensorpack/tensorpack | examples/FasterRCNN/dataset.py | DetectionDataset.load_inference_roidbs | def load_inference_roidbs(self, name):
"""
Args:
name (str): name of one inference dataset, e.g. 'minival2014'
Returns:
roidbs (list[dict]):
Each dict corresponds to one image to run inference on. The
following keys in the dict are expected:
... | python | def load_inference_roidbs(self, name):
"""
Args:
name (str): name of one inference dataset, e.g. 'minival2014'
Returns:
roidbs (list[dict]):
Each dict corresponds to one image to run inference on. The
following keys in the dict are expected:
... | [
"def",
"load_inference_roidbs",
"(",
"self",
",",
"name",
")",
":",
"return",
"COCODetection",
".",
"load_many",
"(",
"cfg",
".",
"DATA",
".",
"BASEDIR",
",",
"name",
",",
"add_gt",
"=",
"False",
")"
] | Args:
name (str): name of one inference dataset, e.g. 'minival2014'
Returns:
roidbs (list[dict]):
Each dict corresponds to one image to run inference on. The
following keys in the dict are expected:
file_name (str): full path to the image
... | [
"Args",
":",
"name",
"(",
"str",
")",
":",
"name",
"of",
"one",
"inference",
"dataset",
"e",
".",
"g",
".",
"minival2014"
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/dataset.py#L231-L245 | train |
tensorpack/tensorpack | examples/FasterRCNN/dataset.py | DetectionDataset.eval_or_save_inference_results | def eval_or_save_inference_results(self, results, dataset, output=None):
"""
Args:
results (list[dict]): the inference results as dicts.
Each dict corresponds to one __instance__. It contains the following keys:
image_id (str): the id that matches `load_infer... | python | def eval_or_save_inference_results(self, results, dataset, output=None):
"""
Args:
results (list[dict]): the inference results as dicts.
Each dict corresponds to one __instance__. It contains the following keys:
image_id (str): the id that matches `load_infer... | [
"def",
"eval_or_save_inference_results",
"(",
"self",
",",
"results",
",",
"dataset",
",",
"output",
"=",
"None",
")",
":",
"continuous_id_to_COCO_id",
"=",
"{",
"v",
":",
"k",
"for",
"k",
",",
"v",
"in",
"COCODetection",
".",
"COCO_id_to_category_id",
".",
... | Args:
results (list[dict]): the inference results as dicts.
Each dict corresponds to one __instance__. It contains the following keys:
image_id (str): the id that matches `load_inference_roidbs`.
category_id (int): the category prediction, in range [1, #categ... | [
"Args",
":",
"results",
"(",
"list",
"[",
"dict",
"]",
")",
":",
"the",
"inference",
"results",
"as",
"dicts",
".",
"Each",
"dict",
"corresponds",
"to",
"one",
"__instance__",
".",
"It",
"contains",
"the",
"following",
"keys",
":"
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/dataset.py#L247-L282 | train |
tensorpack/tensorpack | tensorpack/utils/timer.py | timed_operation | def timed_operation(msg, log_start=False):
"""
Surround a context with a timer.
Args:
msg(str): the log to print.
log_start(bool): whether to print also at the beginning.
Example:
.. code-block:: python
with timed_operation('Good Stuff'):
time.sleep... | python | def timed_operation(msg, log_start=False):
"""
Surround a context with a timer.
Args:
msg(str): the log to print.
log_start(bool): whether to print also at the beginning.
Example:
.. code-block:: python
with timed_operation('Good Stuff'):
time.sleep... | [
"def",
"timed_operation",
"(",
"msg",
",",
"log_start",
"=",
"False",
")",
":",
"assert",
"len",
"(",
"msg",
")",
"if",
"log_start",
":",
"logger",
".",
"info",
"(",
"'Start {} ...'",
".",
"format",
"(",
"msg",
")",
")",
"start",
"=",
"timer",
"(",
"... | Surround a context with a timer.
Args:
msg(str): the log to print.
log_start(bool): whether to print also at the beginning.
Example:
.. code-block:: python
with timed_operation('Good Stuff'):
time.sleep(1)
Will print:
.. code-block:: pytho... | [
"Surround",
"a",
"context",
"with",
"a",
"timer",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/timer.py#L23-L50 | train |
tensorpack/tensorpack | tensorpack/utils/timer.py | total_timer | def total_timer(msg):
""" A context which add the time spent inside to TotalTimer. """
start = timer()
yield
t = timer() - start
_TOTAL_TIMER_DATA[msg].feed(t) | python | def total_timer(msg):
""" A context which add the time spent inside to TotalTimer. """
start = timer()
yield
t = timer() - start
_TOTAL_TIMER_DATA[msg].feed(t) | [
"def",
"total_timer",
"(",
"msg",
")",
":",
"start",
"=",
"timer",
"(",
")",
"yield",
"t",
"=",
"timer",
"(",
")",
"-",
"start",
"_TOTAL_TIMER_DATA",
"[",
"msg",
"]",
".",
"feed",
"(",
"t",
")"
] | A context which add the time spent inside to TotalTimer. | [
"A",
"context",
"which",
"add",
"the",
"time",
"spent",
"inside",
"to",
"TotalTimer",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/timer.py#L57-L62 | train |
tensorpack/tensorpack | tensorpack/utils/timer.py | print_total_timer | def print_total_timer():
"""
Print the content of the TotalTimer, if it's not empty. This function will automatically get
called when program exits.
"""
if len(_TOTAL_TIMER_DATA) == 0:
return
for k, v in six.iteritems(_TOTAL_TIMER_DATA):
logger.info("Total Time: {} -> {:.2f} sec,... | python | def print_total_timer():
"""
Print the content of the TotalTimer, if it's not empty. This function will automatically get
called when program exits.
"""
if len(_TOTAL_TIMER_DATA) == 0:
return
for k, v in six.iteritems(_TOTAL_TIMER_DATA):
logger.info("Total Time: {} -> {:.2f} sec,... | [
"def",
"print_total_timer",
"(",
")",
":",
"if",
"len",
"(",
"_TOTAL_TIMER_DATA",
")",
"==",
"0",
":",
"return",
"for",
"k",
",",
"v",
"in",
"six",
".",
"iteritems",
"(",
"_TOTAL_TIMER_DATA",
")",
":",
"logger",
".",
"info",
"(",
"\"Total Time: {} -> {:.2f... | Print the content of the TotalTimer, if it's not empty. This function will automatically get
called when program exits. | [
"Print",
"the",
"content",
"of",
"the",
"TotalTimer",
"if",
"it",
"s",
"not",
"empty",
".",
"This",
"function",
"will",
"automatically",
"get",
"called",
"when",
"program",
"exits",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/timer.py#L65-L74 | train |
tensorpack/tensorpack | tensorpack/dataflow/imgaug/base.py | AugmentorList.reset_state | def reset_state(self):
""" Will reset state of each augmentor """
super(AugmentorList, self).reset_state()
for a in self.augmentors:
a.reset_state() | python | def reset_state(self):
""" Will reset state of each augmentor """
super(AugmentorList, self).reset_state()
for a in self.augmentors:
a.reset_state() | [
"def",
"reset_state",
"(",
"self",
")",
":",
"super",
"(",
"AugmentorList",
",",
"self",
")",
".",
"reset_state",
"(",
")",
"for",
"a",
"in",
"self",
".",
"augmentors",
":",
"a",
".",
"reset_state",
"(",
")"
] | Will reset state of each augmentor | [
"Will",
"reset",
"state",
"of",
"each",
"augmentor"
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/dataflow/imgaug/base.py#L224-L228 | train |
tensorpack/tensorpack | tensorpack/utils/concurrency.py | ensure_proc_terminate | def ensure_proc_terminate(proc):
"""
Make sure processes terminate when main process exit.
Args:
proc (multiprocessing.Process or list)
"""
if isinstance(proc, list):
for p in proc:
ensure_proc_terminate(p)
return
def stop_proc_by_weak_ref(ref):
proc... | python | def ensure_proc_terminate(proc):
"""
Make sure processes terminate when main process exit.
Args:
proc (multiprocessing.Process or list)
"""
if isinstance(proc, list):
for p in proc:
ensure_proc_terminate(p)
return
def stop_proc_by_weak_ref(ref):
proc... | [
"def",
"ensure_proc_terminate",
"(",
"proc",
")",
":",
"if",
"isinstance",
"(",
"proc",
",",
"list",
")",
":",
"for",
"p",
"in",
"proc",
":",
"ensure_proc_terminate",
"(",
"p",
")",
"return",
"def",
"stop_proc_by_weak_ref",
"(",
"ref",
")",
":",
"proc",
... | Make sure processes terminate when main process exit.
Args:
proc (multiprocessing.Process or list) | [
"Make",
"sure",
"processes",
"terminate",
"when",
"main",
"process",
"exit",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/concurrency.py#L152-L174 | train |
tensorpack/tensorpack | tensorpack/utils/concurrency.py | enable_death_signal | def enable_death_signal(_warn=True):
"""
Set the "death signal" of the current process, so that
the current process will be cleaned with guarantee
in case the parent dies accidentally.
"""
if platform.system() != 'Linux':
return
try:
import prctl # pip install python-prctl... | python | def enable_death_signal(_warn=True):
"""
Set the "death signal" of the current process, so that
the current process will be cleaned with guarantee
in case the parent dies accidentally.
"""
if platform.system() != 'Linux':
return
try:
import prctl # pip install python-prctl... | [
"def",
"enable_death_signal",
"(",
"_warn",
"=",
"True",
")",
":",
"if",
"platform",
".",
"system",
"(",
")",
"!=",
"'Linux'",
":",
"return",
"try",
":",
"import",
"prctl",
"# pip install python-prctl",
"except",
"ImportError",
":",
"if",
"_warn",
":",
"log_... | Set the "death signal" of the current process, so that
the current process will be cleaned with guarantee
in case the parent dies accidentally. | [
"Set",
"the",
"death",
"signal",
"of",
"the",
"current",
"process",
"so",
"that",
"the",
"current",
"process",
"will",
"be",
"cleaned",
"with",
"guarantee",
"in",
"case",
"the",
"parent",
"dies",
"accidentally",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/concurrency.py#L177-L196 | train |
tensorpack/tensorpack | tensorpack/utils/concurrency.py | mask_sigint | def mask_sigint():
"""
Returns:
If called in main thread, returns a context where ``SIGINT`` is ignored, and yield True.
Otherwise yield False.
"""
if is_main_thread():
sigint_handler = signal.signal(signal.SIGINT, signal.SIG_IGN)
yield True
signal.signal(signal.S... | python | def mask_sigint():
"""
Returns:
If called in main thread, returns a context where ``SIGINT`` is ignored, and yield True.
Otherwise yield False.
"""
if is_main_thread():
sigint_handler = signal.signal(signal.SIGINT, signal.SIG_IGN)
yield True
signal.signal(signal.S... | [
"def",
"mask_sigint",
"(",
")",
":",
"if",
"is_main_thread",
"(",
")",
":",
"sigint_handler",
"=",
"signal",
".",
"signal",
"(",
"signal",
".",
"SIGINT",
",",
"signal",
".",
"SIG_IGN",
")",
"yield",
"True",
"signal",
".",
"signal",
"(",
"signal",
".",
... | Returns:
If called in main thread, returns a context where ``SIGINT`` is ignored, and yield True.
Otherwise yield False. | [
"Returns",
":",
"If",
"called",
"in",
"main",
"thread",
"returns",
"a",
"context",
"where",
"SIGINT",
"is",
"ignored",
"and",
"yield",
"True",
".",
"Otherwise",
"yield",
"False",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/concurrency.py#L208-L219 | train |
tensorpack/tensorpack | tensorpack/utils/concurrency.py | start_proc_mask_signal | def start_proc_mask_signal(proc):
"""
Start process(es) with SIGINT ignored.
Args:
proc: (mp.Process or list)
Note:
The signal mask is only applied when called from main thread.
"""
if not isinstance(proc, list):
proc = [proc]
with mask_sigint():
for p in p... | python | def start_proc_mask_signal(proc):
"""
Start process(es) with SIGINT ignored.
Args:
proc: (mp.Process or list)
Note:
The signal mask is only applied when called from main thread.
"""
if not isinstance(proc, list):
proc = [proc]
with mask_sigint():
for p in p... | [
"def",
"start_proc_mask_signal",
"(",
"proc",
")",
":",
"if",
"not",
"isinstance",
"(",
"proc",
",",
"list",
")",
":",
"proc",
"=",
"[",
"proc",
"]",
"with",
"mask_sigint",
"(",
")",
":",
"for",
"p",
"in",
"proc",
":",
"if",
"isinstance",
"(",
"p",
... | Start process(es) with SIGINT ignored.
Args:
proc: (mp.Process or list)
Note:
The signal mask is only applied when called from main thread. | [
"Start",
"process",
"(",
"es",
")",
"with",
"SIGINT",
"ignored",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/concurrency.py#L222-L244 | train |
tensorpack/tensorpack | tensorpack/utils/concurrency.py | subproc_call | def subproc_call(cmd, timeout=None):
"""
Execute a command with timeout, and return STDOUT and STDERR
Args:
cmd(str): the command to execute.
timeout(float): timeout in seconds.
Returns:
output(bytes), retcode(int). If timeout, retcode is -1.
"""
try:
output = s... | python | def subproc_call(cmd, timeout=None):
"""
Execute a command with timeout, and return STDOUT and STDERR
Args:
cmd(str): the command to execute.
timeout(float): timeout in seconds.
Returns:
output(bytes), retcode(int). If timeout, retcode is -1.
"""
try:
output = s... | [
"def",
"subproc_call",
"(",
"cmd",
",",
"timeout",
"=",
"None",
")",
":",
"try",
":",
"output",
"=",
"subprocess",
".",
"check_output",
"(",
"cmd",
",",
"stderr",
"=",
"subprocess",
".",
"STDOUT",
",",
"shell",
"=",
"True",
",",
"timeout",
"=",
"timeou... | Execute a command with timeout, and return STDOUT and STDERR
Args:
cmd(str): the command to execute.
timeout(float): timeout in seconds.
Returns:
output(bytes), retcode(int). If timeout, retcode is -1. | [
"Execute",
"a",
"command",
"with",
"timeout",
"and",
"return",
"STDOUT",
"and",
"STDERR"
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/concurrency.py#L247-L273 | train |
tensorpack/tensorpack | tensorpack/utils/concurrency.py | StoppableThread.queue_put_stoppable | def queue_put_stoppable(self, q, obj):
""" Put obj to queue, but will give up when the thread is stopped"""
while not self.stopped():
try:
q.put(obj, timeout=5)
break
except queue.Full:
pass | python | def queue_put_stoppable(self, q, obj):
""" Put obj to queue, but will give up when the thread is stopped"""
while not self.stopped():
try:
q.put(obj, timeout=5)
break
except queue.Full:
pass | [
"def",
"queue_put_stoppable",
"(",
"self",
",",
"q",
",",
"obj",
")",
":",
"while",
"not",
"self",
".",
"stopped",
"(",
")",
":",
"try",
":",
"q",
".",
"put",
"(",
"obj",
",",
"timeout",
"=",
"5",
")",
"break",
"except",
"queue",
".",
"Full",
":"... | Put obj to queue, but will give up when the thread is stopped | [
"Put",
"obj",
"to",
"queue",
"but",
"will",
"give",
"up",
"when",
"the",
"thread",
"is",
"stopped"
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/concurrency.py#L59-L66 | train |
tensorpack/tensorpack | tensorpack/utils/concurrency.py | StoppableThread.queue_get_stoppable | def queue_get_stoppable(self, q):
""" Take obj from queue, but will give up when the thread is stopped"""
while not self.stopped():
try:
return q.get(timeout=5)
except queue.Empty:
pass | python | def queue_get_stoppable(self, q):
""" Take obj from queue, but will give up when the thread is stopped"""
while not self.stopped():
try:
return q.get(timeout=5)
except queue.Empty:
pass | [
"def",
"queue_get_stoppable",
"(",
"self",
",",
"q",
")",
":",
"while",
"not",
"self",
".",
"stopped",
"(",
")",
":",
"try",
":",
"return",
"q",
".",
"get",
"(",
"timeout",
"=",
"5",
")",
"except",
"queue",
".",
"Empty",
":",
"pass"
] | Take obj from queue, but will give up when the thread is stopped | [
"Take",
"obj",
"from",
"queue",
"but",
"will",
"give",
"up",
"when",
"the",
"thread",
"is",
"stopped"
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/concurrency.py#L68-L74 | train |
tensorpack/tensorpack | tensorpack/utils/concurrency.py | OrderedContainer.put | def put(self, rank, val):
"""
Args:
rank(int): rank of th element. All elements must have different ranks.
val: an object
"""
idx = bisect.bisect(self.ranks, rank)
self.ranks.insert(idx, rank)
self.data.insert(idx, val) | python | def put(self, rank, val):
"""
Args:
rank(int): rank of th element. All elements must have different ranks.
val: an object
"""
idx = bisect.bisect(self.ranks, rank)
self.ranks.insert(idx, rank)
self.data.insert(idx, val) | [
"def",
"put",
"(",
"self",
",",
"rank",
",",
"val",
")",
":",
"idx",
"=",
"bisect",
".",
"bisect",
"(",
"self",
".",
"ranks",
",",
"rank",
")",
"self",
".",
"ranks",
".",
"insert",
"(",
"idx",
",",
"rank",
")",
"self",
".",
"data",
".",
"insert... | Args:
rank(int): rank of th element. All elements must have different ranks.
val: an object | [
"Args",
":",
"rank",
"(",
"int",
")",
":",
"rank",
"of",
"th",
"element",
".",
"All",
"elements",
"must",
"have",
"different",
"ranks",
".",
"val",
":",
"an",
"object"
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/concurrency.py#L294-L302 | train |
tensorpack/tensorpack | examples/basics/mnist-visualizations.py | visualize_conv_weights | def visualize_conv_weights(filters, name):
"""Visualize use weights in convolution filters.
Args:
filters: tensor containing the weights [H,W,Cin,Cout]
name: label for tensorboard
Returns:
image of all weight
"""
with tf.name_scope('visualize_w_' + name):
filters = ... | python | def visualize_conv_weights(filters, name):
"""Visualize use weights in convolution filters.
Args:
filters: tensor containing the weights [H,W,Cin,Cout]
name: label for tensorboard
Returns:
image of all weight
"""
with tf.name_scope('visualize_w_' + name):
filters = ... | [
"def",
"visualize_conv_weights",
"(",
"filters",
",",
"name",
")",
":",
"with",
"tf",
".",
"name_scope",
"(",
"'visualize_w_'",
"+",
"name",
")",
":",
"filters",
"=",
"tf",
".",
"transpose",
"(",
"filters",
",",
"(",
"3",
",",
"2",
",",
"0",
",",
"1"... | Visualize use weights in convolution filters.
Args:
filters: tensor containing the weights [H,W,Cin,Cout]
name: label for tensorboard
Returns:
image of all weight | [
"Visualize",
"use",
"weights",
"in",
"convolution",
"filters",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/basics/mnist-visualizations.py#L17-L36 | train |
tensorpack/tensorpack | examples/basics/mnist-visualizations.py | visualize_conv_activations | def visualize_conv_activations(activation, name):
"""Visualize activations for convolution layers.
Remarks:
This tries to place all activations into a square.
Args:
activation: tensor with the activation [B,H,W,C]
name: label for tensorboard
Returns:
image of almost al... | python | def visualize_conv_activations(activation, name):
"""Visualize activations for convolution layers.
Remarks:
This tries to place all activations into a square.
Args:
activation: tensor with the activation [B,H,W,C]
name: label for tensorboard
Returns:
image of almost al... | [
"def",
"visualize_conv_activations",
"(",
"activation",
",",
"name",
")",
":",
"import",
"math",
"with",
"tf",
".",
"name_scope",
"(",
"'visualize_act_'",
"+",
"name",
")",
":",
"_",
",",
"h",
",",
"w",
",",
"c",
"=",
"activation",
".",
"get_shape",
"(",... | Visualize activations for convolution layers.
Remarks:
This tries to place all activations into a square.
Args:
activation: tensor with the activation [B,H,W,C]
name: label for tensorboard
Returns:
image of almost all activations | [
"Visualize",
"activations",
"for",
"convolution",
"layers",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/basics/mnist-visualizations.py#L39-L64 | train |
tensorpack/tensorpack | examples/GAN/InfoGAN-mnist.py | shapeless_placeholder | def shapeless_placeholder(x, axis, name):
"""
Make the static shape of a tensor less specific.
If you want to feed to a tensor, the shape of the feed value must match
the tensor's static shape. This function creates a placeholder which
defaults to x if not fed, but has a less specific static shape ... | python | def shapeless_placeholder(x, axis, name):
"""
Make the static shape of a tensor less specific.
If you want to feed to a tensor, the shape of the feed value must match
the tensor's static shape. This function creates a placeholder which
defaults to x if not fed, but has a less specific static shape ... | [
"def",
"shapeless_placeholder",
"(",
"x",
",",
"axis",
",",
"name",
")",
":",
"shp",
"=",
"x",
".",
"get_shape",
"(",
")",
".",
"as_list",
"(",
")",
"if",
"not",
"isinstance",
"(",
"axis",
",",
"list",
")",
":",
"axis",
"=",
"[",
"axis",
"]",
"fo... | Make the static shape of a tensor less specific.
If you want to feed to a tensor, the shape of the feed value must match
the tensor's static shape. This function creates a placeholder which
defaults to x if not fed, but has a less specific static shape than x.
See also `tensorflow#5680 <https://github.... | [
"Make",
"the",
"static",
"shape",
"of",
"a",
"tensor",
"less",
"specific",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/GAN/InfoGAN-mnist.py#L40-L66 | train |
tensorpack/tensorpack | examples/GAN/InfoGAN-mnist.py | entropy_from_samples | def entropy_from_samples(samples, vec):
"""
Estimate H(x|s) ~= -E_{x \sim P(x|s)}[\log Q(x|s)], where x are samples, and Q is parameterized by vec.
"""
samples_cat = tf.argmax(samples[:, :NUM_CLASS], axis=1, output_type=tf.int32)
samples_uniform = samples[:, NUM_CLASS:]
cat, uniform = get_distri... | python | def entropy_from_samples(samples, vec):
"""
Estimate H(x|s) ~= -E_{x \sim P(x|s)}[\log Q(x|s)], where x are samples, and Q is parameterized by vec.
"""
samples_cat = tf.argmax(samples[:, :NUM_CLASS], axis=1, output_type=tf.int32)
samples_uniform = samples[:, NUM_CLASS:]
cat, uniform = get_distri... | [
"def",
"entropy_from_samples",
"(",
"samples",
",",
"vec",
")",
":",
"samples_cat",
"=",
"tf",
".",
"argmax",
"(",
"samples",
"[",
":",
",",
":",
"NUM_CLASS",
"]",
",",
"axis",
"=",
"1",
",",
"output_type",
"=",
"tf",
".",
"int32",
")",
"samples_unifor... | Estimate H(x|s) ~= -E_{x \sim P(x|s)}[\log Q(x|s)], where x are samples, and Q is parameterized by vec. | [
"Estimate",
"H",
"(",
"x|s",
")",
"~",
"=",
"-",
"E_",
"{",
"x",
"\\",
"sim",
"P",
"(",
"x|s",
")",
"}",
"[",
"\\",
"log",
"Q",
"(",
"x|s",
")",
"]",
"where",
"x",
"are",
"samples",
"and",
"Q",
"is",
"parameterized",
"by",
"vec",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/GAN/InfoGAN-mnist.py#L75-L90 | train |
tensorpack/tensorpack | examples/GAN/InfoGAN-mnist.py | sample_prior | def sample_prior(batch_size):
cat, _ = get_distributions(DIST_PRIOR_PARAM[:NUM_CLASS], DIST_PRIOR_PARAM[NUM_CLASS:])
sample_cat = tf.one_hot(cat.sample(batch_size), NUM_CLASS)
"""
OpenAI official code actually models the "uniform" latent code as
a Gaussian distribution, but obtain the samples from ... | python | def sample_prior(batch_size):
cat, _ = get_distributions(DIST_PRIOR_PARAM[:NUM_CLASS], DIST_PRIOR_PARAM[NUM_CLASS:])
sample_cat = tf.one_hot(cat.sample(batch_size), NUM_CLASS)
"""
OpenAI official code actually models the "uniform" latent code as
a Gaussian distribution, but obtain the samples from ... | [
"def",
"sample_prior",
"(",
"batch_size",
")",
":",
"cat",
",",
"_",
"=",
"get_distributions",
"(",
"DIST_PRIOR_PARAM",
"[",
":",
"NUM_CLASS",
"]",
",",
"DIST_PRIOR_PARAM",
"[",
"NUM_CLASS",
":",
"]",
")",
"sample_cat",
"=",
"tf",
".",
"one_hot",
"(",
"cat... | OpenAI official code actually models the "uniform" latent code as
a Gaussian distribution, but obtain the samples from a uniform distribution. | [
"OpenAI",
"official",
"code",
"actually",
"models",
"the",
"uniform",
"latent",
"code",
"as",
"a",
"Gaussian",
"distribution",
"but",
"obtain",
"the",
"samples",
"from",
"a",
"uniform",
"distribution",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/GAN/InfoGAN-mnist.py#L94-L104 | train |
tensorpack/tensorpack | examples/GAN/InfoGAN-mnist.py | Model.build_graph | def build_graph(self, real_sample):
real_sample = tf.expand_dims(real_sample, -1)
# sample the latent code:
zc = shapeless_placeholder(sample_prior(BATCH), 0, name='z_code')
z_noise = shapeless_placeholder(
tf.random_uniform([BATCH, NOISE_DIM], -1, 1), 0, name='z_noise')
... | python | def build_graph(self, real_sample):
real_sample = tf.expand_dims(real_sample, -1)
# sample the latent code:
zc = shapeless_placeholder(sample_prior(BATCH), 0, name='z_code')
z_noise = shapeless_placeholder(
tf.random_uniform([BATCH, NOISE_DIM], -1, 1), 0, name='z_noise')
... | [
"def",
"build_graph",
"(",
"self",
",",
"real_sample",
")",
":",
"real_sample",
"=",
"tf",
".",
"expand_dims",
"(",
"real_sample",
",",
"-",
"1",
")",
"# sample the latent code:",
"zc",
"=",
"shapeless_placeholder",
"(",
"sample_prior",
"(",
"BATCH",
")",
",",... | Mutual information between x (i.e. zc in this case) and some
information s (the generated samples in this case):
I(x;s) = H(x) - H(x|s)
= H(x) + E[\log P(x|s)]
The distribution from which zc is sampled, in this case, is set to a fixed prior already.
... | [
"Mutual",
"information",
"between",
"x",
"(",
"i",
".",
"e",
".",
"zc",
"in",
"this",
"case",
")",
"and",
"some",
"information",
"s",
"(",
"the",
"generated",
"samples",
"in",
"this",
"case",
")",
":"
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/GAN/InfoGAN-mnist.py#L141-L202 | train |
tensorpack/tensorpack | examples/DynamicFilterNetwork/steering-filter.py | DynamicConvFilter | def DynamicConvFilter(inputs, filters, out_channel,
kernel_shape,
stride=1,
padding='SAME'):
""" see "Dynamic Filter Networks" (NIPS 2016)
by Bert De Brabandere*, Xu Jia*, Tinne Tuytelaars and Luc Van Gool
Remarks:
This is the co... | python | def DynamicConvFilter(inputs, filters, out_channel,
kernel_shape,
stride=1,
padding='SAME'):
""" see "Dynamic Filter Networks" (NIPS 2016)
by Bert De Brabandere*, Xu Jia*, Tinne Tuytelaars and Luc Van Gool
Remarks:
This is the co... | [
"def",
"DynamicConvFilter",
"(",
"inputs",
",",
"filters",
",",
"out_channel",
",",
"kernel_shape",
",",
"stride",
"=",
"1",
",",
"padding",
"=",
"'SAME'",
")",
":",
"# tf.unstack only works with known batch_size :-(",
"batch_size",
",",
"h",
",",
"w",
",",
"in_... | see "Dynamic Filter Networks" (NIPS 2016)
by Bert De Brabandere*, Xu Jia*, Tinne Tuytelaars and Luc Van Gool
Remarks:
This is the convolution version of a dynamic filter.
Args:
inputs : unfiltered input [b, h, w, 1] only grayscale images.
filters : learned filters of [b, k, k, ... | [
"see",
"Dynamic",
"Filter",
"Networks",
"(",
"NIPS",
"2016",
")",
"by",
"Bert",
"De",
"Brabandere",
"*",
"Xu",
"Jia",
"*",
"Tinne",
"Tuytelaars",
"and",
"Luc",
"Van",
"Gool"
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/DynamicFilterNetwork/steering-filter.py#L24-L59 | train |
tensorpack/tensorpack | examples/DynamicFilterNetwork/steering-filter.py | Model._parameter_net | def _parameter_net(self, theta, kernel_shape=9):
"""Estimate filters for convolution layers
Args:
theta: angle of filter
kernel_shape: size of each filter
Returns:
learned filter as [B, k, k, 1]
"""
with argscope(FullyConnected, nl=tf.nn.leak... | python | def _parameter_net(self, theta, kernel_shape=9):
"""Estimate filters for convolution layers
Args:
theta: angle of filter
kernel_shape: size of each filter
Returns:
learned filter as [B, k, k, 1]
"""
with argscope(FullyConnected, nl=tf.nn.leak... | [
"def",
"_parameter_net",
"(",
"self",
",",
"theta",
",",
"kernel_shape",
"=",
"9",
")",
":",
"with",
"argscope",
"(",
"FullyConnected",
",",
"nl",
"=",
"tf",
".",
"nn",
".",
"leaky_relu",
")",
":",
"net",
"=",
"FullyConnected",
"(",
"'fc1'",
",",
"thet... | Estimate filters for convolution layers
Args:
theta: angle of filter
kernel_shape: size of each filter
Returns:
learned filter as [B, k, k, 1] | [
"Estimate",
"filters",
"for",
"convolution",
"layers"
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/DynamicFilterNetwork/steering-filter.py#L103-L120 | train |
tensorpack/tensorpack | examples/DynamicFilterNetwork/steering-filter.py | ThetaImages.filter_with_theta | def filter_with_theta(image, theta, sigma=1., filter_size=9):
"""Implements a steerable Gaussian filter.
This function can be used to evaluate the first
directional derivative of an image, using the
method outlined in
W. T. Freeman and E. H. Adelson, "The Design
... | python | def filter_with_theta(image, theta, sigma=1., filter_size=9):
"""Implements a steerable Gaussian filter.
This function can be used to evaluate the first
directional derivative of an image, using the
method outlined in
W. T. Freeman and E. H. Adelson, "The Design
... | [
"def",
"filter_with_theta",
"(",
"image",
",",
"theta",
",",
"sigma",
"=",
"1.",
",",
"filter_size",
"=",
"9",
")",
":",
"x",
"=",
"np",
".",
"arange",
"(",
"-",
"filter_size",
"//",
"2",
"+",
"1",
",",
"filter_size",
"//",
"2",
"+",
"1",
")",
"#... | Implements a steerable Gaussian filter.
This function can be used to evaluate the first
directional derivative of an image, using the
method outlined in
W. T. Freeman and E. H. Adelson, "The Design
and Use of Steerable Filters", IEEE PAMI, 1991.
It evaluates th... | [
"Implements",
"a",
"steerable",
"Gaussian",
"filter",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/DynamicFilterNetwork/steering-filter.py#L162-L204 | train |
tensorpack/tensorpack | examples/GAN/GAN.py | GANModelDesc.collect_variables | def collect_variables(self, g_scope='gen', d_scope='discrim'):
"""
Assign `self.g_vars` to the parameters under scope `g_scope`,
and same with `self.d_vars`.
"""
self.g_vars = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, g_scope)
assert self.g_vars
self.d_v... | python | def collect_variables(self, g_scope='gen', d_scope='discrim'):
"""
Assign `self.g_vars` to the parameters under scope `g_scope`,
and same with `self.d_vars`.
"""
self.g_vars = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, g_scope)
assert self.g_vars
self.d_v... | [
"def",
"collect_variables",
"(",
"self",
",",
"g_scope",
"=",
"'gen'",
",",
"d_scope",
"=",
"'discrim'",
")",
":",
"self",
".",
"g_vars",
"=",
"tf",
".",
"get_collection",
"(",
"tf",
".",
"GraphKeys",
".",
"TRAINABLE_VARIABLES",
",",
"g_scope",
")",
"asser... | Assign `self.g_vars` to the parameters under scope `g_scope`,
and same with `self.d_vars`. | [
"Assign",
"self",
".",
"g_vars",
"to",
"the",
"parameters",
"under",
"scope",
"g_scope",
"and",
"same",
"with",
"self",
".",
"d_vars",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/GAN/GAN.py#L17-L25 | train |
tensorpack/tensorpack | examples/GAN/GAN.py | GANModelDesc.build_losses | def build_losses(self, logits_real, logits_fake):
"""
Build standard GAN loss and set `self.g_loss` and `self.d_loss`.
D and G play two-player minimax game with value function V(G,D)
min_G max _D V(D, G) = IE_{x ~ p_data} [log D(x)] + IE_{z ~ p_fake} [log (1 - D(G(z)))]
Args... | python | def build_losses(self, logits_real, logits_fake):
"""
Build standard GAN loss and set `self.g_loss` and `self.d_loss`.
D and G play two-player minimax game with value function V(G,D)
min_G max _D V(D, G) = IE_{x ~ p_data} [log D(x)] + IE_{z ~ p_fake} [log (1 - D(G(z)))]
Args... | [
"def",
"build_losses",
"(",
"self",
",",
"logits_real",
",",
"logits_fake",
")",
":",
"with",
"tf",
".",
"name_scope",
"(",
"\"GAN_loss\"",
")",
":",
"score_real",
"=",
"tf",
".",
"sigmoid",
"(",
"logits_real",
")",
"score_fake",
"=",
"tf",
".",
"sigmoid",... | Build standard GAN loss and set `self.g_loss` and `self.d_loss`.
D and G play two-player minimax game with value function V(G,D)
min_G max _D V(D, G) = IE_{x ~ p_data} [log D(x)] + IE_{z ~ p_fake} [log (1 - D(G(z)))]
Args:
logits_real (tf.Tensor): discrim logits from real sample... | [
"Build",
"standard",
"GAN",
"loss",
"and",
"set",
"self",
".",
"g_loss",
"and",
"self",
".",
"d_loss",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/GAN/GAN.py#L27-L62 | train |
tensorpack/tensorpack | examples/GAN/GAN.py | GANTrainer._build_gan_trainer | def _build_gan_trainer(self, input, model):
"""
We need to set tower_func because it's a TowerTrainer,
and only TowerTrainer supports automatic graph creation for inference during training.
If we don't care about inference during training, using tower_func is
not needed. Just ca... | python | def _build_gan_trainer(self, input, model):
"""
We need to set tower_func because it's a TowerTrainer,
and only TowerTrainer supports automatic graph creation for inference during training.
If we don't care about inference during training, using tower_func is
not needed. Just ca... | [
"def",
"_build_gan_trainer",
"(",
"self",
",",
"input",
",",
"model",
")",
":",
"# Build the graph",
"self",
".",
"tower_func",
"=",
"TowerFuncWrapper",
"(",
"model",
".",
"build_graph",
",",
"model",
".",
"get_input_signature",
"(",
")",
")",
"with",
"TowerCo... | We need to set tower_func because it's a TowerTrainer,
and only TowerTrainer supports automatic graph creation for inference during training.
If we don't care about inference during training, using tower_func is
not needed. Just calling model.build_graph directly is OK. | [
"We",
"need",
"to",
"set",
"tower_func",
"because",
"it",
"s",
"a",
"TowerTrainer",
"and",
"only",
"TowerTrainer",
"supports",
"automatic",
"graph",
"creation",
"for",
"inference",
"during",
"training",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/GAN/GAN.py#L99-L119 | train |
tensorpack/tensorpack | tensorpack/models/tflayer.py | convert_to_tflayer_args | def convert_to_tflayer_args(args_names, name_mapping):
"""
After applying this decorator:
1. data_format becomes tf.layers style
2. nl becomes activation
3. initializers are renamed
4. positional args are transformed to corresponding kwargs, according to args_names
5. kwargs are mapped to tf... | python | def convert_to_tflayer_args(args_names, name_mapping):
"""
After applying this decorator:
1. data_format becomes tf.layers style
2. nl becomes activation
3. initializers are renamed
4. positional args are transformed to corresponding kwargs, according to args_names
5. kwargs are mapped to tf... | [
"def",
"convert_to_tflayer_args",
"(",
"args_names",
",",
"name_mapping",
")",
":",
"def",
"decorator",
"(",
"func",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"func",
")",
"def",
"decorated_func",
"(",
"inputs",
",",
"*",
"args",
",",
"*",
"*",
"kwa... | After applying this decorator:
1. data_format becomes tf.layers style
2. nl becomes activation
3. initializers are renamed
4. positional args are transformed to corresponding kwargs, according to args_names
5. kwargs are mapped to tf.layers names if needed, by name_mapping | [
"After",
"applying",
"this",
"decorator",
":",
"1",
".",
"data_format",
"becomes",
"tf",
".",
"layers",
"style",
"2",
".",
"nl",
"becomes",
"activation",
"3",
".",
"initializers",
"are",
"renamed",
"4",
".",
"positional",
"args",
"are",
"transformed",
"to",
... | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/models/tflayer.py#L33-L70 | train |
tensorpack/tensorpack | tensorpack/models/tflayer.py | rename_get_variable | def rename_get_variable(mapping):
"""
Args:
mapping(dict): an old -> new mapping for variable basename. e.g. {'kernel': 'W'}
Returns:
A context where the variables are renamed.
"""
def custom_getter(getter, name, *args, **kwargs):
splits = name.split('/')
basename = ... | python | def rename_get_variable(mapping):
"""
Args:
mapping(dict): an old -> new mapping for variable basename. e.g. {'kernel': 'W'}
Returns:
A context where the variables are renamed.
"""
def custom_getter(getter, name, *args, **kwargs):
splits = name.split('/')
basename = ... | [
"def",
"rename_get_variable",
"(",
"mapping",
")",
":",
"def",
"custom_getter",
"(",
"getter",
",",
"name",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"splits",
"=",
"name",
".",
"split",
"(",
"'/'",
")",
"basename",
"=",
"splits",
"[",
"-"... | Args:
mapping(dict): an old -> new mapping for variable basename. e.g. {'kernel': 'W'}
Returns:
A context where the variables are renamed. | [
"Args",
":",
"mapping",
"(",
"dict",
")",
":",
"an",
"old",
"-",
">",
"new",
"mapping",
"for",
"variable",
"basename",
".",
"e",
".",
"g",
".",
"{",
"kernel",
":",
"W",
"}"
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/models/tflayer.py#L73-L89 | train |
tensorpack/tensorpack | tensorpack/models/regularize.py | regularize_cost | def regularize_cost(regex, func, name='regularize_cost'):
"""
Apply a regularizer on trainable variables matching the regex, and print
the matched variables (only print once in multi-tower training).
In replicated mode, it will only regularize variables within the current tower.
If called under a T... | python | def regularize_cost(regex, func, name='regularize_cost'):
"""
Apply a regularizer on trainable variables matching the regex, and print
the matched variables (only print once in multi-tower training).
In replicated mode, it will only regularize variables within the current tower.
If called under a T... | [
"def",
"regularize_cost",
"(",
"regex",
",",
"func",
",",
"name",
"=",
"'regularize_cost'",
")",
":",
"assert",
"len",
"(",
"regex",
")",
"ctx",
"=",
"get_current_tower_context",
"(",
")",
"if",
"not",
"ctx",
".",
"is_training",
":",
"# Currently cannot build ... | Apply a regularizer on trainable variables matching the regex, and print
the matched variables (only print once in multi-tower training).
In replicated mode, it will only regularize variables within the current tower.
If called under a TowerContext with `is_training==False`, this function returns a zero co... | [
"Apply",
"a",
"regularizer",
"on",
"trainable",
"variables",
"matching",
"the",
"regex",
"and",
"print",
"the",
"matched",
"variables",
"(",
"only",
"print",
"once",
"in",
"multi",
"-",
"tower",
"training",
")",
".",
"In",
"replicated",
"mode",
"it",
"will",... | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/models/regularize.py#L33-L100 | train |
tensorpack/tensorpack | tensorpack/models/regularize.py | regularize_cost_from_collection | def regularize_cost_from_collection(name='regularize_cost'):
"""
Get the cost from the regularizers in ``tf.GraphKeys.REGULARIZATION_LOSSES``.
If in replicated mode, will only regularize variables created within the current tower.
Args:
name (str): the name of the returned tensor
Returns:
... | python | def regularize_cost_from_collection(name='regularize_cost'):
"""
Get the cost from the regularizers in ``tf.GraphKeys.REGULARIZATION_LOSSES``.
If in replicated mode, will only regularize variables created within the current tower.
Args:
name (str): the name of the returned tensor
Returns:
... | [
"def",
"regularize_cost_from_collection",
"(",
"name",
"=",
"'regularize_cost'",
")",
":",
"ctx",
"=",
"get_current_tower_context",
"(",
")",
"if",
"not",
"ctx",
".",
"is_training",
":",
"# TODO Currently cannot build the wd_cost correctly at inference,",
"# because ths vs_na... | Get the cost from the regularizers in ``tf.GraphKeys.REGULARIZATION_LOSSES``.
If in replicated mode, will only regularize variables created within the current tower.
Args:
name (str): the name of the returned tensor
Returns:
tf.Tensor: a scalar, the total regularization cost. | [
"Get",
"the",
"cost",
"from",
"the",
"regularizers",
"in",
"tf",
".",
"GraphKeys",
".",
"REGULARIZATION_LOSSES",
".",
"If",
"in",
"replicated",
"mode",
"will",
"only",
"regularize",
"variables",
"created",
"within",
"the",
"current",
"tower",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/models/regularize.py#L103-L141 | train |
tensorpack/tensorpack | tensorpack/models/regularize.py | Dropout | def Dropout(x, *args, **kwargs):
"""
Same as `tf.layers.dropout`.
However, for historical reasons, the first positional argument is
interpreted as keep_prob rather than drop_prob.
Explicitly use `rate=` keyword arguments to ensure things are consistent.
"""
if 'is_training' in kwargs:
... | python | def Dropout(x, *args, **kwargs):
"""
Same as `tf.layers.dropout`.
However, for historical reasons, the first positional argument is
interpreted as keep_prob rather than drop_prob.
Explicitly use `rate=` keyword arguments to ensure things are consistent.
"""
if 'is_training' in kwargs:
... | [
"def",
"Dropout",
"(",
"x",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"'is_training'",
"in",
"kwargs",
":",
"kwargs",
"[",
"'training'",
"]",
"=",
"kwargs",
".",
"pop",
"(",
"'is_training'",
")",
"if",
"len",
"(",
"args",
")",
">",... | Same as `tf.layers.dropout`.
However, for historical reasons, the first positional argument is
interpreted as keep_prob rather than drop_prob.
Explicitly use `rate=` keyword arguments to ensure things are consistent. | [
"Same",
"as",
"tf",
".",
"layers",
".",
"dropout",
".",
"However",
"for",
"historical",
"reasons",
"the",
"first",
"positional",
"argument",
"is",
"interpreted",
"as",
"keep_prob",
"rather",
"than",
"drop_prob",
".",
"Explicitly",
"use",
"rate",
"=",
"keyword"... | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/models/regularize.py#L145-L175 | train |
tensorpack/tensorpack | tensorpack/dataflow/imgaug/paste.py | BackgroundFiller.fill | def fill(self, background_shape, img):
"""
Return a proper background image of background_shape, given img.
Args:
background_shape (tuple): a shape (h, w)
img: an image
Returns:
a background image
"""
background_shape = tuple(backgroun... | python | def fill(self, background_shape, img):
"""
Return a proper background image of background_shape, given img.
Args:
background_shape (tuple): a shape (h, w)
img: an image
Returns:
a background image
"""
background_shape = tuple(backgroun... | [
"def",
"fill",
"(",
"self",
",",
"background_shape",
",",
"img",
")",
":",
"background_shape",
"=",
"tuple",
"(",
"background_shape",
")",
"return",
"self",
".",
"_fill",
"(",
"background_shape",
",",
"img",
")"
] | Return a proper background image of background_shape, given img.
Args:
background_shape (tuple): a shape (h, w)
img: an image
Returns:
a background image | [
"Return",
"a",
"proper",
"background",
"image",
"of",
"background_shape",
"given",
"img",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/dataflow/imgaug/paste.py#L17-L28 | train |
tensorpack/tensorpack | tensorpack/models/linearwrap.py | LinearWrap.apply | def apply(self, func, *args, **kwargs):
"""
Apply a function on the wrapped tensor.
Returns:
LinearWrap: ``LinearWrap(func(self.tensor(), *args, **kwargs))``.
"""
ret = func(self._t, *args, **kwargs)
return LinearWrap(ret) | python | def apply(self, func, *args, **kwargs):
"""
Apply a function on the wrapped tensor.
Returns:
LinearWrap: ``LinearWrap(func(self.tensor(), *args, **kwargs))``.
"""
ret = func(self._t, *args, **kwargs)
return LinearWrap(ret) | [
"def",
"apply",
"(",
"self",
",",
"func",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"ret",
"=",
"func",
"(",
"self",
".",
"_t",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"LinearWrap",
"(",
"ret",
")"
] | Apply a function on the wrapped tensor.
Returns:
LinearWrap: ``LinearWrap(func(self.tensor(), *args, **kwargs))``. | [
"Apply",
"a",
"function",
"on",
"the",
"wrapped",
"tensor",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/models/linearwrap.py#L68-L76 | train |
tensorpack/tensorpack | tensorpack/models/linearwrap.py | LinearWrap.apply2 | def apply2(self, func, *args, **kwargs):
"""
Apply a function on the wrapped tensor. The tensor
will be the second argument of func.
This is because many symbolic functions
(such as tensorpack's layers) takes 'scope' as the first argument.
Returns:
LinearWra... | python | def apply2(self, func, *args, **kwargs):
"""
Apply a function on the wrapped tensor. The tensor
will be the second argument of func.
This is because many symbolic functions
(such as tensorpack's layers) takes 'scope' as the first argument.
Returns:
LinearWra... | [
"def",
"apply2",
"(",
"self",
",",
"func",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"ret",
"=",
"func",
"(",
"args",
"[",
"0",
"]",
",",
"self",
".",
"_t",
",",
"*",
"(",
"args",
"[",
"1",
":",
"]",
")",
",",
"*",
"*",
"kwargs... | Apply a function on the wrapped tensor. The tensor
will be the second argument of func.
This is because many symbolic functions
(such as tensorpack's layers) takes 'scope' as the first argument.
Returns:
LinearWrap: ``LinearWrap(func(args[0], self.tensor(), *args[1:], **kwa... | [
"Apply",
"a",
"function",
"on",
"the",
"wrapped",
"tensor",
".",
"The",
"tensor",
"will",
"be",
"the",
"second",
"argument",
"of",
"func",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/models/linearwrap.py#L78-L90 | train |
tensorpack/tensorpack | examples/Saliency/saliency-maps.py | guided_relu | def guided_relu():
"""
Returns:
A context where the gradient of :meth:`tf.nn.relu` is replaced by
guided back-propagation, as described in the paper:
`Striving for Simplicity: The All Convolutional Net
<https://arxiv.org/abs/1412.6806>`_
"""
from tensorflow.python.ops imp... | python | def guided_relu():
"""
Returns:
A context where the gradient of :meth:`tf.nn.relu` is replaced by
guided back-propagation, as described in the paper:
`Striving for Simplicity: The All Convolutional Net
<https://arxiv.org/abs/1412.6806>`_
"""
from tensorflow.python.ops imp... | [
"def",
"guided_relu",
"(",
")",
":",
"from",
"tensorflow",
".",
"python",
".",
"ops",
"import",
"gen_nn_ops",
"# noqa",
"@",
"tf",
".",
"RegisterGradient",
"(",
"\"GuidedReLU\"",
")",
"def",
"GuidedReluGrad",
"(",
"op",
",",
"grad",
")",
":",
"return",
"tf... | Returns:
A context where the gradient of :meth:`tf.nn.relu` is replaced by
guided back-propagation, as described in the paper:
`Striving for Simplicity: The All Convolutional Net
<https://arxiv.org/abs/1412.6806>`_ | [
"Returns",
":",
"A",
"context",
"where",
"the",
"gradient",
"of",
":",
"meth",
":",
"tf",
".",
"nn",
".",
"relu",
"is",
"replaced",
"by",
"guided",
"back",
"-",
"propagation",
"as",
"described",
"in",
"the",
"paper",
":",
"Striving",
"for",
"Simplicity",... | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/Saliency/saliency-maps.py#L19-L37 | train |
tensorpack/tensorpack | examples/Saliency/saliency-maps.py | saliency_map | def saliency_map(output, input, name="saliency_map"):
"""
Produce a saliency map as described in the paper:
`Deep Inside Convolutional Networks: Visualising Image Classification Models and Saliency Maps
<https://arxiv.org/abs/1312.6034>`_.
The saliency map is the gradient of the max element in outpu... | python | def saliency_map(output, input, name="saliency_map"):
"""
Produce a saliency map as described in the paper:
`Deep Inside Convolutional Networks: Visualising Image Classification Models and Saliency Maps
<https://arxiv.org/abs/1312.6034>`_.
The saliency map is the gradient of the max element in outpu... | [
"def",
"saliency_map",
"(",
"output",
",",
"input",
",",
"name",
"=",
"\"saliency_map\"",
")",
":",
"max_outp",
"=",
"tf",
".",
"reduce_max",
"(",
"output",
",",
"1",
")",
"saliency_op",
"=",
"tf",
".",
"gradients",
"(",
"max_outp",
",",
"input",
")",
... | Produce a saliency map as described in the paper:
`Deep Inside Convolutional Networks: Visualising Image Classification Models and Saliency Maps
<https://arxiv.org/abs/1312.6034>`_.
The saliency map is the gradient of the max element in output w.r.t input.
Returns:
tf.Tensor: the saliency map. ... | [
"Produce",
"a",
"saliency",
"map",
"as",
"described",
"in",
"the",
"paper",
":",
"Deep",
"Inside",
"Convolutional",
"Networks",
":",
"Visualising",
"Image",
"Classification",
"Models",
"and",
"Saliency",
"Maps",
"<https",
":",
"//",
"arxiv",
".",
"org",
"/",
... | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/Saliency/saliency-maps.py#L40-L52 | train |
tensorpack/tensorpack | tensorpack/models/conv2d.py | Conv2D | def Conv2D(
inputs,
filters,
kernel_size,
strides=(1, 1),
padding='same',
data_format='channels_last',
dilation_rate=(1, 1),
activation=None,
use_bias=True,
kernel_initializer=None,
bias_initializer=tf.zeros_initializer(),
k... | python | def Conv2D(
inputs,
filters,
kernel_size,
strides=(1, 1),
padding='same',
data_format='channels_last',
dilation_rate=(1, 1),
activation=None,
use_bias=True,
kernel_initializer=None,
bias_initializer=tf.zeros_initializer(),
k... | [
"def",
"Conv2D",
"(",
"inputs",
",",
"filters",
",",
"kernel_size",
",",
"strides",
"=",
"(",
"1",
",",
"1",
")",
",",
"padding",
"=",
"'same'",
",",
"data_format",
"=",
"'channels_last'",
",",
"dilation_rate",
"=",
"(",
"1",
",",
"1",
")",
",",
"act... | A wrapper around `tf.layers.Conv2D`.
Some differences to maintain backward-compatibility:
1. Default kernel initializer is variance_scaling_initializer(2.0).
2. Default padding is 'same'.
3. Support 'split' argument to do group conv. Note that this is not efficient.
Variable Names:
* ``W``: w... | [
"A",
"wrapper",
"around",
"tf",
".",
"layers",
".",
"Conv2D",
".",
"Some",
"differences",
"to",
"maintain",
"backward",
"-",
"compatibility",
":"
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/models/conv2d.py#L23-L140 | train |
tensorpack/tensorpack | tensorpack/models/conv2d.py | Conv2DTranspose | def Conv2DTranspose(
inputs,
filters,
kernel_size,
strides=(1, 1),
padding='same',
data_format='channels_last',
activation=None,
use_bias=True,
kernel_initializer=None,
bias_initializer=tf.zeros_initializer(),
kernel_regularizer=Non... | python | def Conv2DTranspose(
inputs,
filters,
kernel_size,
strides=(1, 1),
padding='same',
data_format='channels_last',
activation=None,
use_bias=True,
kernel_initializer=None,
bias_initializer=tf.zeros_initializer(),
kernel_regularizer=Non... | [
"def",
"Conv2DTranspose",
"(",
"inputs",
",",
"filters",
",",
"kernel_size",
",",
"strides",
"=",
"(",
"1",
",",
"1",
")",
",",
"padding",
"=",
"'same'",
",",
"data_format",
"=",
"'channels_last'",
",",
"activation",
"=",
"None",
",",
"use_bias",
"=",
"T... | A wrapper around `tf.layers.Conv2DTranspose`.
Some differences to maintain backward-compatibility:
1. Default kernel initializer is variance_scaling_initializer(2.0).
2. Default padding is 'same'
Variable Names:
* ``W``: weights
* ``b``: bias | [
"A",
"wrapper",
"around",
"tf",
".",
"layers",
".",
"Conv2DTranspose",
".",
"Some",
"differences",
"to",
"maintain",
"backward",
"-",
"compatibility",
":"
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/models/conv2d.py#L151-L252 | train |
tensorpack/tensorpack | tensorpack/callbacks/param.py | GraphVarParam.setup_graph | def setup_graph(self):
""" Will setup the assign operator for that variable. """
all_vars = tfv1.global_variables() + tfv1.local_variables()
for v in all_vars:
if v.name == self.var_name:
self.var = v
break
else:
raise ValueError("{... | python | def setup_graph(self):
""" Will setup the assign operator for that variable. """
all_vars = tfv1.global_variables() + tfv1.local_variables()
for v in all_vars:
if v.name == self.var_name:
self.var = v
break
else:
raise ValueError("{... | [
"def",
"setup_graph",
"(",
"self",
")",
":",
"all_vars",
"=",
"tfv1",
".",
"global_variables",
"(",
")",
"+",
"tfv1",
".",
"local_variables",
"(",
")",
"for",
"v",
"in",
"all_vars",
":",
"if",
"v",
".",
"name",
"==",
"self",
".",
"var_name",
":",
"se... | Will setup the assign operator for that variable. | [
"Will",
"setup",
"the",
"assign",
"operator",
"for",
"that",
"variable",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/callbacks/param.py#L68-L76 | train |
tensorpack/tensorpack | tensorpack/callbacks/param.py | HyperParamSetter.get_value_to_set | def get_value_to_set(self):
"""
Returns:
The value to assign to the variable.
Note:
Subclasses will implement the abstract method
:meth:`_get_value_to_set`, which should return a new value to
set, or return None to do nothing.
"""
... | python | def get_value_to_set(self):
"""
Returns:
The value to assign to the variable.
Note:
Subclasses will implement the abstract method
:meth:`_get_value_to_set`, which should return a new value to
set, or return None to do nothing.
"""
... | [
"def",
"get_value_to_set",
"(",
"self",
")",
":",
"ret",
"=",
"self",
".",
"_get_value_to_set",
"(",
")",
"if",
"ret",
"is",
"not",
"None",
"and",
"ret",
"!=",
"self",
".",
"_last_value",
":",
"if",
"self",
".",
"epoch_num",
"!=",
"self",
".",
"_last_e... | Returns:
The value to assign to the variable.
Note:
Subclasses will implement the abstract method
:meth:`_get_value_to_set`, which should return a new value to
set, or return None to do nothing. | [
"Returns",
":",
"The",
"value",
"to",
"assign",
"to",
"the",
"variable",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/callbacks/param.py#L143-L164 | train |
tensorpack/tensorpack | tensorpack/callbacks/param.py | ScheduledHyperParamSetter._get_value_to_set_at_point | def _get_value_to_set_at_point(self, point):
"""
Using schedule, compute the value to be set at a given point.
"""
laste, lastv = None, None
for e, v in self.schedule:
if e == point:
return v # meet the exact boundary, return directly
if... | python | def _get_value_to_set_at_point(self, point):
"""
Using schedule, compute the value to be set at a given point.
"""
laste, lastv = None, None
for e, v in self.schedule:
if e == point:
return v # meet the exact boundary, return directly
if... | [
"def",
"_get_value_to_set_at_point",
"(",
"self",
",",
"point",
")",
":",
"laste",
",",
"lastv",
"=",
"None",
",",
"None",
"for",
"e",
",",
"v",
"in",
"self",
".",
"schedule",
":",
"if",
"e",
"==",
"point",
":",
"return",
"v",
"# meet the exact boundary,... | Using schedule, compute the value to be set at a given point. | [
"Using",
"schedule",
"compute",
"the",
"value",
"to",
"be",
"set",
"at",
"a",
"given",
"point",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/callbacks/param.py#L283-L301 | train |
tensorpack/tensorpack | examples/basics/mnist-convnet.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-convnet.py#L27-L76 | train |
tensorpack/tensorpack | examples/ResNet/load-resnet.py | name_conversion | def name_conversion(caffe_layer_name):
""" Convert a caffe parameter name to a tensorflow parameter name as
defined in the above model """
# beginning & end mapping
NAME_MAP = {'bn_conv1/beta': 'conv0/bn/beta',
'bn_conv1/gamma': 'conv0/bn/gamma',
'bn_conv1/mean/EMA': ... | python | def name_conversion(caffe_layer_name):
""" Convert a caffe parameter name to a tensorflow parameter name as
defined in the above model """
# beginning & end mapping
NAME_MAP = {'bn_conv1/beta': 'conv0/bn/beta',
'bn_conv1/gamma': 'conv0/bn/gamma',
'bn_conv1/mean/EMA': ... | [
"def",
"name_conversion",
"(",
"caffe_layer_name",
")",
":",
"# beginning & end mapping",
"NAME_MAP",
"=",
"{",
"'bn_conv1/beta'",
":",
"'conv0/bn/beta'",
",",
"'bn_conv1/gamma'",
":",
"'conv0/bn/gamma'",
",",
"'bn_conv1/mean/EMA'",
":",
"'conv0/bn/mean/EMA'",
",",
"'bn_c... | Convert a caffe parameter name to a tensorflow parameter name as
defined in the above model | [
"Convert",
"a",
"caffe",
"parameter",
"name",
"to",
"a",
"tensorflow",
"parameter",
"name",
"as",
"defined",
"in",
"the",
"above",
"model"
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/ResNet/load-resnet.py#L101-L138 | train |
tensorpack/tensorpack | tensorpack/tfutils/varreplace.py | custom_getter_scope | def custom_getter_scope(custom_getter):
"""
Args:
custom_getter: the same as in :func:`tf.get_variable`
Returns:
The current variable scope with a custom_getter.
"""
scope = tf.get_variable_scope()
if get_tf_version_tuple() >= (1, 5):
with tf.variable_scope(
... | python | def custom_getter_scope(custom_getter):
"""
Args:
custom_getter: the same as in :func:`tf.get_variable`
Returns:
The current variable scope with a custom_getter.
"""
scope = tf.get_variable_scope()
if get_tf_version_tuple() >= (1, 5):
with tf.variable_scope(
... | [
"def",
"custom_getter_scope",
"(",
"custom_getter",
")",
":",
"scope",
"=",
"tf",
".",
"get_variable_scope",
"(",
")",
"if",
"get_tf_version_tuple",
"(",
")",
">=",
"(",
"1",
",",
"5",
")",
":",
"with",
"tf",
".",
"variable_scope",
"(",
"scope",
",",
"cu... | Args:
custom_getter: the same as in :func:`tf.get_variable`
Returns:
The current variable scope with a custom_getter. | [
"Args",
":",
"custom_getter",
":",
"the",
"same",
"as",
"in",
":",
"func",
":",
"tf",
".",
"get_variable"
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/tfutils/varreplace.py#L14-L33 | train |
tensorpack/tensorpack | tensorpack/tfutils/varreplace.py | remap_variables | def remap_variables(fn):
"""
Use fn to map the output of any variable getter.
Args:
fn (tf.Variable -> tf.Tensor)
Returns:
The current variable scope with a custom_getter that maps
all the variables by fn.
Example:
.. code-block:: python
with varreplac... | python | def remap_variables(fn):
"""
Use fn to map the output of any variable getter.
Args:
fn (tf.Variable -> tf.Tensor)
Returns:
The current variable scope with a custom_getter that maps
all the variables by fn.
Example:
.. code-block:: python
with varreplac... | [
"def",
"remap_variables",
"(",
"fn",
")",
":",
"def",
"custom_getter",
"(",
"getter",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"v",
"=",
"getter",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"fn",
"(",
"v",
")",
"return"... | Use fn to map the output of any variable getter.
Args:
fn (tf.Variable -> tf.Tensor)
Returns:
The current variable scope with a custom_getter that maps
all the variables by fn.
Example:
.. code-block:: python
with varreplace.remap_variables(lambda var: quantiz... | [
"Use",
"fn",
"to",
"map",
"the",
"output",
"of",
"any",
"variable",
"getter",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/tfutils/varreplace.py#L36-L56 | train |
tensorpack/tensorpack | tensorpack/tfutils/varreplace.py | freeze_variables | def freeze_variables(stop_gradient=True, skip_collection=False):
"""
Return a context to freeze variables,
by wrapping ``tf.get_variable`` with a custom getter.
It works by either applying ``tf.stop_gradient`` on the variables,
or by keeping them out of the ``TRAINABLE_VARIABLES`` collection, or
... | python | def freeze_variables(stop_gradient=True, skip_collection=False):
"""
Return a context to freeze variables,
by wrapping ``tf.get_variable`` with a custom getter.
It works by either applying ``tf.stop_gradient`` on the variables,
or by keeping them out of the ``TRAINABLE_VARIABLES`` collection, or
... | [
"def",
"freeze_variables",
"(",
"stop_gradient",
"=",
"True",
",",
"skip_collection",
"=",
"False",
")",
":",
"def",
"custom_getter",
"(",
"getter",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"trainable",
"=",
"kwargs",
".",
"get",
"(",
"'train... | Return a context to freeze variables,
by wrapping ``tf.get_variable`` with a custom getter.
It works by either applying ``tf.stop_gradient`` on the variables,
or by keeping them out of the ``TRAINABLE_VARIABLES`` collection, or
both.
Example:
.. code-block:: python
with varrepl... | [
"Return",
"a",
"context",
"to",
"freeze",
"variables",
"by",
"wrapping",
"tf",
".",
"get_variable",
"with",
"a",
"custom",
"getter",
".",
"It",
"works",
"by",
"either",
"applying",
"tf",
".",
"stop_gradient",
"on",
"the",
"variables",
"or",
"by",
"keeping",
... | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/tfutils/varreplace.py#L59-L97 | train |
tensorpack/tensorpack | tensorpack/utils/loadcaffe.py | load_caffe | def load_caffe(model_desc, model_file):
"""
Load a caffe model. You must be able to ``import caffe`` to use this
function.
Args:
model_desc (str): path to caffe model description file (.prototxt).
model_file (str): path to caffe model parameter file (.caffemodel).
Returns:
di... | python | def load_caffe(model_desc, model_file):
"""
Load a caffe model. You must be able to ``import caffe`` to use this
function.
Args:
model_desc (str): path to caffe model description file (.prototxt).
model_file (str): path to caffe model parameter file (.caffemodel).
Returns:
di... | [
"def",
"load_caffe",
"(",
"model_desc",
",",
"model_file",
")",
":",
"with",
"change_env",
"(",
"'GLOG_minloglevel'",
",",
"'2'",
")",
":",
"import",
"caffe",
"caffe",
".",
"set_mode_cpu",
"(",
")",
"net",
"=",
"caffe",
".",
"Net",
"(",
"model_desc",
",",
... | Load a caffe model. You must be able to ``import caffe`` to use this
function.
Args:
model_desc (str): path to caffe model description file (.prototxt).
model_file (str): path to caffe model parameter file (.caffemodel).
Returns:
dict: the parameters. | [
"Load",
"a",
"caffe",
"model",
".",
"You",
"must",
"be",
"able",
"to",
"import",
"caffe",
"to",
"use",
"this",
"function",
".",
"Args",
":",
"model_desc",
"(",
"str",
")",
":",
"path",
"to",
"caffe",
"model",
"description",
"file",
"(",
".",
"prototxt"... | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/loadcaffe.py#L96-L113 | train |
tensorpack/tensorpack | tensorpack/utils/loadcaffe.py | get_caffe_pb | def get_caffe_pb():
"""
Get caffe protobuf.
Returns:
The imported caffe protobuf module.
"""
dir = get_dataset_path('caffe')
caffe_pb_file = os.path.join(dir, 'caffe_pb2.py')
if not os.path.isfile(caffe_pb_file):
download(CAFFE_PROTO_URL, dir)
assert os.path.isfile(os... | python | def get_caffe_pb():
"""
Get caffe protobuf.
Returns:
The imported caffe protobuf module.
"""
dir = get_dataset_path('caffe')
caffe_pb_file = os.path.join(dir, 'caffe_pb2.py')
if not os.path.isfile(caffe_pb_file):
download(CAFFE_PROTO_URL, dir)
assert os.path.isfile(os... | [
"def",
"get_caffe_pb",
"(",
")",
":",
"dir",
"=",
"get_dataset_path",
"(",
"'caffe'",
")",
"caffe_pb_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"dir",
",",
"'caffe_pb2.py'",
")",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"caffe_pb_file",
... | Get caffe protobuf.
Returns:
The imported caffe protobuf module. | [
"Get",
"caffe",
"protobuf",
".",
"Returns",
":",
"The",
"imported",
"caffe",
"protobuf",
"module",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/loadcaffe.py#L116-L147 | train |
tensorpack/tensorpack | examples/FasterRCNN/config.py | finalize_configs | def finalize_configs(is_training):
"""
Run some sanity checks, and populate some configs from others
"""
_C.freeze(False) # populate new keys now
_C.DATA.NUM_CLASS = _C.DATA.NUM_CATEGORY + 1 # +1 background
_C.DATA.BASEDIR = os.path.expanduser(_C.DATA.BASEDIR)
if isinstance(_C.DATA.VAL, si... | python | def finalize_configs(is_training):
"""
Run some sanity checks, and populate some configs from others
"""
_C.freeze(False) # populate new keys now
_C.DATA.NUM_CLASS = _C.DATA.NUM_CATEGORY + 1 # +1 background
_C.DATA.BASEDIR = os.path.expanduser(_C.DATA.BASEDIR)
if isinstance(_C.DATA.VAL, si... | [
"def",
"finalize_configs",
"(",
"is_training",
")",
":",
"_C",
".",
"freeze",
"(",
"False",
")",
"# populate new keys now",
"_C",
".",
"DATA",
".",
"NUM_CLASS",
"=",
"_C",
".",
"DATA",
".",
"NUM_CATEGORY",
"+",
"1",
"# +1 background",
"_C",
".",
"DATA",
".... | Run some sanity checks, and populate some configs from others | [
"Run",
"some",
"sanity",
"checks",
"and",
"populate",
"some",
"configs",
"from",
"others"
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/config.py#L214-L282 | train |
tensorpack/tensorpack | examples/FasterRCNN/config.py | AttrDict.to_dict | def to_dict(self):
"""Convert to a nested dict. """
return {k: v.to_dict() if isinstance(v, AttrDict) else v
for k, v in self.__dict__.items() if not k.startswith('_')} | python | def to_dict(self):
"""Convert to a nested dict. """
return {k: v.to_dict() if isinstance(v, AttrDict) else v
for k, v in self.__dict__.items() if not k.startswith('_')} | [
"def",
"to_dict",
"(",
"self",
")",
":",
"return",
"{",
"k",
":",
"v",
".",
"to_dict",
"(",
")",
"if",
"isinstance",
"(",
"v",
",",
"AttrDict",
")",
"else",
"v",
"for",
"k",
",",
"v",
"in",
"self",
".",
"__dict__",
".",
"items",
"(",
")",
"if",... | Convert to a nested dict. | [
"Convert",
"to",
"a",
"nested",
"dict",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/config.py#L41-L44 | train |
tensorpack/tensorpack | examples/FasterRCNN/config.py | AttrDict.update_args | def update_args(self, args):
"""Update from command line args. """
for cfg in args:
keys, v = cfg.split('=', maxsplit=1)
keylist = keys.split('.')
dic = self
for i, k in enumerate(keylist[:-1]):
assert k in dir(dic), "Unknown config key: {... | python | def update_args(self, args):
"""Update from command line args. """
for cfg in args:
keys, v = cfg.split('=', maxsplit=1)
keylist = keys.split('.')
dic = self
for i, k in enumerate(keylist[:-1]):
assert k in dir(dic), "Unknown config key: {... | [
"def",
"update_args",
"(",
"self",
",",
"args",
")",
":",
"for",
"cfg",
"in",
"args",
":",
"keys",
",",
"v",
"=",
"cfg",
".",
"split",
"(",
"'='",
",",
"maxsplit",
"=",
"1",
")",
"keylist",
"=",
"keys",
".",
"split",
"(",
"'.'",
")",
"dic",
"="... | Update from command line args. | [
"Update",
"from",
"command",
"line",
"args",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/config.py#L46-L61 | train |
tensorpack/tensorpack | tensorpack/tfutils/sessinit.py | get_model_loader | def get_model_loader(filename):
"""
Get a corresponding model loader by looking at the file name.
Returns:
SessInit: either a :class:`DictRestore` (if name ends with 'npy/npz') or
:class:`SaverRestore` (otherwise).
"""
assert isinstance(filename, six.string_types), filename
file... | python | def get_model_loader(filename):
"""
Get a corresponding model loader by looking at the file name.
Returns:
SessInit: either a :class:`DictRestore` (if name ends with 'npy/npz') or
:class:`SaverRestore` (otherwise).
"""
assert isinstance(filename, six.string_types), filename
file... | [
"def",
"get_model_loader",
"(",
"filename",
")",
":",
"assert",
"isinstance",
"(",
"filename",
",",
"six",
".",
"string_types",
")",
",",
"filename",
"filename",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"filename",
")",
"if",
"filename",
".",
"endsw... | Get a corresponding model loader by looking at the file name.
Returns:
SessInit: either a :class:`DictRestore` (if name ends with 'npy/npz') or
:class:`SaverRestore` (otherwise). | [
"Get",
"a",
"corresponding",
"model",
"loader",
"by",
"looking",
"at",
"the",
"file",
"name",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/tfutils/sessinit.py#L245-L263 | train |
tensorpack/tensorpack | tensorpack/tfutils/sessinit.py | SaverRestore._read_checkpoint_vars | def _read_checkpoint_vars(model_path):
""" return a set of strings """
reader = tf.train.NewCheckpointReader(model_path)
reader = CheckpointReaderAdapter(reader) # use an adapter to standardize the name
ckpt_vars = reader.get_variable_to_shape_map().keys()
return reader, set(c... | python | def _read_checkpoint_vars(model_path):
""" return a set of strings """
reader = tf.train.NewCheckpointReader(model_path)
reader = CheckpointReaderAdapter(reader) # use an adapter to standardize the name
ckpt_vars = reader.get_variable_to_shape_map().keys()
return reader, set(c... | [
"def",
"_read_checkpoint_vars",
"(",
"model_path",
")",
":",
"reader",
"=",
"tf",
".",
"train",
".",
"NewCheckpointReader",
"(",
"model_path",
")",
"reader",
"=",
"CheckpointReaderAdapter",
"(",
"reader",
")",
"# use an adapter to standardize the name",
"ckpt_vars",
"... | return a set of strings | [
"return",
"a",
"set",
"of",
"strings"
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/tfutils/sessinit.py#L118-L123 | train |
tensorpack/tensorpack | tensorpack/tfutils/argscope.py | argscope | def argscope(layers, **kwargs):
"""
Args:
layers (list or layer): layer or list of layers to apply the arguments.
Returns:
a context where all appearance of these layer will by default have the
arguments specified by kwargs.
Example:
.. code-block:: python
... | python | def argscope(layers, **kwargs):
"""
Args:
layers (list or layer): layer or list of layers to apply the arguments.
Returns:
a context where all appearance of these layer will by default have the
arguments specified by kwargs.
Example:
.. code-block:: python
... | [
"def",
"argscope",
"(",
"layers",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"isinstance",
"(",
"layers",
",",
"list",
")",
":",
"layers",
"=",
"[",
"layers",
"]",
"# def _check_args_exist(l):",
"# args = inspect.getargspec(l).args",
"# for k, v in si... | Args:
layers (list or layer): layer or list of layers to apply the arguments.
Returns:
a context where all appearance of these layer will by default have the
arguments specified by kwargs.
Example:
.. code-block:: python
with argscope(Conv2D, kernel_shape=3, nl=tf.... | [
"Args",
":",
"layers",
"(",
"list",
"or",
"layer",
")",
":",
"layer",
"or",
"list",
"of",
"layers",
"to",
"apply",
"the",
"arguments",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/tfutils/argscope.py#L22-L57 | train |
tensorpack/tensorpack | tensorpack/tfutils/argscope.py | enable_argscope_for_function | def enable_argscope_for_function(func, log_shape=True):
"""Decorator for function to support argscope
Example:
.. code-block:: python
from mylib import myfunc
myfunc = enable_argscope_for_function(myfunc)
Args:
func: A function mapping one or multiple tensors to o... | python | def enable_argscope_for_function(func, log_shape=True):
"""Decorator for function to support argscope
Example:
.. code-block:: python
from mylib import myfunc
myfunc = enable_argscope_for_function(myfunc)
Args:
func: A function mapping one or multiple tensors to o... | [
"def",
"enable_argscope_for_function",
"(",
"func",
",",
"log_shape",
"=",
"True",
")",
":",
"assert",
"callable",
"(",
"func",
")",
",",
"\"func should be a callable\"",
"@",
"wraps",
"(",
"func",
")",
"def",
"wrapped_func",
"(",
"*",
"args",
",",
"*",
"*",... | Decorator for function to support argscope
Example:
.. code-block:: python
from mylib import myfunc
myfunc = enable_argscope_for_function(myfunc)
Args:
func: A function mapping one or multiple tensors to one or multiple
tensors.
log_shape (bool): S... | [
"Decorator",
"for",
"function",
"to",
"support",
"argscope"
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/tfutils/argscope.py#L73-L123 | train |
tensorpack/tensorpack | tensorpack/tfutils/argscope.py | enable_argscope_for_module | def enable_argscope_for_module(module, log_shape=True):
"""
Overwrite all functions of a given module to support argscope.
Note that this function monkey-patches the module and therefore could
have unexpected consequences.
It has been only tested to work well with ``tf.layers`` module.
Example:... | python | def enable_argscope_for_module(module, log_shape=True):
"""
Overwrite all functions of a given module to support argscope.
Note that this function monkey-patches the module and therefore could
have unexpected consequences.
It has been only tested to work well with ``tf.layers`` module.
Example:... | [
"def",
"enable_argscope_for_module",
"(",
"module",
",",
"log_shape",
"=",
"True",
")",
":",
"if",
"is_tfv2",
"(",
")",
"and",
"module",
"==",
"tf",
".",
"layers",
":",
"module",
"=",
"tf",
".",
"compat",
".",
"v1",
".",
"layers",
"for",
"name",
",",
... | Overwrite all functions of a given module to support argscope.
Note that this function monkey-patches the module and therefore could
have unexpected consequences.
It has been only tested to work well with ``tf.layers`` module.
Example:
.. code-block:: python
import tensorflow as t... | [
"Overwrite",
"all",
"functions",
"of",
"a",
"given",
"module",
"to",
"support",
"argscope",
".",
"Note",
"that",
"this",
"function",
"monkey",
"-",
"patches",
"the",
"module",
"and",
"therefore",
"could",
"have",
"unexpected",
"consequences",
".",
"It",
"has",... | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/tfutils/argscope.py#L126-L148 | train |
tensorpack/tensorpack | examples/GAN/Image2Image.py | visualize_tensors | def visualize_tensors(name, imgs, scale_func=lambda x: (x + 1.) * 128., max_outputs=1):
"""Generate tensor for TensorBoard (casting, clipping)
Args:
name: name for visualization operation
*imgs: multiple tensors as list
scale_func: scale input tensors to fit range [0, 255]
Example:... | python | def visualize_tensors(name, imgs, scale_func=lambda x: (x + 1.) * 128., max_outputs=1):
"""Generate tensor for TensorBoard (casting, clipping)
Args:
name: name for visualization operation
*imgs: multiple tensors as list
scale_func: scale input tensors to fit range [0, 255]
Example:... | [
"def",
"visualize_tensors",
"(",
"name",
",",
"imgs",
",",
"scale_func",
"=",
"lambda",
"x",
":",
"(",
"x",
"+",
"1.",
")",
"*",
"128.",
",",
"max_outputs",
"=",
"1",
")",
":",
"xy",
"=",
"scale_func",
"(",
"tf",
".",
"concat",
"(",
"imgs",
",",
... | Generate tensor for TensorBoard (casting, clipping)
Args:
name: name for visualization operation
*imgs: multiple tensors as list
scale_func: scale input tensors to fit range [0, 255]
Example:
visualize_tensors('viz1', [img1])
visualize_tensors('viz2', [img1, img2, img3]... | [
"Generate",
"tensor",
"for",
"TensorBoard",
"(",
"casting",
"clipping",
")"
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/GAN/Image2Image.py#L46-L60 | train |
tensorpack/tensorpack | examples/GAN/Image2Image.py | split_input | def split_input(img):
"""
img: an RGB image of shape (s, 2s, 3).
:return: [input, output]
"""
# split the image into left + right pairs
s = img.shape[0]
assert img.shape[1] == 2 * s
input, output = img[:, :s, :], img[:, s:, :]
if args.mode == 'BtoA':
input, output = output, i... | python | def split_input(img):
"""
img: an RGB image of shape (s, 2s, 3).
:return: [input, output]
"""
# split the image into left + right pairs
s = img.shape[0]
assert img.shape[1] == 2 * s
input, output = img[:, :s, :], img[:, s:, :]
if args.mode == 'BtoA':
input, output = output, i... | [
"def",
"split_input",
"(",
"img",
")",
":",
"# split the image into left + right pairs",
"s",
"=",
"img",
".",
"shape",
"[",
"0",
"]",
"assert",
"img",
".",
"shape",
"[",
"1",
"]",
"==",
"2",
"*",
"s",
"input",
",",
"output",
"=",
"img",
"[",
":",
",... | img: an RGB image of shape (s, 2s, 3).
:return: [input, output] | [
"img",
":",
"an",
"RGB",
"image",
"of",
"shape",
"(",
"s",
"2s",
"3",
")",
".",
":",
"return",
":",
"[",
"input",
"output",
"]"
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/GAN/Image2Image.py#L149-L164 | train |
tensorpack/tensorpack | examples/GAN/Image2Image.py | Model.discriminator | def discriminator(self, inputs, outputs):
""" return a (b, 1) logits"""
l = tf.concat([inputs, outputs], 3)
with argscope(Conv2D, kernel_size=4, strides=2, activation=BNLReLU):
l = (LinearWrap(l)
.Conv2D('conv0', NF, activation=tf.nn.leaky_relu)
.Con... | python | def discriminator(self, inputs, outputs):
""" return a (b, 1) logits"""
l = tf.concat([inputs, outputs], 3)
with argscope(Conv2D, kernel_size=4, strides=2, activation=BNLReLU):
l = (LinearWrap(l)
.Conv2D('conv0', NF, activation=tf.nn.leaky_relu)
.Con... | [
"def",
"discriminator",
"(",
"self",
",",
"inputs",
",",
"outputs",
")",
":",
"l",
"=",
"tf",
".",
"concat",
"(",
"[",
"inputs",
",",
"outputs",
"]",
",",
"3",
")",
"with",
"argscope",
"(",
"Conv2D",
",",
"kernel_size",
"=",
"4",
",",
"strides",
"=... | return a (b, 1) logits | [
"return",
"a",
"(",
"b",
"1",
")",
"logits"
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/GAN/Image2Image.py#L106-L116 | train |
tensorpack/tensorpack | tensorpack/tfutils/symbolic_functions.py | print_stat | def print_stat(x, message=None):
""" A simple print Op that might be easier to use than :meth:`tf.Print`.
Use it like: ``x = print_stat(x, message='This is x')``.
"""
if message is None:
message = x.op.name
lst = [tf.shape(x), tf.reduce_mean(x)]
if x.dtype.is_floating:
lst.ap... | python | def print_stat(x, message=None):
""" A simple print Op that might be easier to use than :meth:`tf.Print`.
Use it like: ``x = print_stat(x, message='This is x')``.
"""
if message is None:
message = x.op.name
lst = [tf.shape(x), tf.reduce_mean(x)]
if x.dtype.is_floating:
lst.ap... | [
"def",
"print_stat",
"(",
"x",
",",
"message",
"=",
"None",
")",
":",
"if",
"message",
"is",
"None",
":",
"message",
"=",
"x",
".",
"op",
".",
"name",
"lst",
"=",
"[",
"tf",
".",
"shape",
"(",
"x",
")",
",",
"tf",
".",
"reduce_mean",
"(",
"x",
... | A simple print Op that might be easier to use than :meth:`tf.Print`.
Use it like: ``x = print_stat(x, message='This is x')``. | [
"A",
"simple",
"print",
"Op",
"that",
"might",
"be",
"easier",
"to",
"use",
"than",
":",
"meth",
":",
"tf",
".",
"Print",
".",
"Use",
"it",
"like",
":",
"x",
"=",
"print_stat",
"(",
"x",
"message",
"=",
"This",
"is",
"x",
")",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/tfutils/symbolic_functions.py#L13-L23 | train |
tensorpack/tensorpack | tensorpack/tfutils/symbolic_functions.py | rms | def rms(x, name=None):
"""
Returns:
root mean square of tensor x.
"""
if name is None:
name = x.op.name + '/rms'
with tfv1.name_scope(None): # name already contains the scope
return tf.sqrt(tf.reduce_mean(tf.square(x)), name=name)
return tf.sqrt(tf.reduce_mean(t... | python | def rms(x, name=None):
"""
Returns:
root mean square of tensor x.
"""
if name is None:
name = x.op.name + '/rms'
with tfv1.name_scope(None): # name already contains the scope
return tf.sqrt(tf.reduce_mean(tf.square(x)), name=name)
return tf.sqrt(tf.reduce_mean(t... | [
"def",
"rms",
"(",
"x",
",",
"name",
"=",
"None",
")",
":",
"if",
"name",
"is",
"None",
":",
"name",
"=",
"x",
".",
"op",
".",
"name",
"+",
"'/rms'",
"with",
"tfv1",
".",
"name_scope",
"(",
"None",
")",
":",
"# name already contains the scope",
"retu... | Returns:
root mean square of tensor x. | [
"Returns",
":",
"root",
"mean",
"square",
"of",
"tensor",
"x",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/tfutils/symbolic_functions.py#L27-L36 | train |
tensorpack/tensorpack | tensorpack/tfutils/symbolic_functions.py | psnr | def psnr(prediction, ground_truth, maxp=None, name='psnr'):
"""`Peek Signal to Noise Ratio <https://en.wikipedia.org/wiki/Peak_signal-to-noise_ratio>`_.
.. math::
PSNR = 20 \cdot \log_{10}(MAX_p) - 10 \cdot \log_{10}(MSE)
Args:
prediction: a :class:`tf.Tensor` representing the prediction ... | python | def psnr(prediction, ground_truth, maxp=None, name='psnr'):
"""`Peek Signal to Noise Ratio <https://en.wikipedia.org/wiki/Peak_signal-to-noise_ratio>`_.
.. math::
PSNR = 20 \cdot \log_{10}(MAX_p) - 10 \cdot \log_{10}(MSE)
Args:
prediction: a :class:`tf.Tensor` representing the prediction ... | [
"def",
"psnr",
"(",
"prediction",
",",
"ground_truth",
",",
"maxp",
"=",
"None",
",",
"name",
"=",
"'psnr'",
")",
":",
"maxp",
"=",
"float",
"(",
"maxp",
")",
"def",
"log10",
"(",
"x",
")",
":",
"with",
"tf",
".",
"name_scope",
"(",
"\"log10\"",
")... | `Peek Signal to Noise Ratio <https://en.wikipedia.org/wiki/Peak_signal-to-noise_ratio>`_.
.. math::
PSNR = 20 \cdot \log_{10}(MAX_p) - 10 \cdot \log_{10}(MSE)
Args:
prediction: a :class:`tf.Tensor` representing the prediction signal.
ground_truth: another :class:`tf.Tensor` with the s... | [
"Peek",
"Signal",
"to",
"Noise",
"Ratio",
"<https",
":",
"//",
"en",
".",
"wikipedia",
".",
"org",
"/",
"wiki",
"/",
"Peak_signal",
"-",
"to",
"-",
"noise_ratio",
">",
"_",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/tfutils/symbolic_functions.py#L41-L72 | train |
tensorpack/tensorpack | tensorpack/dataflow/imgaug/deform.py | GaussianMap.get_gaussian_weight | def get_gaussian_weight(self, anchor):
"""
Args:
anchor: coordinate of the center
"""
ret = np.zeros(self.shape, dtype='float32')
y, x = np.mgrid[:self.shape[0], :self.shape[1]]
y = y.astype('float32') / ret.shape[0] - anchor[0]
x = x.astype('float32'... | python | def get_gaussian_weight(self, anchor):
"""
Args:
anchor: coordinate of the center
"""
ret = np.zeros(self.shape, dtype='float32')
y, x = np.mgrid[:self.shape[0], :self.shape[1]]
y = y.astype('float32') / ret.shape[0] - anchor[0]
x = x.astype('float32'... | [
"def",
"get_gaussian_weight",
"(",
"self",
",",
"anchor",
")",
":",
"ret",
"=",
"np",
".",
"zeros",
"(",
"self",
".",
"shape",
",",
"dtype",
"=",
"'float32'",
")",
"y",
",",
"x",
"=",
"np",
".",
"mgrid",
"[",
":",
"self",
".",
"shape",
"[",
"0",
... | Args:
anchor: coordinate of the center | [
"Args",
":",
"anchor",
":",
"coordinate",
"of",
"the",
"center"
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/dataflow/imgaug/deform.py#L26-L39 | train |
tensorpack/tensorpack | examples/OpticalFlow/flownet_models.py | pad | def pad(x, p=3):
"""Pad tensor in H, W
Remarks:
TensorFlow uses "ceil(input_spatial_shape[i] / strides[i])" rather than explicit padding
like Caffe, pyTorch does. Hence, we need to pad here beforehand.
Args:
x (tf.tensor): incoming tensor
p (int, optional): padding for H, W... | python | def pad(x, p=3):
"""Pad tensor in H, W
Remarks:
TensorFlow uses "ceil(input_spatial_shape[i] / strides[i])" rather than explicit padding
like Caffe, pyTorch does. Hence, we need to pad here beforehand.
Args:
x (tf.tensor): incoming tensor
p (int, optional): padding for H, W... | [
"def",
"pad",
"(",
"x",
",",
"p",
"=",
"3",
")",
":",
"return",
"tf",
".",
"pad",
"(",
"x",
",",
"[",
"[",
"0",
",",
"0",
"]",
",",
"[",
"0",
",",
"0",
"]",
",",
"[",
"p",
",",
"p",
"]",
",",
"[",
"p",
",",
"p",
"]",
"]",
")"
] | Pad tensor in H, W
Remarks:
TensorFlow uses "ceil(input_spatial_shape[i] / strides[i])" rather than explicit padding
like Caffe, pyTorch does. Hence, we need to pad here beforehand.
Args:
x (tf.tensor): incoming tensor
p (int, optional): padding for H, W
Returns:
t... | [
"Pad",
"tensor",
"in",
"H",
"W"
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/OpticalFlow/flownet_models.py#L17-L31 | train |
tensorpack/tensorpack | examples/OpticalFlow/flownet_models.py | correlation | def correlation(ina, inb,
kernel_size, max_displacement,
stride_1, stride_2,
pad, data_format):
"""
Correlation Cost Volume computation.
This is a fallback Python-only implementation, specialized just for FlowNet2.
It takes a lot of memory and is slow.
... | python | def correlation(ina, inb,
kernel_size, max_displacement,
stride_1, stride_2,
pad, data_format):
"""
Correlation Cost Volume computation.
This is a fallback Python-only implementation, specialized just for FlowNet2.
It takes a lot of memory and is slow.
... | [
"def",
"correlation",
"(",
"ina",
",",
"inb",
",",
"kernel_size",
",",
"max_displacement",
",",
"stride_1",
",",
"stride_2",
",",
"pad",
",",
"data_format",
")",
":",
"assert",
"pad",
"==",
"max_displacement",
"assert",
"kernel_size",
"==",
"1",
"assert",
"d... | Correlation Cost Volume computation.
This is a fallback Python-only implementation, specialized just for FlowNet2.
It takes a lot of memory and is slow.
If you know to compile a custom op yourself, it's better to use the cuda implementation here:
https://github.com/PatWie/tensorflow-recipes/tree/maste... | [
"Correlation",
"Cost",
"Volume",
"computation",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/OpticalFlow/flownet_models.py#L38-L72 | train |
tensorpack/tensorpack | examples/OpticalFlow/flownet_models.py | resize | def resize(x, mode, factor=4):
"""Resize input tensor with unkown input-shape by a factor
Args:
x (tf.Tensor): tensor NCHW
factor (int, optional): resize factor for H, W
Note:
Differences here against Caffe have huge impacts on the
quality of the predictions.
Returns:
... | python | def resize(x, mode, factor=4):
"""Resize input tensor with unkown input-shape by a factor
Args:
x (tf.Tensor): tensor NCHW
factor (int, optional): resize factor for H, W
Note:
Differences here against Caffe have huge impacts on the
quality of the predictions.
Returns:
... | [
"def",
"resize",
"(",
"x",
",",
"mode",
",",
"factor",
"=",
"4",
")",
":",
"assert",
"mode",
"in",
"[",
"'bilinear'",
",",
"'nearest'",
"]",
",",
"mode",
"shp",
"=",
"tf",
".",
"shape",
"(",
"x",
")",
"[",
"2",
":",
"]",
"*",
"factor",
"# NCHW ... | Resize input tensor with unkown input-shape by a factor
Args:
x (tf.Tensor): tensor NCHW
factor (int, optional): resize factor for H, W
Note:
Differences here against Caffe have huge impacts on the
quality of the predictions.
Returns:
tf.Tensor: resized tensor NCHW | [
"Resize",
"input",
"tensor",
"with",
"unkown",
"input",
"-",
"shape",
"by",
"a",
"factor"
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/OpticalFlow/flownet_models.py#L115-L139 | train |
tensorpack/tensorpack | examples/OpticalFlow/flownet_models.py | FlowNet2.flownet2_fusion | def flownet2_fusion(self, x):
"""
Architecture in Table 4 of FlowNet 2.0.
Args:
x: NCHW tensor, where C=11 is the concatenation of 7 items of [3, 2, 2, 1, 1, 1, 1] channels.
"""
with argscope([tf.layers.conv2d], activation=lambda x: tf.nn.leaky_relu(x, 0.1),
... | python | def flownet2_fusion(self, x):
"""
Architecture in Table 4 of FlowNet 2.0.
Args:
x: NCHW tensor, where C=11 is the concatenation of 7 items of [3, 2, 2, 1, 1, 1, 1] channels.
"""
with argscope([tf.layers.conv2d], activation=lambda x: tf.nn.leaky_relu(x, 0.1),
... | [
"def",
"flownet2_fusion",
"(",
"self",
",",
"x",
")",
":",
"with",
"argscope",
"(",
"[",
"tf",
".",
"layers",
".",
"conv2d",
"]",
",",
"activation",
"=",
"lambda",
"x",
":",
"tf",
".",
"nn",
".",
"leaky_relu",
"(",
"x",
",",
"0.1",
")",
",",
"pad... | Architecture in Table 4 of FlowNet 2.0.
Args:
x: NCHW tensor, where C=11 is the concatenation of 7 items of [3, 2, 2, 1, 1, 1, 1] channels. | [
"Architecture",
"in",
"Table",
"4",
"of",
"FlowNet",
"2",
".",
"0",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/OpticalFlow/flownet_models.py#L230-L264 | train |
tensorpack/tensorpack | examples/OpticalFlow/flownet_models.py | FlowNet2.flownet2_sd | def flownet2_sd(self, x):
"""
Architecture in Table 3 of FlowNet 2.0.
Args:
x: concatenation of two inputs, of shape [1, 2xC, H, W]
"""
with argscope([tf.layers.conv2d], activation=lambda x: tf.nn.leaky_relu(x, 0.1),
padding='valid', strides=2, ... | python | def flownet2_sd(self, x):
"""
Architecture in Table 3 of FlowNet 2.0.
Args:
x: concatenation of two inputs, of shape [1, 2xC, H, W]
"""
with argscope([tf.layers.conv2d], activation=lambda x: tf.nn.leaky_relu(x, 0.1),
padding='valid', strides=2, ... | [
"def",
"flownet2_sd",
"(",
"self",
",",
"x",
")",
":",
"with",
"argscope",
"(",
"[",
"tf",
".",
"layers",
".",
"conv2d",
"]",
",",
"activation",
"=",
"lambda",
"x",
":",
"tf",
".",
"nn",
".",
"leaky_relu",
"(",
"x",
",",
"0.1",
")",
",",
"padding... | Architecture in Table 3 of FlowNet 2.0.
Args:
x: concatenation of two inputs, of shape [1, 2xC, H, W] | [
"Architecture",
"in",
"Table",
"3",
"of",
"FlowNet",
"2",
".",
"0",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/OpticalFlow/flownet_models.py#L266-L320 | train |
tensorpack/tensorpack | examples/OpticalFlow/flownet_models.py | FlowNet2S.graph_structure | def graph_structure(self, x, standalone=True):
"""
Architecture of FlowNetSimple in Figure 2 of FlowNet 1.0.
Args:
x: 2CHW if standalone==True, else NCHW where C=12 is a concatenation
of 5 tensors of [3, 3, 3, 2, 1] channels.
standalone: If True, this mod... | python | def graph_structure(self, x, standalone=True):
"""
Architecture of FlowNetSimple in Figure 2 of FlowNet 1.0.
Args:
x: 2CHW if standalone==True, else NCHW where C=12 is a concatenation
of 5 tensors of [3, 3, 3, 2, 1] channels.
standalone: If True, this mod... | [
"def",
"graph_structure",
"(",
"self",
",",
"x",
",",
"standalone",
"=",
"True",
")",
":",
"if",
"standalone",
":",
"x",
"=",
"tf",
".",
"concat",
"(",
"tf",
".",
"split",
"(",
"x",
",",
"2",
",",
"axis",
"=",
"0",
")",
",",
"axis",
"=",
"1",
... | Architecture of FlowNetSimple in Figure 2 of FlowNet 1.0.
Args:
x: 2CHW if standalone==True, else NCHW where C=12 is a concatenation
of 5 tensors of [3, 3, 3, 2, 1] channels.
standalone: If True, this model is used to predict flow from two inputs.
If Fals... | [
"Architecture",
"of",
"FlowNetSimple",
"in",
"Figure",
"2",
"of",
"FlowNet",
"1",
".",
"0",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/OpticalFlow/flownet_models.py#L324-L375 | train |
tensorpack/tensorpack | examples/OpticalFlow/flownet_models.py | FlowNet2C.graph_structure | def graph_structure(self, x1x2):
"""
Architecture of FlowNetCorr in Figure 2 of FlowNet 1.0.
Args:
x: 2CHW.
"""
with argscope([tf.layers.conv2d], activation=lambda x: tf.nn.leaky_relu(x, 0.1),
padding='valid', strides=2, kernel_size=3,
... | python | def graph_structure(self, x1x2):
"""
Architecture of FlowNetCorr in Figure 2 of FlowNet 1.0.
Args:
x: 2CHW.
"""
with argscope([tf.layers.conv2d], activation=lambda x: tf.nn.leaky_relu(x, 0.1),
padding='valid', strides=2, kernel_size=3,
... | [
"def",
"graph_structure",
"(",
"self",
",",
"x1x2",
")",
":",
"with",
"argscope",
"(",
"[",
"tf",
".",
"layers",
".",
"conv2d",
"]",
",",
"activation",
"=",
"lambda",
"x",
":",
"tf",
".",
"nn",
".",
"leaky_relu",
"(",
"x",
",",
"0.1",
")",
",",
"... | Architecture of FlowNetCorr in Figure 2 of FlowNet 1.0.
Args:
x: 2CHW. | [
"Architecture",
"of",
"FlowNetCorr",
"in",
"Figure",
"2",
"of",
"FlowNet",
"1",
".",
"0",
".",
"Args",
":",
"x",
":",
"2CHW",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/OpticalFlow/flownet_models.py#L379-L442 | train |
tensorpack/tensorpack | examples/FasterRCNN/viz.py | draw_annotation | def draw_annotation(img, boxes, klass, is_crowd=None):
"""Will not modify img"""
labels = []
assert len(boxes) == len(klass)
if is_crowd is not None:
assert len(boxes) == len(is_crowd)
for cls, crd in zip(klass, is_crowd):
clsname = cfg.DATA.CLASS_NAMES[cls]
if cr... | python | def draw_annotation(img, boxes, klass, is_crowd=None):
"""Will not modify img"""
labels = []
assert len(boxes) == len(klass)
if is_crowd is not None:
assert len(boxes) == len(is_crowd)
for cls, crd in zip(klass, is_crowd):
clsname = cfg.DATA.CLASS_NAMES[cls]
if cr... | [
"def",
"draw_annotation",
"(",
"img",
",",
"boxes",
",",
"klass",
",",
"is_crowd",
"=",
"None",
")",
":",
"labels",
"=",
"[",
"]",
"assert",
"len",
"(",
"boxes",
")",
"==",
"len",
"(",
"klass",
")",
"if",
"is_crowd",
"is",
"not",
"None",
":",
"asse... | Will not modify img | [
"Will",
"not",
"modify",
"img"
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/viz.py#L15-L30 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.