id int32 0 252k | repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 75 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
27,300 | 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 |
27,301 | 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 |
27,302 | 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 |
27,303 | 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 |
27,304 | 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 |
27,305 | 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 |
27,306 | 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 |
27,307 | 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 |
27,308 | 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 |
27,309 | 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 |
27,310 | 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 |
27,311 | 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 |
27,312 | tensorpack/tensorpack | examples/FasterRCNN/viz.py | draw_mask | def draw_mask(im, mask, alpha=0.5, color=None):
"""
Overlay a mask on top of the image.
Args:
im: a 3-channel uint8 image in BGR
mask: a binary 1-channel image of the same size
color: if None, will choose automatically
"""
if color is None:
color = PALETTE_RGB[np.ran... | python | def draw_mask(im, mask, alpha=0.5, color=None):
"""
Overlay a mask on top of the image.
Args:
im: a 3-channel uint8 image in BGR
mask: a binary 1-channel image of the same size
color: if None, will choose automatically
"""
if color is None:
color = PALETTE_RGB[np.ran... | [
"def",
"draw_mask",
"(",
"im",
",",
"mask",
",",
"alpha",
"=",
"0.5",
",",
"color",
"=",
"None",
")",
":",
"if",
"color",
"is",
"None",
":",
"color",
"=",
"PALETTE_RGB",
"[",
"np",
".",
"random",
".",
"choice",
"(",
"len",
"(",
"PALETTE_RGB",
")",
... | Overlay a mask on top of the image.
Args:
im: a 3-channel uint8 image in BGR
mask: a binary 1-channel image of the same size
color: if None, will choose automatically | [
"Overlay",
"a",
"mask",
"on",
"top",
"of",
"the",
"image",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/viz.py#L94-L108 |
27,313 | tensorpack/tensorpack | tensorpack/dataflow/remote.py | send_dataflow_zmq | def send_dataflow_zmq(df, addr, hwm=50, format=None, bind=False):
"""
Run DataFlow and send data to a ZMQ socket addr.
It will serialize and send each datapoint to this address with a PUSH socket.
This function never returns.
Args:
df (DataFlow): Will infinitely loop over the DataFlow.
... | python | def send_dataflow_zmq(df, addr, hwm=50, format=None, bind=False):
"""
Run DataFlow and send data to a ZMQ socket addr.
It will serialize and send each datapoint to this address with a PUSH socket.
This function never returns.
Args:
df (DataFlow): Will infinitely loop over the DataFlow.
... | [
"def",
"send_dataflow_zmq",
"(",
"df",
",",
"addr",
",",
"hwm",
"=",
"50",
",",
"format",
"=",
"None",
",",
"bind",
"=",
"False",
")",
":",
"assert",
"format",
"in",
"[",
"None",
",",
"'zmq_op'",
",",
"'zmq_ops'",
"]",
"if",
"format",
"is",
"None",
... | Run DataFlow and send data to a ZMQ socket addr.
It will serialize and send each datapoint to this address with a PUSH socket.
This function never returns.
Args:
df (DataFlow): Will infinitely loop over the DataFlow.
addr: a ZMQ socket endpoint.
hwm (int): ZMQ high-water mark (buffe... | [
"Run",
"DataFlow",
"and",
"send",
"data",
"to",
"a",
"ZMQ",
"socket",
"addr",
".",
"It",
"will",
"serialize",
"and",
"send",
"each",
"datapoint",
"to",
"this",
"address",
"with",
"a",
"PUSH",
"socket",
".",
"This",
"function",
"never",
"returns",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/dataflow/remote.py#L26-L85 |
27,314 | tensorpack/tensorpack | examples/FasterRCNN/model_box.py | crop_and_resize | def crop_and_resize(image, boxes, box_ind, crop_size, pad_border=True):
"""
Aligned version of tf.image.crop_and_resize, following our definition of floating point boxes.
Args:
image: NCHW
boxes: nx4, x1y1x2y2
box_ind: (n,)
crop_size (int):
Returns:
n,C,size,size... | python | def crop_and_resize(image, boxes, box_ind, crop_size, pad_border=True):
"""
Aligned version of tf.image.crop_and_resize, following our definition of floating point boxes.
Args:
image: NCHW
boxes: nx4, x1y1x2y2
box_ind: (n,)
crop_size (int):
Returns:
n,C,size,size... | [
"def",
"crop_and_resize",
"(",
"image",
",",
"boxes",
",",
"box_ind",
",",
"crop_size",
",",
"pad_border",
"=",
"True",
")",
":",
"assert",
"isinstance",
"(",
"crop_size",
",",
"int",
")",
",",
"crop_size",
"boxes",
"=",
"tf",
".",
"stop_gradient",
"(",
... | Aligned version of tf.image.crop_and_resize, following our definition of floating point boxes.
Args:
image: NCHW
boxes: nx4, x1y1x2y2
box_ind: (n,)
crop_size (int):
Returns:
n,C,size,size | [
"Aligned",
"version",
"of",
"tf",
".",
"image",
".",
"crop_and_resize",
"following",
"our",
"definition",
"of",
"floating",
"point",
"boxes",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/model_box.py#L83-L153 |
27,315 | tensorpack/tensorpack | examples/FasterRCNN/model_box.py | RPNAnchors.narrow_to | def narrow_to(self, featuremap):
"""
Slice anchors to the spatial size of this featuremap.
"""
shape2d = tf.shape(featuremap)[2:] # h,w
slice3d = tf.concat([shape2d, [-1]], axis=0)
slice4d = tf.concat([shape2d, [-1, -1]], axis=0)
boxes = tf.slice(self.boxes, [0, ... | python | def narrow_to(self, featuremap):
"""
Slice anchors to the spatial size of this featuremap.
"""
shape2d = tf.shape(featuremap)[2:] # h,w
slice3d = tf.concat([shape2d, [-1]], axis=0)
slice4d = tf.concat([shape2d, [-1, -1]], axis=0)
boxes = tf.slice(self.boxes, [0, ... | [
"def",
"narrow_to",
"(",
"self",
",",
"featuremap",
")",
":",
"shape2d",
"=",
"tf",
".",
"shape",
"(",
"featuremap",
")",
"[",
"2",
":",
"]",
"# h,w",
"slice3d",
"=",
"tf",
".",
"concat",
"(",
"[",
"shape2d",
",",
"[",
"-",
"1",
"]",
"]",
",",
... | Slice anchors to the spatial size of this featuremap. | [
"Slice",
"anchors",
"to",
"the",
"spatial",
"size",
"of",
"this",
"featuremap",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/model_box.py#L189-L199 |
27,316 | tensorpack/tensorpack | tensorpack/utils/argtools.py | map_arg | def map_arg(**maps):
"""
Apply a mapping on certain argument before calling the original function.
Args:
maps (dict): {argument_name: map_func}
"""
def deco(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
if six.PY2:
argmap = inspect.g... | python | def map_arg(**maps):
"""
Apply a mapping on certain argument before calling the original function.
Args:
maps (dict): {argument_name: map_func}
"""
def deco(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
if six.PY2:
argmap = inspect.g... | [
"def",
"map_arg",
"(",
"*",
"*",
"maps",
")",
":",
"def",
"deco",
"(",
"func",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"six",
".",
"PY2",
":",
"a... | Apply a mapping on certain argument before calling the original function.
Args:
maps (dict): {argument_name: map_func} | [
"Apply",
"a",
"mapping",
"on",
"certain",
"argument",
"before",
"calling",
"the",
"original",
"function",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/argtools.py#L19-L40 |
27,317 | tensorpack/tensorpack | tensorpack/utils/argtools.py | graph_memoized | def graph_memoized(func):
"""
Like memoized, but keep one cache per default graph.
"""
# TODO it keeps the graph alive
from ..compat import tfv1
GRAPH_ARG_NAME = '__IMPOSSIBLE_NAME_FOR_YOU__'
@memoized
def func_with_graph_arg(*args, **kwargs):
kwargs.pop(GRAPH_ARG_NAME)
... | python | def graph_memoized(func):
"""
Like memoized, but keep one cache per default graph.
"""
# TODO it keeps the graph alive
from ..compat import tfv1
GRAPH_ARG_NAME = '__IMPOSSIBLE_NAME_FOR_YOU__'
@memoized
def func_with_graph_arg(*args, **kwargs):
kwargs.pop(GRAPH_ARG_NAME)
... | [
"def",
"graph_memoized",
"(",
"func",
")",
":",
"# TODO it keeps the graph alive",
"from",
".",
".",
"compat",
"import",
"tfv1",
"GRAPH_ARG_NAME",
"=",
"'__IMPOSSIBLE_NAME_FOR_YOU__'",
"@",
"memoized",
"def",
"func_with_graph_arg",
"(",
"*",
"args",
",",
"*",
"*",
... | Like memoized, but keep one cache per default graph. | [
"Like",
"memoized",
"but",
"keep",
"one",
"cache",
"per",
"default",
"graph",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/argtools.py#L49-L69 |
27,318 | tensorpack/tensorpack | tensorpack/utils/argtools.py | memoized_ignoreargs | def memoized_ignoreargs(func):
"""
A decorator. It performs memoization ignoring the arguments used to call
the function.
"""
def wrapper(*args, **kwargs):
if func not in _MEMOIZED_NOARGS:
res = func(*args, **kwargs)
_MEMOIZED_NOARGS[func] = res
return res... | python | def memoized_ignoreargs(func):
"""
A decorator. It performs memoization ignoring the arguments used to call
the function.
"""
def wrapper(*args, **kwargs):
if func not in _MEMOIZED_NOARGS:
res = func(*args, **kwargs)
_MEMOIZED_NOARGS[func] = res
return res... | [
"def",
"memoized_ignoreargs",
"(",
"func",
")",
":",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"func",
"not",
"in",
"_MEMOIZED_NOARGS",
":",
"res",
"=",
"func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"_ME... | A decorator. It performs memoization ignoring the arguments used to call
the function. | [
"A",
"decorator",
".",
"It",
"performs",
"memoization",
"ignoring",
"the",
"arguments",
"used",
"to",
"call",
"the",
"function",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/argtools.py#L75-L86 |
27,319 | tensorpack/tensorpack | tensorpack/utils/argtools.py | shape2d | def shape2d(a):
"""
Ensure a 2D shape.
Args:
a: a int or tuple/list of length 2
Returns:
list: of length 2. if ``a`` is a int, return ``[a, a]``.
"""
if type(a) == int:
return [a, a]
if isinstance(a, (list, tuple)):
assert len(a) == 2
return list(a)
... | python | def shape2d(a):
"""
Ensure a 2D shape.
Args:
a: a int or tuple/list of length 2
Returns:
list: of length 2. if ``a`` is a int, return ``[a, a]``.
"""
if type(a) == int:
return [a, a]
if isinstance(a, (list, tuple)):
assert len(a) == 2
return list(a)
... | [
"def",
"shape2d",
"(",
"a",
")",
":",
"if",
"type",
"(",
"a",
")",
"==",
"int",
":",
"return",
"[",
"a",
",",
"a",
"]",
"if",
"isinstance",
"(",
"a",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"assert",
"len",
"(",
"a",
")",
"==",
"2",
... | Ensure a 2D shape.
Args:
a: a int or tuple/list of length 2
Returns:
list: of length 2. if ``a`` is a int, return ``[a, a]``. | [
"Ensure",
"a",
"2D",
"shape",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/argtools.py#L89-L104 |
27,320 | tensorpack/tensorpack | tensorpack/utils/argtools.py | shape4d | def shape4d(a, data_format='NHWC'):
"""
Ensuer a 4D shape, to use with 4D symbolic functions.
Args:
a: a int or tuple/list of length 2
Returns:
list: of length 4. if ``a`` is a int, return ``[1, a, a, 1]``
or ``[1, 1, a, a]`` depending on data_format.
"""
s2d = shap... | python | def shape4d(a, data_format='NHWC'):
"""
Ensuer a 4D shape, to use with 4D symbolic functions.
Args:
a: a int or tuple/list of length 2
Returns:
list: of length 4. if ``a`` is a int, return ``[1, a, a, 1]``
or ``[1, 1, a, a]`` depending on data_format.
"""
s2d = shap... | [
"def",
"shape4d",
"(",
"a",
",",
"data_format",
"=",
"'NHWC'",
")",
":",
"s2d",
"=",
"shape2d",
"(",
"a",
")",
"if",
"get_data_format",
"(",
"data_format",
",",
"False",
")",
"==",
"'NHWC'",
":",
"return",
"[",
"1",
"]",
"+",
"s2d",
"+",
"[",
"1",
... | Ensuer a 4D shape, to use with 4D symbolic functions.
Args:
a: a int or tuple/list of length 2
Returns:
list: of length 4. if ``a`` is a int, return ``[1, a, a, 1]``
or ``[1, 1, a, a]`` depending on data_format. | [
"Ensuer",
"a",
"4D",
"shape",
"to",
"use",
"with",
"4D",
"symbolic",
"functions",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/argtools.py#L118-L133 |
27,321 | tensorpack/tensorpack | tensorpack/utils/argtools.py | call_only_once | def call_only_once(func):
"""
Decorate a method or property of a class, so that this method can only
be called once for every instance.
Calling it more than once will result in exception.
"""
@functools.wraps(func)
def wrapper(*args, **kwargs):
self = args[0]
# cannot use has... | python | def call_only_once(func):
"""
Decorate a method or property of a class, so that this method can only
be called once for every instance.
Calling it more than once will result in exception.
"""
@functools.wraps(func)
def wrapper(*args, **kwargs):
self = args[0]
# cannot use has... | [
"def",
"call_only_once",
"(",
"func",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
"=",
"args",
"[",
"0",
"]",
"# cannot use hasattr here, because hasattr tries t... | Decorate a method or property of a class, so that this method can only
be called once for every instance.
Calling it more than once will result in exception. | [
"Decorate",
"a",
"method",
"or",
"property",
"of",
"a",
"class",
"so",
"that",
"this",
"method",
"can",
"only",
"be",
"called",
"once",
"for",
"every",
"instance",
".",
"Calling",
"it",
"more",
"than",
"once",
"will",
"result",
"in",
"exception",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/argtools.py#L149-L178 |
27,322 | tensorpack/tensorpack | tensorpack/utils/argtools.py | memoized_method | def memoized_method(func):
"""
A decorator that performs memoization on methods. It stores the cache on the object instance itself.
"""
@functools.wraps(func)
def wrapper(*args, **kwargs):
self = args[0]
assert func.__name__ in dir(self), "memoized_method can only be used on method!... | python | def memoized_method(func):
"""
A decorator that performs memoization on methods. It stores the cache on the object instance itself.
"""
@functools.wraps(func)
def wrapper(*args, **kwargs):
self = args[0]
assert func.__name__ in dir(self), "memoized_method can only be used on method!... | [
"def",
"memoized_method",
"(",
"func",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
"=",
"args",
"[",
"0",
"]",
"assert",
"func",
".",
"__name__",
"in",
... | A decorator that performs memoization on methods. It stores the cache on the object instance itself. | [
"A",
"decorator",
"that",
"performs",
"memoization",
"on",
"methods",
".",
"It",
"stores",
"the",
"cache",
"on",
"the",
"object",
"instance",
"itself",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/argtools.py#L181-L204 |
27,323 | tensorpack/tensorpack | tensorpack/tfutils/scope_utils.py | auto_reuse_variable_scope | def auto_reuse_variable_scope(func):
"""
A decorator which automatically reuses the current variable scope if the
function has been called with the same variable scope before.
Example:
.. code-block:: python
@auto_reuse_variable_scope
def myfunc(x):
return tf.layers.co... | python | def auto_reuse_variable_scope(func):
"""
A decorator which automatically reuses the current variable scope if the
function has been called with the same variable scope before.
Example:
.. code-block:: python
@auto_reuse_variable_scope
def myfunc(x):
return tf.layers.co... | [
"def",
"auto_reuse_variable_scope",
"(",
"func",
")",
":",
"used_scope",
"=",
"set",
"(",
")",
"@",
"functools",
".",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"scope",
"=",
"tf",
".",
"get_vari... | A decorator which automatically reuses the current variable scope if the
function has been called with the same variable scope before.
Example:
.. code-block:: python
@auto_reuse_variable_scope
def myfunc(x):
return tf.layers.conv2d(x, 128, 3)
myfunc(x1) # will inher... | [
"A",
"decorator",
"which",
"automatically",
"reuses",
"the",
"current",
"variable",
"scope",
"if",
"the",
"function",
"has",
"been",
"called",
"with",
"the",
"same",
"variable",
"scope",
"before",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/tfutils/scope_utils.py#L15-L54 |
27,324 | tensorpack/tensorpack | tensorpack/tfutils/scope_utils.py | cached_name_scope | def cached_name_scope(name, top_level=True):
"""
Return a context which either opens and caches a new name scope,
or reenter an existing one.
Args:
top_level(bool): if True, the name scope will always be top-level.
It will not be nested under any existing name scope of the caller.
... | python | def cached_name_scope(name, top_level=True):
"""
Return a context which either opens and caches a new name scope,
or reenter an existing one.
Args:
top_level(bool): if True, the name scope will always be top-level.
It will not be nested under any existing name scope of the caller.
... | [
"def",
"cached_name_scope",
"(",
"name",
",",
"top_level",
"=",
"True",
")",
":",
"if",
"not",
"top_level",
":",
"current_ns",
"=",
"tf",
".",
"get_default_graph",
"(",
")",
".",
"get_name_scope",
"(",
")",
"if",
"current_ns",
":",
"name",
"=",
"current_ns... | Return a context which either opens and caches a new name scope,
or reenter an existing one.
Args:
top_level(bool): if True, the name scope will always be top-level.
It will not be nested under any existing name scope of the caller. | [
"Return",
"a",
"context",
"which",
"either",
"opens",
"and",
"caches",
"a",
"new",
"name",
"scope",
"or",
"reenter",
"an",
"existing",
"one",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/tfutils/scope_utils.py#L136-L151 |
27,325 | tensorpack/tensorpack | tensorpack/graph_builder/training.py | SyncMultiGPUReplicatedBuilder.get_post_init_ops | def get_post_init_ops():
"""
Copy values of variables on GPU 0 to other GPUs.
"""
# literally all variables, because it's better to sync optimizer-internal variables as well
all_vars = tf.global_variables() + tf.local_variables()
var_by_name = dict([(v.name, v) for v in a... | python | def get_post_init_ops():
"""
Copy values of variables on GPU 0 to other GPUs.
"""
# literally all variables, because it's better to sync optimizer-internal variables as well
all_vars = tf.global_variables() + tf.local_variables()
var_by_name = dict([(v.name, v) for v in a... | [
"def",
"get_post_init_ops",
"(",
")",
":",
"# literally all variables, because it's better to sync optimizer-internal variables as well",
"all_vars",
"=",
"tf",
".",
"global_variables",
"(",
")",
"+",
"tf",
".",
"local_variables",
"(",
")",
"var_by_name",
"=",
"dict",
"("... | Copy values of variables on GPU 0 to other GPUs. | [
"Copy",
"values",
"of",
"variables",
"on",
"GPU",
"0",
"to",
"other",
"GPUs",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/graph_builder/training.py#L309-L349 |
27,326 | tensorpack/tensorpack | tensorpack/utils/utils.py | humanize_time_delta | def humanize_time_delta(sec):
"""Humanize timedelta given in seconds
Args:
sec (float): time difference in seconds. Must be positive.
Returns:
str - time difference as a readable string
Example:
.. code-block:: python
print(humanize_time_delta(1)) ... | python | def humanize_time_delta(sec):
"""Humanize timedelta given in seconds
Args:
sec (float): time difference in seconds. Must be positive.
Returns:
str - time difference as a readable string
Example:
.. code-block:: python
print(humanize_time_delta(1)) ... | [
"def",
"humanize_time_delta",
"(",
"sec",
")",
":",
"if",
"sec",
"<",
"0",
":",
"logger",
".",
"warn",
"(",
"\"humanize_time_delta() obtains negative seconds!\"",
")",
"return",
"\"{:.3g} seconds\"",
".",
"format",
"(",
"sec",
")",
"if",
"sec",
"==",
"0",
":",... | Humanize timedelta given in seconds
Args:
sec (float): time difference in seconds. Must be positive.
Returns:
str - time difference as a readable string
Example:
.. code-block:: python
print(humanize_time_delta(1)) # 1 second
print(h... | [
"Humanize",
"timedelta",
"given",
"in",
"seconds"
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/utils.py#L26-L65 |
27,327 | tensorpack/tensorpack | tensorpack/utils/utils.py | get_rng | def get_rng(obj=None):
"""
Get a good RNG seeded with time, pid and the object.
Args:
obj: some object to use to generate random seed.
Returns:
np.random.RandomState: the RNG.
"""
seed = (id(obj) + os.getpid() +
int(datetime.now().strftime("%Y%m%d%H%M%S%f"))) % 42949... | python | def get_rng(obj=None):
"""
Get a good RNG seeded with time, pid and the object.
Args:
obj: some object to use to generate random seed.
Returns:
np.random.RandomState: the RNG.
"""
seed = (id(obj) + os.getpid() +
int(datetime.now().strftime("%Y%m%d%H%M%S%f"))) % 42949... | [
"def",
"get_rng",
"(",
"obj",
"=",
"None",
")",
":",
"seed",
"=",
"(",
"id",
"(",
"obj",
")",
"+",
"os",
".",
"getpid",
"(",
")",
"+",
"int",
"(",
"datetime",
".",
"now",
"(",
")",
".",
"strftime",
"(",
"\"%Y%m%d%H%M%S%f\"",
")",
")",
")",
"%",... | Get a good RNG seeded with time, pid and the object.
Args:
obj: some object to use to generate random seed.
Returns:
np.random.RandomState: the RNG. | [
"Get",
"a",
"good",
"RNG",
"seeded",
"with",
"time",
"pid",
"and",
"the",
"object",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/utils.py#L117-L130 |
27,328 | tensorpack/tensorpack | tensorpack/utils/utils.py | execute_only_once | def execute_only_once():
"""
Each called in the code to this function is guaranteed to return True the
first time and False afterwards.
Returns:
bool: whether this is the first time this function gets called from this line of code.
Example:
.. code-block:: python
if ex... | python | def execute_only_once():
"""
Each called in the code to this function is guaranteed to return True the
first time and False afterwards.
Returns:
bool: whether this is the first time this function gets called from this line of code.
Example:
.. code-block:: python
if ex... | [
"def",
"execute_only_once",
"(",
")",
":",
"f",
"=",
"inspect",
".",
"currentframe",
"(",
")",
".",
"f_back",
"ident",
"=",
"(",
"f",
".",
"f_code",
".",
"co_filename",
",",
"f",
".",
"f_lineno",
")",
"if",
"ident",
"in",
"_EXECUTE_HISTORY",
":",
"retu... | Each called in the code to this function is guaranteed to return True the
first time and False afterwards.
Returns:
bool: whether this is the first time this function gets called from this line of code.
Example:
.. code-block:: python
if execute_only_once():
# ... | [
"Each",
"called",
"in",
"the",
"code",
"to",
"this",
"function",
"is",
"guaranteed",
"to",
"return",
"True",
"the",
"first",
"time",
"and",
"False",
"afterwards",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/utils.py#L136-L155 |
27,329 | tensorpack/tensorpack | tensorpack/utils/utils.py | get_tqdm_kwargs | def get_tqdm_kwargs(**kwargs):
"""
Return default arguments to be used with tqdm.
Args:
kwargs: extra arguments to be used.
Returns:
dict:
"""
default = dict(
smoothing=0.5,
dynamic_ncols=True,
ascii=True,
bar_format='{l_bar}{bar}|{n_fmt}/{total_f... | python | def get_tqdm_kwargs(**kwargs):
"""
Return default arguments to be used with tqdm.
Args:
kwargs: extra arguments to be used.
Returns:
dict:
"""
default = dict(
smoothing=0.5,
dynamic_ncols=True,
ascii=True,
bar_format='{l_bar}{bar}|{n_fmt}/{total_f... | [
"def",
"get_tqdm_kwargs",
"(",
"*",
"*",
"kwargs",
")",
":",
"default",
"=",
"dict",
"(",
"smoothing",
"=",
"0.5",
",",
"dynamic_ncols",
"=",
"True",
",",
"ascii",
"=",
"True",
",",
"bar_format",
"=",
"'{l_bar}{bar}|{n_fmt}/{total_fmt}[{elapsed}<{remaining},{rate_... | Return default arguments to be used with tqdm.
Args:
kwargs: extra arguments to be used.
Returns:
dict: | [
"Return",
"default",
"arguments",
"to",
"be",
"used",
"with",
"tqdm",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/utils.py#L190-L214 |
27,330 | tensorpack/tensorpack | tensorpack/utils/utils.py | find_library_full_path | def find_library_full_path(name):
"""
Similar to `from ctypes.util import find_library`, but try
to return full path if possible.
"""
from ctypes.util import find_library
if os.name == "posix" and sys.platform == "darwin":
# on Mac, ctypes already returns full path
return find_l... | python | def find_library_full_path(name):
"""
Similar to `from ctypes.util import find_library`, but try
to return full path if possible.
"""
from ctypes.util import find_library
if os.name == "posix" and sys.platform == "darwin":
# on Mac, ctypes already returns full path
return find_l... | [
"def",
"find_library_full_path",
"(",
"name",
")",
":",
"from",
"ctypes",
".",
"util",
"import",
"find_library",
"if",
"os",
".",
"name",
"==",
"\"posix\"",
"and",
"sys",
".",
"platform",
"==",
"\"darwin\"",
":",
"# on Mac, ctypes already returns full path",
"retu... | Similar to `from ctypes.util import find_library`, but try
to return full path if possible. | [
"Similar",
"to",
"from",
"ctypes",
".",
"util",
"import",
"find_library",
"but",
"try",
"to",
"return",
"full",
"path",
"if",
"possible",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/utils.py#L223-L293 |
27,331 | tensorpack/tensorpack | examples/DoReFa-Net/dorefa.py | get_dorefa | def get_dorefa(bitW, bitA, bitG):
"""
Return the three quantization functions fw, fa, fg, for weights, activations and gradients respectively
"""
def quantize(x, k):
n = float(2 ** k - 1)
@tf.custom_gradient
def _quantize(x):
return tf.round(x * n) / n, lambda dy: dy... | python | def get_dorefa(bitW, bitA, bitG):
"""
Return the three quantization functions fw, fa, fg, for weights, activations and gradients respectively
"""
def quantize(x, k):
n = float(2 ** k - 1)
@tf.custom_gradient
def _quantize(x):
return tf.round(x * n) / n, lambda dy: dy... | [
"def",
"get_dorefa",
"(",
"bitW",
",",
"bitA",
",",
"bitG",
")",
":",
"def",
"quantize",
"(",
"x",
",",
"k",
")",
":",
"n",
"=",
"float",
"(",
"2",
"**",
"k",
"-",
"1",
")",
"@",
"tf",
".",
"custom_gradient",
"def",
"_quantize",
"(",
"x",
")",
... | Return the three quantization functions fw, fa, fg, for weights, activations and gradients respectively | [
"Return",
"the",
"three",
"quantization",
"functions",
"fw",
"fa",
"fg",
"for",
"weights",
"activations",
"and",
"gradients",
"respectively"
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/DoReFa-Net/dorefa.py#L8-L64 |
27,332 | tensorpack/tensorpack | tensorpack/utils/viz.py | draw_text | def draw_text(img, pos, text, color, font_scale=0.4):
"""
Draw text on an image.
Args:
pos (tuple): x, y; the position of the text
text (str):
font_scale (float):
color (tuple): a 3-tuple BGR color in [0, 255]
"""
img = img.astype(np.uint8)
x0, y0 = int(pos[0]), ... | python | def draw_text(img, pos, text, color, font_scale=0.4):
"""
Draw text on an image.
Args:
pos (tuple): x, y; the position of the text
text (str):
font_scale (float):
color (tuple): a 3-tuple BGR color in [0, 255]
"""
img = img.astype(np.uint8)
x0, y0 = int(pos[0]), ... | [
"def",
"draw_text",
"(",
"img",
",",
"pos",
",",
"text",
",",
"color",
",",
"font_scale",
"=",
"0.4",
")",
":",
"img",
"=",
"img",
".",
"astype",
"(",
"np",
".",
"uint8",
")",
"x0",
",",
"y0",
"=",
"int",
"(",
"pos",
"[",
"0",
"]",
")",
",",
... | Draw text on an image.
Args:
pos (tuple): x, y; the position of the text
text (str):
font_scale (float):
color (tuple): a 3-tuple BGR color in [0, 255] | [
"Draw",
"text",
"on",
"an",
"image",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/viz.py#L353-L379 |
27,333 | tensorpack/tensorpack | examples/FasterRCNN/common.py | segmentation_to_mask | def segmentation_to_mask(polys, height, width):
"""
Convert polygons to binary masks.
Args:
polys: a list of nx2 float array. Each array contains many (x, y) coordinates.
Returns:
a binary matrix of (height, width)
"""
polys = [p.flatten().tolist() for p in polys]
assert le... | python | def segmentation_to_mask(polys, height, width):
"""
Convert polygons to binary masks.
Args:
polys: a list of nx2 float array. Each array contains many (x, y) coordinates.
Returns:
a binary matrix of (height, width)
"""
polys = [p.flatten().tolist() for p in polys]
assert le... | [
"def",
"segmentation_to_mask",
"(",
"polys",
",",
"height",
",",
"width",
")",
":",
"polys",
"=",
"[",
"p",
".",
"flatten",
"(",
")",
".",
"tolist",
"(",
")",
"for",
"p",
"in",
"polys",
"]",
"assert",
"len",
"(",
"polys",
")",
">",
"0",
",",
"\"P... | Convert polygons to binary masks.
Args:
polys: a list of nx2 float array. Each array contains many (x, y) coordinates.
Returns:
a binary matrix of (height, width) | [
"Convert",
"polygons",
"to",
"binary",
"masks",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/common.py#L91-L107 |
27,334 | tensorpack/tensorpack | tensorpack/models/pool.py | MaxPooling | def MaxPooling(
inputs,
pool_size,
strides=None,
padding='valid',
data_format='channels_last'):
"""
Same as `tf.layers.MaxPooling2D`. Default strides is equal to pool_size.
"""
if strides is None:
strides = pool_size
layer = tf.layers.MaxPooling2D(pool... | python | def MaxPooling(
inputs,
pool_size,
strides=None,
padding='valid',
data_format='channels_last'):
"""
Same as `tf.layers.MaxPooling2D`. Default strides is equal to pool_size.
"""
if strides is None:
strides = pool_size
layer = tf.layers.MaxPooling2D(pool... | [
"def",
"MaxPooling",
"(",
"inputs",
",",
"pool_size",
",",
"strides",
"=",
"None",
",",
"padding",
"=",
"'valid'",
",",
"data_format",
"=",
"'channels_last'",
")",
":",
"if",
"strides",
"is",
"None",
":",
"strides",
"=",
"pool_size",
"layer",
"=",
"tf",
... | Same as `tf.layers.MaxPooling2D`. Default strides is equal to pool_size. | [
"Same",
"as",
"tf",
".",
"layers",
".",
"MaxPooling2D",
".",
"Default",
"strides",
"is",
"equal",
"to",
"pool_size",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/models/pool.py#L21-L34 |
27,335 | tensorpack/tensorpack | tensorpack/models/pool.py | AvgPooling | def AvgPooling(
inputs,
pool_size,
strides=None,
padding='valid',
data_format='channels_last'):
"""
Same as `tf.layers.AveragePooling2D`. Default strides is equal to pool_size.
"""
if strides is None:
strides = pool_size
layer = tf.layers.AveragePoolin... | python | def AvgPooling(
inputs,
pool_size,
strides=None,
padding='valid',
data_format='channels_last'):
"""
Same as `tf.layers.AveragePooling2D`. Default strides is equal to pool_size.
"""
if strides is None:
strides = pool_size
layer = tf.layers.AveragePoolin... | [
"def",
"AvgPooling",
"(",
"inputs",
",",
"pool_size",
",",
"strides",
"=",
"None",
",",
"padding",
"=",
"'valid'",
",",
"data_format",
"=",
"'channels_last'",
")",
":",
"if",
"strides",
"is",
"None",
":",
"strides",
"=",
"pool_size",
"layer",
"=",
"tf",
... | Same as `tf.layers.AveragePooling2D`. Default strides is equal to pool_size. | [
"Same",
"as",
"tf",
".",
"layers",
".",
"AveragePooling2D",
".",
"Default",
"strides",
"is",
"equal",
"to",
"pool_size",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/models/pool.py#L41-L54 |
27,336 | tensorpack/tensorpack | tensorpack/models/pool.py | FixedUnPooling | def FixedUnPooling(x, shape, unpool_mat=None, data_format='channels_last'):
"""
Unpool the input with a fixed matrix to perform kronecker product with.
Args:
x (tf.Tensor): a 4D image tensor
shape: int or (h, w) tuple
unpool_mat: a tf.Tensor or np.ndarray 2D matrix with size=shape.
... | python | def FixedUnPooling(x, shape, unpool_mat=None, data_format='channels_last'):
"""
Unpool the input with a fixed matrix to perform kronecker product with.
Args:
x (tf.Tensor): a 4D image tensor
shape: int or (h, w) tuple
unpool_mat: a tf.Tensor or np.ndarray 2D matrix with size=shape.
... | [
"def",
"FixedUnPooling",
"(",
"x",
",",
"shape",
",",
"unpool_mat",
"=",
"None",
",",
"data_format",
"=",
"'channels_last'",
")",
":",
"data_format",
"=",
"get_data_format",
"(",
"data_format",
",",
"keras_mode",
"=",
"False",
")",
"shape",
"=",
"shape2d",
"... | Unpool the input with a fixed matrix to perform kronecker product with.
Args:
x (tf.Tensor): a 4D image tensor
shape: int or (h, w) tuple
unpool_mat: a tf.Tensor or np.ndarray 2D matrix with size=shape.
If is None, will use a matrix with 1 at top-left corner.
Returns:
... | [
"Unpool",
"the",
"input",
"with",
"a",
"fixed",
"matrix",
"to",
"perform",
"kronecker",
"product",
"with",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/models/pool.py#L91-L140 |
27,337 | tensorpack/tensorpack | tensorpack/tfutils/varmanip.py | save_chkpt_vars | def save_chkpt_vars(dic, path):
"""
Save variables in dic to path.
Args:
dic: {name: value}
path: save as npz if the name ends with '.npz', otherwise save as a checkpoint.
"""
logger.info("Variables to save to {}:".format(path))
keys = sorted(list(dic.keys()))
logger.info(pp... | python | def save_chkpt_vars(dic, path):
"""
Save variables in dic to path.
Args:
dic: {name: value}
path: save as npz if the name ends with '.npz', otherwise save as a checkpoint.
"""
logger.info("Variables to save to {}:".format(path))
keys = sorted(list(dic.keys()))
logger.info(pp... | [
"def",
"save_chkpt_vars",
"(",
"dic",
",",
"path",
")",
":",
"logger",
".",
"info",
"(",
"\"Variables to save to {}:\"",
".",
"format",
"(",
"path",
")",
")",
"keys",
"=",
"sorted",
"(",
"list",
"(",
"dic",
".",
"keys",
"(",
")",
")",
")",
"logger",
... | Save variables in dic to path.
Args:
dic: {name: value}
path: save as npz if the name ends with '.npz', otherwise save as a checkpoint. | [
"Save",
"variables",
"in",
"dic",
"to",
"path",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/tfutils/varmanip.py#L140-L163 |
27,338 | tensorpack/tensorpack | tensorpack/tfutils/varmanip.py | get_checkpoint_path | def get_checkpoint_path(model_path):
"""
Work around TF problems in checkpoint path handling.
Args:
model_path: a user-input path
Returns:
str: the argument that can be passed to NewCheckpointReader
"""
if os.path.basename(model_path) == model_path:
model_path = os.path.... | python | def get_checkpoint_path(model_path):
"""
Work around TF problems in checkpoint path handling.
Args:
model_path: a user-input path
Returns:
str: the argument that can be passed to NewCheckpointReader
"""
if os.path.basename(model_path) == model_path:
model_path = os.path.... | [
"def",
"get_checkpoint_path",
"(",
"model_path",
")",
":",
"if",
"os",
".",
"path",
".",
"basename",
"(",
"model_path",
")",
"==",
"model_path",
":",
"model_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"'.'",
",",
"model_path",
")",
"# avoid #4921 and ... | Work around TF problems in checkpoint path handling.
Args:
model_path: a user-input path
Returns:
str: the argument that can be passed to NewCheckpointReader | [
"Work",
"around",
"TF",
"problems",
"in",
"checkpoint",
"path",
"handling",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/tfutils/varmanip.py#L166-L193 |
27,339 | tensorpack/tensorpack | tensorpack/tfutils/varmanip.py | load_chkpt_vars | def load_chkpt_vars(model_path):
""" Load all variables from a checkpoint to a dict.
Args:
model_path(str): path to a checkpoint.
Returns:
dict: a name:value dict
"""
model_path = get_checkpoint_path(model_path)
reader = tfv1.train.NewCheckpointReader(model_path)
var_names ... | python | def load_chkpt_vars(model_path):
""" Load all variables from a checkpoint to a dict.
Args:
model_path(str): path to a checkpoint.
Returns:
dict: a name:value dict
"""
model_path = get_checkpoint_path(model_path)
reader = tfv1.train.NewCheckpointReader(model_path)
var_names ... | [
"def",
"load_chkpt_vars",
"(",
"model_path",
")",
":",
"model_path",
"=",
"get_checkpoint_path",
"(",
"model_path",
")",
"reader",
"=",
"tfv1",
".",
"train",
".",
"NewCheckpointReader",
"(",
"model_path",
")",
"var_names",
"=",
"reader",
".",
"get_variable_to_shap... | Load all variables from a checkpoint to a dict.
Args:
model_path(str): path to a checkpoint.
Returns:
dict: a name:value dict | [
"Load",
"all",
"variables",
"from",
"a",
"checkpoint",
"to",
"a",
"dict",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/tfutils/varmanip.py#L196-L211 |
27,340 | tensorpack/tensorpack | tensorpack/callbacks/monitor.py | Monitors.put_summary | def put_summary(self, summary):
"""
Put a `tf.Summary`.
"""
if isinstance(summary, six.binary_type):
summary = tf.Summary.FromString(summary)
assert isinstance(summary, tf.Summary), type(summary)
# TODO other types
for val in summary.value:
... | python | def put_summary(self, summary):
"""
Put a `tf.Summary`.
"""
if isinstance(summary, six.binary_type):
summary = tf.Summary.FromString(summary)
assert isinstance(summary, tf.Summary), type(summary)
# TODO other types
for val in summary.value:
... | [
"def",
"put_summary",
"(",
"self",
",",
"summary",
")",
":",
"if",
"isinstance",
"(",
"summary",
",",
"six",
".",
"binary_type",
")",
":",
"summary",
"=",
"tf",
".",
"Summary",
".",
"FromString",
"(",
"summary",
")",
"assert",
"isinstance",
"(",
"summary... | Put a `tf.Summary`. | [
"Put",
"a",
"tf",
".",
"Summary",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/callbacks/monitor.py#L143-L164 |
27,341 | tensorpack/tensorpack | tensorpack/callbacks/monitor.py | Monitors.put_scalar | def put_scalar(self, name, val):
"""
Put a scalar.
"""
if isinstance(val, np.floating):
val = float(val)
if isinstance(val, np.integer):
val = int(val)
self._dispatch(lambda m: m.process_scalar(name, val))
s = create_scalar_summary(name, va... | python | def put_scalar(self, name, val):
"""
Put a scalar.
"""
if isinstance(val, np.floating):
val = float(val)
if isinstance(val, np.integer):
val = int(val)
self._dispatch(lambda m: m.process_scalar(name, val))
s = create_scalar_summary(name, va... | [
"def",
"put_scalar",
"(",
"self",
",",
"name",
",",
"val",
")",
":",
"if",
"isinstance",
"(",
"val",
",",
"np",
".",
"floating",
")",
":",
"val",
"=",
"float",
"(",
"val",
")",
"if",
"isinstance",
"(",
"val",
",",
"np",
".",
"integer",
")",
":",
... | Put a scalar. | [
"Put",
"a",
"scalar",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/callbacks/monitor.py#L166-L176 |
27,342 | tensorpack/tensorpack | tensorpack/callbacks/monitor.py | Monitors.put_image | def put_image(self, name, val):
"""
Put an image.
Args:
name (str):
val (np.ndarray): 2D, 3D (HWC) or 4D (NHWC) numpy array of images
in range [0,255]. If channel is 3, assumed to be RGB.
"""
assert isinstance(val, np.ndarray)
arr ... | python | def put_image(self, name, val):
"""
Put an image.
Args:
name (str):
val (np.ndarray): 2D, 3D (HWC) or 4D (NHWC) numpy array of images
in range [0,255]. If channel is 3, assumed to be RGB.
"""
assert isinstance(val, np.ndarray)
arr ... | [
"def",
"put_image",
"(",
"self",
",",
"name",
",",
"val",
")",
":",
"assert",
"isinstance",
"(",
"val",
",",
"np",
".",
"ndarray",
")",
"arr",
"=",
"image_to_nhwc",
"(",
"val",
")",
"self",
".",
"_dispatch",
"(",
"lambda",
"m",
":",
"m",
".",
"proc... | Put an image.
Args:
name (str):
val (np.ndarray): 2D, 3D (HWC) or 4D (NHWC) numpy array of images
in range [0,255]. If channel is 3, assumed to be RGB. | [
"Put",
"an",
"image",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/callbacks/monitor.py#L178-L191 |
27,343 | tensorpack/tensorpack | tensorpack/callbacks/monitor.py | JSONWriter._trigger | def _trigger(self):
"""
Add stats to json and dump to disk.
Note that this method is idempotent.
"""
if len(self._stat_now):
self._stat_now['epoch_num'] = self.epoch_num
self._stat_now['global_step'] = self.global_step
self._stats.append(self.... | python | def _trigger(self):
"""
Add stats to json and dump to disk.
Note that this method is idempotent.
"""
if len(self._stat_now):
self._stat_now['epoch_num'] = self.epoch_num
self._stat_now['global_step'] = self.global_step
self._stats.append(self.... | [
"def",
"_trigger",
"(",
"self",
")",
":",
"if",
"len",
"(",
"self",
".",
"_stat_now",
")",
":",
"self",
".",
"_stat_now",
"[",
"'epoch_num'",
"]",
"=",
"self",
".",
"epoch_num",
"self",
".",
"_stat_now",
"[",
"'global_step'",
"]",
"=",
"self",
".",
"... | Add stats to json and dump to disk.
Note that this method is idempotent. | [
"Add",
"stats",
"to",
"json",
"and",
"dump",
"to",
"disk",
".",
"Note",
"that",
"this",
"method",
"is",
"idempotent",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/callbacks/monitor.py#L378-L389 |
27,344 | tensorpack/tensorpack | tensorpack/utils/debug.py | enable_call_trace | def enable_call_trace():
""" Enable trace for calls to any function. """
def tracer(frame, event, arg):
if event == 'call':
co = frame.f_code
func_name = co.co_name
if func_name == 'write' or func_name == 'print':
# ignore write() calls from print stat... | python | def enable_call_trace():
""" Enable trace for calls to any function. """
def tracer(frame, event, arg):
if event == 'call':
co = frame.f_code
func_name = co.co_name
if func_name == 'write' or func_name == 'print':
# ignore write() calls from print stat... | [
"def",
"enable_call_trace",
"(",
")",
":",
"def",
"tracer",
"(",
"frame",
",",
"event",
",",
"arg",
")",
":",
"if",
"event",
"==",
"'call'",
":",
"co",
"=",
"frame",
".",
"f_code",
"func_name",
"=",
"co",
".",
"co_name",
"if",
"func_name",
"==",
"'wr... | Enable trace for calls to any function. | [
"Enable",
"trace",
"for",
"calls",
"to",
"any",
"function",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/debug.py#L8-L27 |
27,345 | tensorpack/tensorpack | tensorpack/train/base.py | _get_property | def _get_property(name):
"""
Delegate property to self.loop
"""
ret = property(
lambda self: getattr(self.loop, name))
if six.PY3: # __doc__ is readonly in Py2
try:
ret.__doc__ = getattr(TrainLoop, name).__doc__
except AttributeError:
pass
retu... | python | def _get_property(name):
"""
Delegate property to self.loop
"""
ret = property(
lambda self: getattr(self.loop, name))
if six.PY3: # __doc__ is readonly in Py2
try:
ret.__doc__ = getattr(TrainLoop, name).__doc__
except AttributeError:
pass
retu... | [
"def",
"_get_property",
"(",
"name",
")",
":",
"ret",
"=",
"property",
"(",
"lambda",
"self",
":",
"getattr",
"(",
"self",
".",
"loop",
",",
"name",
")",
")",
"if",
"six",
".",
"PY3",
":",
"# __doc__ is readonly in Py2",
"try",
":",
"ret",
".",
"__doc_... | Delegate property to self.loop | [
"Delegate",
"property",
"to",
"self",
".",
"loop"
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/train/base.py#L357-L368 |
27,346 | tensorpack/tensorpack | tensorpack/train/base.py | TrainLoop.config | def config(self, steps_per_epoch, starting_epoch, max_epoch):
"""
Configure the loop given the settings.
"""
self.starting_epoch = int(starting_epoch)
self.max_epoch = int(max_epoch)
self.steps_per_epoch = int(steps_per_epoch)
# Allow empty epoch (no steps), if we... | python | def config(self, steps_per_epoch, starting_epoch, max_epoch):
"""
Configure the loop given the settings.
"""
self.starting_epoch = int(starting_epoch)
self.max_epoch = int(max_epoch)
self.steps_per_epoch = int(steps_per_epoch)
# Allow empty epoch (no steps), if we... | [
"def",
"config",
"(",
"self",
",",
"steps_per_epoch",
",",
"starting_epoch",
",",
"max_epoch",
")",
":",
"self",
".",
"starting_epoch",
"=",
"int",
"(",
"starting_epoch",
")",
"self",
".",
"max_epoch",
"=",
"int",
"(",
"max_epoch",
")",
"self",
".",
"steps... | Configure the loop given the settings. | [
"Configure",
"the",
"loop",
"given",
"the",
"settings",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/train/base.py#L43-L53 |
27,347 | tensorpack/tensorpack | tensorpack/train/base.py | Trainer.setup_callbacks | def setup_callbacks(self, callbacks, monitors):
"""
Setup callbacks and monitors. Must be called after the main graph is built.
Args:
callbacks ([Callback]):
monitors ([MonitorBase]):
"""
assert isinstance(callbacks, list), callbacks
assert isinst... | python | def setup_callbacks(self, callbacks, monitors):
"""
Setup callbacks and monitors. Must be called after the main graph is built.
Args:
callbacks ([Callback]):
monitors ([MonitorBase]):
"""
assert isinstance(callbacks, list), callbacks
assert isinst... | [
"def",
"setup_callbacks",
"(",
"self",
",",
"callbacks",
",",
"monitors",
")",
":",
"assert",
"isinstance",
"(",
"callbacks",
",",
"list",
")",
",",
"callbacks",
"assert",
"isinstance",
"(",
"monitors",
",",
"list",
")",
",",
"monitors",
"describe_trainable_va... | Setup callbacks and monitors. Must be called after the main graph is built.
Args:
callbacks ([Callback]):
monitors ([MonitorBase]): | [
"Setup",
"callbacks",
"and",
"monitors",
".",
"Must",
"be",
"called",
"after",
"the",
"main",
"graph",
"is",
"built",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/train/base.py#L184-L211 |
27,348 | tensorpack/tensorpack | tensorpack/train/base.py | Trainer.initialize_hooks | def initialize_hooks(self):
"""
Create SessionRunHooks for all callbacks, and hook it onto `self.sess` to create `self.hooked_sess`.
A new trainer may override this method to create multiple groups of hooks,
which can be useful when the training is not done by a single `train_op`.
... | python | def initialize_hooks(self):
"""
Create SessionRunHooks for all callbacks, and hook it onto `self.sess` to create `self.hooked_sess`.
A new trainer may override this method to create multiple groups of hooks,
which can be useful when the training is not done by a single `train_op`.
... | [
"def",
"initialize_hooks",
"(",
"self",
")",
":",
"hooks",
"=",
"self",
".",
"_callbacks",
".",
"get_hooks",
"(",
")",
"self",
".",
"hooked_sess",
"=",
"tfv1",
".",
"train",
".",
"MonitoredSession",
"(",
"session_creator",
"=",
"ReuseSessionCreator",
"(",
"s... | Create SessionRunHooks for all callbacks, and hook it onto `self.sess` to create `self.hooked_sess`.
A new trainer may override this method to create multiple groups of hooks,
which can be useful when the training is not done by a single `train_op`. | [
"Create",
"SessionRunHooks",
"for",
"all",
"callbacks",
"and",
"hook",
"it",
"onto",
"self",
".",
"sess",
"to",
"create",
"self",
".",
"hooked_sess",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/train/base.py#L246-L255 |
27,349 | tensorpack/tensorpack | tensorpack/tfutils/common.py | get_default_sess_config | def get_default_sess_config(mem_fraction=0.99):
"""
Return a tf.ConfigProto to use as default session config.
You can modify the returned config to fit your needs.
Args:
mem_fraction(float): see the `per_process_gpu_memory_fraction` option
in TensorFlow's GPUOptions protobuf:
... | python | def get_default_sess_config(mem_fraction=0.99):
"""
Return a tf.ConfigProto to use as default session config.
You can modify the returned config to fit your needs.
Args:
mem_fraction(float): see the `per_process_gpu_memory_fraction` option
in TensorFlow's GPUOptions protobuf:
... | [
"def",
"get_default_sess_config",
"(",
"mem_fraction",
"=",
"0.99",
")",
":",
"conf",
"=",
"tfv1",
".",
"ConfigProto",
"(",
")",
"conf",
".",
"allow_soft_placement",
"=",
"True",
"# conf.log_device_placement = True",
"conf",
".",
"intra_op_parallelism_threads",
"=",
... | Return a tf.ConfigProto to use as default session config.
You can modify the returned config to fit your needs.
Args:
mem_fraction(float): see the `per_process_gpu_memory_fraction` option
in TensorFlow's GPUOptions protobuf:
https://github.com/tensorflow/tensorflow/blob/master/t... | [
"Return",
"a",
"tf",
".",
"ConfigProto",
"to",
"use",
"as",
"default",
"session",
"config",
".",
"You",
"can",
"modify",
"the",
"returned",
"config",
"to",
"fit",
"your",
"needs",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/tfutils/common.py#L30-L68 |
27,350 | tensorpack/tensorpack | tensorpack/tfutils/common.py | get_tensors_by_names | def get_tensors_by_names(names):
"""
Get a list of tensors in the default graph by a list of names.
Args:
names (list):
"""
ret = []
G = tfv1.get_default_graph()
for n in names:
opn, varn = get_op_tensor_name(n)
ret.append(G.get_tensor_by_name(varn))
return ret | python | def get_tensors_by_names(names):
"""
Get a list of tensors in the default graph by a list of names.
Args:
names (list):
"""
ret = []
G = tfv1.get_default_graph()
for n in names:
opn, varn = get_op_tensor_name(n)
ret.append(G.get_tensor_by_name(varn))
return ret | [
"def",
"get_tensors_by_names",
"(",
"names",
")",
":",
"ret",
"=",
"[",
"]",
"G",
"=",
"tfv1",
".",
"get_default_graph",
"(",
")",
"for",
"n",
"in",
"names",
":",
"opn",
",",
"varn",
"=",
"get_op_tensor_name",
"(",
"n",
")",
"ret",
".",
"append",
"("... | Get a list of tensors in the default graph by a list of names.
Args:
names (list): | [
"Get",
"a",
"list",
"of",
"tensors",
"in",
"the",
"default",
"graph",
"by",
"a",
"list",
"of",
"names",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/tfutils/common.py#L113-L125 |
27,351 | tensorpack/tensorpack | tensorpack/tfutils/common.py | get_op_or_tensor_by_name | def get_op_or_tensor_by_name(name):
"""
Get either tf.Operation of tf.Tensor from names.
Args:
name (list[str] or str): names of operations or tensors.
Raises:
KeyError, if the name doesn't exist
"""
G = tfv1.get_default_graph()
def f(n):
if len(n) >= 3 and n[-2] =... | python | def get_op_or_tensor_by_name(name):
"""
Get either tf.Operation of tf.Tensor from names.
Args:
name (list[str] or str): names of operations or tensors.
Raises:
KeyError, if the name doesn't exist
"""
G = tfv1.get_default_graph()
def f(n):
if len(n) >= 3 and n[-2] =... | [
"def",
"get_op_or_tensor_by_name",
"(",
"name",
")",
":",
"G",
"=",
"tfv1",
".",
"get_default_graph",
"(",
")",
"def",
"f",
"(",
"n",
")",
":",
"if",
"len",
"(",
"n",
")",
">=",
"3",
"and",
"n",
"[",
"-",
"2",
"]",
"==",
"':'",
":",
"return",
"... | Get either tf.Operation of tf.Tensor from names.
Args:
name (list[str] or str): names of operations or tensors.
Raises:
KeyError, if the name doesn't exist | [
"Get",
"either",
"tf",
".",
"Operation",
"of",
"tf",
".",
"Tensor",
"from",
"names",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/tfutils/common.py#L128-L149 |
27,352 | tensorpack/tensorpack | tensorpack/graph_builder/distributed.py | DistributedBuilderBase._add_sync_queues_and_barrier | def _add_sync_queues_and_barrier(self, name, dependencies):
"""Adds ops to enqueue on all worker queues.
Args:
name: prefixed for the shared_name of ops.
dependencies: control dependency from ops.
Returns:
an op that should be used as control dependency befo... | python | def _add_sync_queues_and_barrier(self, name, dependencies):
"""Adds ops to enqueue on all worker queues.
Args:
name: prefixed for the shared_name of ops.
dependencies: control dependency from ops.
Returns:
an op that should be used as control dependency befo... | [
"def",
"_add_sync_queues_and_barrier",
"(",
"self",
",",
"name",
",",
"dependencies",
")",
":",
"self",
".",
"_sync_queue_counter",
"+=",
"1",
"with",
"tf",
".",
"device",
"(",
"self",
".",
"sync_queue_devices",
"[",
"self",
".",
"_sync_queue_counter",
"%",
"l... | Adds ops to enqueue on all worker queues.
Args:
name: prefixed for the shared_name of ops.
dependencies: control dependency from ops.
Returns:
an op that should be used as control dependency before starting next step. | [
"Adds",
"ops",
"to",
"enqueue",
"on",
"all",
"worker",
"queues",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/graph_builder/distributed.py#L30-L58 |
27,353 | tensorpack/tensorpack | tensorpack/graph_builder/distributed.py | DistributedReplicatedBuilder._apply_shadow_vars | def _apply_shadow_vars(avg_grads):
"""
Create shadow variables on PS, and replace variables in avg_grads
by these shadow variables.
Args:
avg_grads: list of (grad, var) tuples
"""
ps_var_grads = []
for grad, var in avg_grads:
assert var.na... | python | def _apply_shadow_vars(avg_grads):
"""
Create shadow variables on PS, and replace variables in avg_grads
by these shadow variables.
Args:
avg_grads: list of (grad, var) tuples
"""
ps_var_grads = []
for grad, var in avg_grads:
assert var.na... | [
"def",
"_apply_shadow_vars",
"(",
"avg_grads",
")",
":",
"ps_var_grads",
"=",
"[",
"]",
"for",
"grad",
",",
"var",
"in",
"avg_grads",
":",
"assert",
"var",
".",
"name",
".",
"startswith",
"(",
"'tower'",
")",
",",
"var",
".",
"name",
"my_name",
"=",
"'... | Create shadow variables on PS, and replace variables in avg_grads
by these shadow variables.
Args:
avg_grads: list of (grad, var) tuples | [
"Create",
"shadow",
"variables",
"on",
"PS",
"and",
"replace",
"variables",
"in",
"avg_grads",
"by",
"these",
"shadow",
"variables",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/graph_builder/distributed.py#L205-L223 |
27,354 | tensorpack/tensorpack | tensorpack/graph_builder/distributed.py | DistributedReplicatedBuilder._shadow_model_variables | def _shadow_model_variables(shadow_vars):
"""
Create shadow vars for model_variables as well, and add to the list of ``shadow_vars``.
Returns:
list of (shadow_model_var, local_model_var) used for syncing.
"""
G = tf.get_default_graph()
curr_shadow_vars = set(... | python | def _shadow_model_variables(shadow_vars):
"""
Create shadow vars for model_variables as well, and add to the list of ``shadow_vars``.
Returns:
list of (shadow_model_var, local_model_var) used for syncing.
"""
G = tf.get_default_graph()
curr_shadow_vars = set(... | [
"def",
"_shadow_model_variables",
"(",
"shadow_vars",
")",
":",
"G",
"=",
"tf",
".",
"get_default_graph",
"(",
")",
"curr_shadow_vars",
"=",
"set",
"(",
"[",
"v",
".",
"name",
"for",
"v",
"in",
"shadow_vars",
"]",
")",
"model_vars",
"=",
"tf",
".",
"mode... | Create shadow vars for model_variables as well, and add to the list of ``shadow_vars``.
Returns:
list of (shadow_model_var, local_model_var) used for syncing. | [
"Create",
"shadow",
"vars",
"for",
"model_variables",
"as",
"well",
"and",
"add",
"to",
"the",
"list",
"of",
"shadow_vars",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/graph_builder/distributed.py#L226-L255 |
27,355 | tensorpack/tensorpack | tensorpack/graph_builder/distributed.py | DistributedReplicatedBuilder._apply_gradients_and_copy | def _apply_gradients_and_copy(self, opt, raw_grad_list, ps_var_grads):
"""
Apply averaged gradients to ps vars, and then copy the updated
variables back to each tower.
Args:
raw_grad_list: Ngpu x Nvar x 2 gradient list from all towers
ps_var_grads: Nvar x 2 (grad... | python | def _apply_gradients_and_copy(self, opt, raw_grad_list, ps_var_grads):
"""
Apply averaged gradients to ps vars, and then copy the updated
variables back to each tower.
Args:
raw_grad_list: Ngpu x Nvar x 2 gradient list from all towers
ps_var_grads: Nvar x 2 (grad... | [
"def",
"_apply_gradients_and_copy",
"(",
"self",
",",
"opt",
",",
"raw_grad_list",
",",
"ps_var_grads",
")",
":",
"# TODO do this for variables together?",
"with",
"tf",
".",
"name_scope",
"(",
"'apply_gradients'",
")",
":",
"var_update_ops",
"=",
"[",
"]",
"for",
... | Apply averaged gradients to ps vars, and then copy the updated
variables back to each tower.
Args:
raw_grad_list: Ngpu x Nvar x 2 gradient list from all towers
ps_var_grads: Nvar x 2 (grad, ps_var)
Returns:
list of copy ops | [
"Apply",
"averaged",
"gradients",
"to",
"ps",
"vars",
"and",
"then",
"copy",
"the",
"updated",
"variables",
"back",
"to",
"each",
"tower",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/graph_builder/distributed.py#L313-L339 |
27,356 | tensorpack/tensorpack | tensorpack/graph_builder/distributed.py | DistributedReplicatedBuilder._get_initial_sync_op | def _get_initial_sync_op(self):
"""
Get the op to copy-initialized all local variables from PS.
"""
def strip_port(s):
if s.endswith(':0'):
return s[:-2]
return s
local_vars = tf.local_variables()
local_var_by_name = dict([(strip_po... | python | def _get_initial_sync_op(self):
"""
Get the op to copy-initialized all local variables from PS.
"""
def strip_port(s):
if s.endswith(':0'):
return s[:-2]
return s
local_vars = tf.local_variables()
local_var_by_name = dict([(strip_po... | [
"def",
"_get_initial_sync_op",
"(",
"self",
")",
":",
"def",
"strip_port",
"(",
"s",
")",
":",
"if",
"s",
".",
"endswith",
"(",
"':0'",
")",
":",
"return",
"s",
"[",
":",
"-",
"2",
"]",
"return",
"s",
"local_vars",
"=",
"tf",
".",
"local_variables",
... | Get the op to copy-initialized all local variables from PS. | [
"Get",
"the",
"op",
"to",
"copy",
"-",
"initialized",
"all",
"local",
"variables",
"from",
"PS",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/graph_builder/distributed.py#L341-L362 |
27,357 | tensorpack/tensorpack | tensorpack/graph_builder/distributed.py | DistributedReplicatedBuilder._get_sync_model_vars_op | def _get_sync_model_vars_op(self):
"""
Get the op to sync local model_variables to PS.
"""
ops = []
for (shadow_v, local_v) in self._shadow_model_vars:
ops.append(shadow_v.assign(local_v.read_value()))
assert len(ops)
return tf.group(*ops, name='sync_{... | python | def _get_sync_model_vars_op(self):
"""
Get the op to sync local model_variables to PS.
"""
ops = []
for (shadow_v, local_v) in self._shadow_model_vars:
ops.append(shadow_v.assign(local_v.read_value()))
assert len(ops)
return tf.group(*ops, name='sync_{... | [
"def",
"_get_sync_model_vars_op",
"(",
"self",
")",
":",
"ops",
"=",
"[",
"]",
"for",
"(",
"shadow_v",
",",
"local_v",
")",
"in",
"self",
".",
"_shadow_model_vars",
":",
"ops",
".",
"append",
"(",
"shadow_v",
".",
"assign",
"(",
"local_v",
".",
"read_val... | Get the op to sync local model_variables to PS. | [
"Get",
"the",
"op",
"to",
"sync",
"local",
"model_variables",
"to",
"PS",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/graph_builder/distributed.py#L364-L372 |
27,358 | tensorpack/tensorpack | tensorpack/callbacks/summary.py | MergeAllSummaries | def MergeAllSummaries(period=0, run_alone=False, key=None):
"""
This callback is enabled by default.
Evaluate all summaries by ``tf.summary.merge_all``, and write them to logs.
Args:
period (int): by default the callback summarizes once every epoch.
This option (if not set to 0) mak... | python | def MergeAllSummaries(period=0, run_alone=False, key=None):
"""
This callback is enabled by default.
Evaluate all summaries by ``tf.summary.merge_all``, and write them to logs.
Args:
period (int): by default the callback summarizes once every epoch.
This option (if not set to 0) mak... | [
"def",
"MergeAllSummaries",
"(",
"period",
"=",
"0",
",",
"run_alone",
"=",
"False",
",",
"key",
"=",
"None",
")",
":",
"if",
"key",
"is",
"None",
":",
"key",
"=",
"tf",
".",
"GraphKeys",
".",
"SUMMARIES",
"period",
"=",
"int",
"(",
"period",
")",
... | This callback is enabled by default.
Evaluate all summaries by ``tf.summary.merge_all``, and write them to logs.
Args:
period (int): by default the callback summarizes once every epoch.
This option (if not set to 0) makes it additionally summarize every ``period`` steps.
run_alone (... | [
"This",
"callback",
"is",
"enabled",
"by",
"default",
".",
"Evaluate",
"all",
"summaries",
"by",
"tf",
".",
"summary",
".",
"merge_all",
"and",
"write",
"them",
"to",
"logs",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/callbacks/summary.py#L119-L142 |
27,359 | tensorpack/tensorpack | examples/DeepQNetwork/expreplay.py | EnvRunner.step | def step(self, exploration):
"""
Run the environment for one step.
If the episode ends, store the entire episode to the replay memory.
"""
old_s = self._current_ob
if self.rng.rand() <= exploration:
act = self.rng.choice(range(self.num_actions))
else:
... | python | def step(self, exploration):
"""
Run the environment for one step.
If the episode ends, store the entire episode to the replay memory.
"""
old_s = self._current_ob
if self.rng.rand() <= exploration:
act = self.rng.choice(range(self.num_actions))
else:
... | [
"def",
"step",
"(",
"self",
",",
"exploration",
")",
":",
"old_s",
"=",
"self",
".",
"_current_ob",
"if",
"self",
".",
"rng",
".",
"rand",
"(",
")",
"<=",
"exploration",
":",
"act",
"=",
"self",
".",
"rng",
".",
"choice",
"(",
"range",
"(",
"self",... | Run the environment for one step.
If the episode ends, store the entire episode to the replay memory. | [
"Run",
"the",
"environment",
"for",
"one",
"step",
".",
"If",
"the",
"episode",
"ends",
"store",
"the",
"entire",
"episode",
"to",
"the",
"replay",
"memory",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/DeepQNetwork/expreplay.py#L143-L182 |
27,360 | tensorpack/tensorpack | examples/DeepQNetwork/expreplay.py | EnvRunnerManager.step | def step(self, exploration):
"""
Execute one step in any of the runners.
"""
if len(self._runners) > 1:
self._populate_job_queue.put(exploration)
else:
self._runners[0].step(exploration) | python | def step(self, exploration):
"""
Execute one step in any of the runners.
"""
if len(self._runners) > 1:
self._populate_job_queue.put(exploration)
else:
self._runners[0].step(exploration) | [
"def",
"step",
"(",
"self",
",",
"exploration",
")",
":",
"if",
"len",
"(",
"self",
".",
"_runners",
")",
">",
"1",
":",
"self",
".",
"_populate_job_queue",
".",
"put",
"(",
"exploration",
")",
"else",
":",
"self",
".",
"_runners",
"[",
"0",
"]",
"... | Execute one step in any of the runners. | [
"Execute",
"one",
"step",
"in",
"any",
"of",
"the",
"runners",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/DeepQNetwork/expreplay.py#L233-L240 |
27,361 | tensorpack/tensorpack | tensorpack/callbacks/group.py | CallbackTimeLogger.log | def log(self):
""" log the time of some heavy callbacks """
if self.tot < 3:
return
msgs = []
for name, t in self.times:
if t / self.tot > 0.3 and t > 1:
msgs.append(name + ": " + humanize_time_delta(t))
logger.info(
"Callbacks... | python | def log(self):
""" log the time of some heavy callbacks """
if self.tot < 3:
return
msgs = []
for name, t in self.times:
if t / self.tot > 0.3 and t > 1:
msgs.append(name + ": " + humanize_time_delta(t))
logger.info(
"Callbacks... | [
"def",
"log",
"(",
"self",
")",
":",
"if",
"self",
".",
"tot",
"<",
"3",
":",
"return",
"msgs",
"=",
"[",
"]",
"for",
"name",
",",
"t",
"in",
"self",
".",
"times",
":",
"if",
"t",
"/",
"self",
".",
"tot",
">",
"0.3",
"and",
"t",
">",
"1",
... | log the time of some heavy callbacks | [
"log",
"the",
"time",
"of",
"some",
"heavy",
"callbacks"
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/callbacks/group.py#L37-L48 |
27,362 | tensorpack/tensorpack | tensorpack/tfutils/tower.py | TowerTensorHandle.get_variable | def get_variable(self, name):
"""
Get a variable used in this tower.
The name should not contain the variable scope prefix of the tower.
When the tower has the same variable scope and name scope, this is equivalent to
:meth:`get_tensor`.
"""
name = get_op_tensor_... | python | def get_variable(self, name):
"""
Get a variable used in this tower.
The name should not contain the variable scope prefix of the tower.
When the tower has the same variable scope and name scope, this is equivalent to
:meth:`get_tensor`.
"""
name = get_op_tensor_... | [
"def",
"get_variable",
"(",
"self",
",",
"name",
")",
":",
"name",
"=",
"get_op_tensor_name",
"(",
"name",
")",
"[",
"1",
"]",
"if",
"len",
"(",
"self",
".",
"vs_name",
")",
":",
"name_with_vs",
"=",
"self",
".",
"vs_name",
"+",
"\"/\"",
"+",
"name",... | Get a variable used in this tower.
The name should not contain the variable scope prefix of the tower.
When the tower has the same variable scope and name scope, this is equivalent to
:meth:`get_tensor`. | [
"Get",
"a",
"variable",
"used",
"in",
"this",
"tower",
".",
"The",
"name",
"should",
"not",
"contain",
"the",
"variable",
"scope",
"prefix",
"of",
"the",
"tower",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/tfutils/tower.py#L429-L442 |
27,363 | tensorpack/tensorpack | tensorpack/utils/fs.py | mkdir_p | def mkdir_p(dirname):
""" Like "mkdir -p", make a dir recursively, but do nothing if the dir exists
Args:
dirname(str):
"""
assert dirname is not None
if dirname == '' or os.path.isdir(dirname):
return
try:
os.makedirs(dirname)
except OSError as e:
if e.errno... | python | def mkdir_p(dirname):
""" Like "mkdir -p", make a dir recursively, but do nothing if the dir exists
Args:
dirname(str):
"""
assert dirname is not None
if dirname == '' or os.path.isdir(dirname):
return
try:
os.makedirs(dirname)
except OSError as e:
if e.errno... | [
"def",
"mkdir_p",
"(",
"dirname",
")",
":",
"assert",
"dirname",
"is",
"not",
"None",
"if",
"dirname",
"==",
"''",
"or",
"os",
".",
"path",
".",
"isdir",
"(",
"dirname",
")",
":",
"return",
"try",
":",
"os",
".",
"makedirs",
"(",
"dirname",
")",
"e... | Like "mkdir -p", make a dir recursively, but do nothing if the dir exists
Args:
dirname(str): | [
"Like",
"mkdir",
"-",
"p",
"make",
"a",
"dir",
"recursively",
"but",
"do",
"nothing",
"if",
"the",
"dir",
"exists"
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/fs.py#L16-L29 |
27,364 | tensorpack/tensorpack | tensorpack/utils/fs.py | download | def download(url, dir, filename=None, expect_size=None):
"""
Download URL to a directory.
Will figure out the filename automatically from URL, if not given.
"""
mkdir_p(dir)
if filename is None:
filename = url.split('/')[-1]
fpath = os.path.join(dir, filename)
if os.path.isfile(... | python | def download(url, dir, filename=None, expect_size=None):
"""
Download URL to a directory.
Will figure out the filename automatically from URL, if not given.
"""
mkdir_p(dir)
if filename is None:
filename = url.split('/')[-1]
fpath = os.path.join(dir, filename)
if os.path.isfile(... | [
"def",
"download",
"(",
"url",
",",
"dir",
",",
"filename",
"=",
"None",
",",
"expect_size",
"=",
"None",
")",
":",
"mkdir_p",
"(",
"dir",
")",
"if",
"filename",
"is",
"None",
":",
"filename",
"=",
"url",
".",
"split",
"(",
"'/'",
")",
"[",
"-",
... | Download URL to a directory.
Will figure out the filename automatically from URL, if not given. | [
"Download",
"URL",
"to",
"a",
"directory",
".",
"Will",
"figure",
"out",
"the",
"filename",
"automatically",
"from",
"URL",
"if",
"not",
"given",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/fs.py#L32-L74 |
27,365 | tensorpack/tensorpack | tensorpack/tfutils/collection.py | restore_collection | def restore_collection(backup):
"""
Restore from a collection backup.
Args:
backup (dict):
"""
for k, v in six.iteritems(backup):
del tf.get_collection_ref(k)[:]
tf.get_collection_ref(k).extend(v) | python | def restore_collection(backup):
"""
Restore from a collection backup.
Args:
backup (dict):
"""
for k, v in six.iteritems(backup):
del tf.get_collection_ref(k)[:]
tf.get_collection_ref(k).extend(v) | [
"def",
"restore_collection",
"(",
"backup",
")",
":",
"for",
"k",
",",
"v",
"in",
"six",
".",
"iteritems",
"(",
"backup",
")",
":",
"del",
"tf",
".",
"get_collection_ref",
"(",
"k",
")",
"[",
":",
"]",
"tf",
".",
"get_collection_ref",
"(",
"k",
")",
... | Restore from a collection backup.
Args:
backup (dict): | [
"Restore",
"from",
"a",
"collection",
"backup",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/tfutils/collection.py#L37-L46 |
27,366 | tensorpack/tensorpack | tensorpack/tfutils/collection.py | CollectionGuard.get_collection_in_tower | def get_collection_in_tower(self, key):
"""
Get items from this collection that are added in the current tower.
"""
new = tf.get_collection(key)
old = set(self.original.get(key, []))
# persist the order in new
return [x for x in new if x not in old] | python | def get_collection_in_tower(self, key):
"""
Get items from this collection that are added in the current tower.
"""
new = tf.get_collection(key)
old = set(self.original.get(key, []))
# persist the order in new
return [x for x in new if x not in old] | [
"def",
"get_collection_in_tower",
"(",
"self",
",",
"key",
")",
":",
"new",
"=",
"tf",
".",
"get_collection",
"(",
"key",
")",
"old",
"=",
"set",
"(",
"self",
".",
"original",
".",
"get",
"(",
"key",
",",
"[",
"]",
")",
")",
"# persist the order in new... | Get items from this collection that are added in the current tower. | [
"Get",
"items",
"from",
"this",
"collection",
"that",
"are",
"added",
"in",
"the",
"current",
"tower",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/tfutils/collection.py#L168-L175 |
27,367 | tensorpack/tensorpack | examples/PennTreebank/reader.py | ptb_producer | def ptb_producer(raw_data, batch_size, num_steps, name=None):
"""Iterate on the raw PTB data.
This chunks up raw_data into batches of examples and returns Tensors that
are drawn from these batches.
Args:
raw_data: one of the raw data outputs from ptb_raw_data.
batch_size: int, the batch size.
num_... | python | def ptb_producer(raw_data, batch_size, num_steps, name=None):
"""Iterate on the raw PTB data.
This chunks up raw_data into batches of examples and returns Tensors that
are drawn from these batches.
Args:
raw_data: one of the raw data outputs from ptb_raw_data.
batch_size: int, the batch size.
num_... | [
"def",
"ptb_producer",
"(",
"raw_data",
",",
"batch_size",
",",
"num_steps",
",",
"name",
"=",
"None",
")",
":",
"with",
"tf",
".",
"name_scope",
"(",
"name",
",",
"\"PTBProducer\"",
",",
"[",
"raw_data",
",",
"batch_size",
",",
"num_steps",
"]",
")",
":... | Iterate on the raw PTB data.
This chunks up raw_data into batches of examples and returns Tensors that
are drawn from these batches.
Args:
raw_data: one of the raw data outputs from ptb_raw_data.
batch_size: int, the batch size.
num_steps: int, the number of unrolls.
name: the name of this opera... | [
"Iterate",
"on",
"the",
"raw",
"PTB",
"data",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/PennTreebank/reader.py#L78-L119 |
27,368 | tensorpack/tensorpack | examples/HED/hed.py | CaffeBilinearUpSample | def CaffeBilinearUpSample(x, shape):
"""
Deterministic bilinearly-upsample the input images.
It is implemented by deconvolution with "BilinearFiller" in Caffe.
It is aimed to mimic caffe behavior.
Args:
x (tf.Tensor): a NCHW tensor
shape (int): the upsample factor
Returns:
... | python | def CaffeBilinearUpSample(x, shape):
"""
Deterministic bilinearly-upsample the input images.
It is implemented by deconvolution with "BilinearFiller" in Caffe.
It is aimed to mimic caffe behavior.
Args:
x (tf.Tensor): a NCHW tensor
shape (int): the upsample factor
Returns:
... | [
"def",
"CaffeBilinearUpSample",
"(",
"x",
",",
"shape",
")",
":",
"inp_shape",
"=",
"x",
".",
"shape",
".",
"as_list",
"(",
")",
"ch",
"=",
"inp_shape",
"[",
"1",
"]",
"assert",
"ch",
"==",
"1",
",",
"\"This layer only works for channel=1\"",
"# for a versio... | Deterministic bilinearly-upsample the input images.
It is implemented by deconvolution with "BilinearFiller" in Caffe.
It is aimed to mimic caffe behavior.
Args:
x (tf.Tensor): a NCHW tensor
shape (int): the upsample factor
Returns:
tf.Tensor: a NCHW tensor. | [
"Deterministic",
"bilinearly",
"-",
"upsample",
"the",
"input",
"images",
".",
"It",
"is",
"implemented",
"by",
"deconvolution",
"with",
"BilinearFiller",
"in",
"Caffe",
".",
"It",
"is",
"aimed",
"to",
"mimic",
"caffe",
"behavior",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/HED/hed.py#L48-L101 |
27,369 | tensorpack/tensorpack | tensorpack/compat/tensor_spec.py | TensorSpec.is_compatible_with | def is_compatible_with(self, spec_or_tensor):
"""Returns True if spec_or_tensor is compatible with this TensorSpec.
Two tensors are considered compatible if they have the same dtype
and their shapes are compatible (see `tf.TensorShape.is_compatible_with`).
Args:
spec_or_tensor: A tf.TensorSpec o... | python | def is_compatible_with(self, spec_or_tensor):
"""Returns True if spec_or_tensor is compatible with this TensorSpec.
Two tensors are considered compatible if they have the same dtype
and their shapes are compatible (see `tf.TensorShape.is_compatible_with`).
Args:
spec_or_tensor: A tf.TensorSpec o... | [
"def",
"is_compatible_with",
"(",
"self",
",",
"spec_or_tensor",
")",
":",
"return",
"(",
"self",
".",
"_dtype",
".",
"is_compatible_with",
"(",
"spec_or_tensor",
".",
"dtype",
")",
"and",
"self",
".",
"_shape",
".",
"is_compatible_with",
"(",
"spec_or_tensor",
... | Returns True if spec_or_tensor is compatible with this TensorSpec.
Two tensors are considered compatible if they have the same dtype
and their shapes are compatible (see `tf.TensorShape.is_compatible_with`).
Args:
spec_or_tensor: A tf.TensorSpec or a tf.Tensor
Returns:
True if spec_or_ten... | [
"Returns",
"True",
"if",
"spec_or_tensor",
"is",
"compatible",
"with",
"this",
"TensorSpec",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/compat/tensor_spec.py#L75-L88 |
27,370 | tensorpack/tensorpack | tensorpack/tfutils/model_utils.py | describe_trainable_vars | def describe_trainable_vars():
"""
Print a description of the current model parameters.
Skip variables starting with "tower", as they are just duplicates built by data-parallel logic.
"""
train_vars = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES)
if len(train_vars) == 0:
logger.war... | python | def describe_trainable_vars():
"""
Print a description of the current model parameters.
Skip variables starting with "tower", as they are just duplicates built by data-parallel logic.
"""
train_vars = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES)
if len(train_vars) == 0:
logger.war... | [
"def",
"describe_trainable_vars",
"(",
")",
":",
"train_vars",
"=",
"tf",
".",
"get_collection",
"(",
"tf",
".",
"GraphKeys",
".",
"TRAINABLE_VARIABLES",
")",
"if",
"len",
"(",
"train_vars",
")",
"==",
"0",
":",
"logger",
".",
"warn",
"(",
"\"No trainable va... | Print a description of the current model parameters.
Skip variables starting with "tower", as they are just duplicates built by data-parallel logic. | [
"Print",
"a",
"description",
"of",
"the",
"current",
"model",
"parameters",
".",
"Skip",
"variables",
"starting",
"with",
"tower",
"as",
"they",
"are",
"just",
"duplicates",
"built",
"by",
"data",
"-",
"parallel",
"logic",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/tfutils/model_utils.py#L15-L67 |
27,371 | tensorpack/tensorpack | examples/SimilarityLearning/mnist-embeddings.py | EmbeddingModel.embed | def embed(self, x, nfeatures=2):
"""Embed all given tensors into an nfeatures-dim space. """
list_split = 0
if isinstance(x, list):
list_split = len(x)
x = tf.concat(x, 0)
# pre-process MNIST dataflow data
x = tf.expand_dims(x, 3)
x = x * 2 - 1
... | python | def embed(self, x, nfeatures=2):
"""Embed all given tensors into an nfeatures-dim space. """
list_split = 0
if isinstance(x, list):
list_split = len(x)
x = tf.concat(x, 0)
# pre-process MNIST dataflow data
x = tf.expand_dims(x, 3)
x = x * 2 - 1
... | [
"def",
"embed",
"(",
"self",
",",
"x",
",",
"nfeatures",
"=",
"2",
")",
":",
"list_split",
"=",
"0",
"if",
"isinstance",
"(",
"x",
",",
"list",
")",
":",
"list_split",
"=",
"len",
"(",
"x",
")",
"x",
"=",
"tf",
".",
"concat",
"(",
"x",
",",
"... | Embed all given tensors into an nfeatures-dim space. | [
"Embed",
"all",
"given",
"tensors",
"into",
"an",
"nfeatures",
"-",
"dim",
"space",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/SimilarityLearning/mnist-embeddings.py#L200-L224 |
27,372 | tensorpack/tensorpack | tensorpack/graph_builder/utils.py | allreduce_grads | def allreduce_grads(all_grads, average):
"""
All-reduce average the gradients among K devices. Results are broadcasted to all devices.
Args:
all_grads (K x N): List of list of gradients. N is the number of variables.
average (bool): average gradients or not.
Returns:
K x N: sam... | python | def allreduce_grads(all_grads, average):
"""
All-reduce average the gradients among K devices. Results are broadcasted to all devices.
Args:
all_grads (K x N): List of list of gradients. N is the number of variables.
average (bool): average gradients or not.
Returns:
K x N: sam... | [
"def",
"allreduce_grads",
"(",
"all_grads",
",",
"average",
")",
":",
"if",
"get_tf_version_tuple",
"(",
")",
"<=",
"(",
"1",
",",
"12",
")",
":",
"from",
"tensorflow",
".",
"contrib",
"import",
"nccl",
"else",
":",
"from",
"tensorflow",
".",
"python",
"... | All-reduce average the gradients among K devices. Results are broadcasted to all devices.
Args:
all_grads (K x N): List of list of gradients. N is the number of variables.
average (bool): average gradients or not.
Returns:
K x N: same as input, but each grad is replaced by the average ... | [
"All",
"-",
"reduce",
"average",
"the",
"gradients",
"among",
"K",
"devices",
".",
"Results",
"are",
"broadcasted",
"to",
"all",
"devices",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/graph_builder/utils.py#L139-L173 |
27,373 | tensorpack/tensorpack | tensorpack/graph_builder/utils.py | allreduce_grads_hierarchical | def allreduce_grads_hierarchical(all_grads, devices, average=False):
"""
Hierarchical allreduce for DGX-1 system.
Args:
all_grads (K x N): List of list of gradients. N is the number of variables.
devices ([str]): K str for the K devices.
average (bool): average gradients or not.
... | python | def allreduce_grads_hierarchical(all_grads, devices, average=False):
"""
Hierarchical allreduce for DGX-1 system.
Args:
all_grads (K x N): List of list of gradients. N is the number of variables.
devices ([str]): K str for the K devices.
average (bool): average gradients or not.
... | [
"def",
"allreduce_grads_hierarchical",
"(",
"all_grads",
",",
"devices",
",",
"average",
"=",
"False",
")",
":",
"num_gpu",
"=",
"len",
"(",
"devices",
")",
"assert",
"num_gpu",
"==",
"8",
",",
"num_gpu",
"assert",
"len",
"(",
"all_grads",
")",
"==",
"num_... | Hierarchical allreduce for DGX-1 system.
Args:
all_grads (K x N): List of list of gradients. N is the number of variables.
devices ([str]): K str for the K devices.
average (bool): average gradients or not.
Returns:
(K x N): same as input, but each grad is replaced by the avera... | [
"Hierarchical",
"allreduce",
"for",
"DGX",
"-",
"1",
"system",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/graph_builder/utils.py#L177-L235 |
27,374 | tensorpack/tensorpack | tensorpack/graph_builder/utils.py | aggregate_grads | def aggregate_grads(all_grads,
colocation=False,
devices=None,
average=True):
"""
Average the gradients.
Args:
all_grads (K x N x 2): A list of K lists. Each of the list is a list of N (grad, var) tuples.
The variables have to ... | python | def aggregate_grads(all_grads,
colocation=False,
devices=None,
average=True):
"""
Average the gradients.
Args:
all_grads (K x N x 2): A list of K lists. Each of the list is a list of N (grad, var) tuples.
The variables have to ... | [
"def",
"aggregate_grads",
"(",
"all_grads",
",",
"colocation",
"=",
"False",
",",
"devices",
"=",
"None",
",",
"average",
"=",
"True",
")",
":",
"assert",
"not",
"(",
"devices",
"is",
"not",
"None",
"and",
"colocation",
")",
"if",
"devices",
"is",
"not",... | Average the gradients.
Args:
all_grads (K x N x 2): A list of K lists. Each of the list is a list of N (grad, var) tuples.
The variables have to be the same across the K lists.
colocation (bool): colocate gradient averaging on the device of the variable.
devices (list[str]): ass... | [
"Average",
"the",
"gradients",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/graph_builder/utils.py#L239-L287 |
27,375 | tensorpack/tensorpack | examples/FasterRCNN/model_fpn.py | fpn_map_rois_to_levels | def fpn_map_rois_to_levels(boxes):
"""
Assign boxes to level 2~5.
Args:
boxes (nx4):
Returns:
[tf.Tensor]: 4 tensors for level 2-5. Each tensor is a vector of indices of boxes in its level.
[tf.Tensor]: 4 tensors, the gathered boxes in each level.
Be careful that the retur... | python | def fpn_map_rois_to_levels(boxes):
"""
Assign boxes to level 2~5.
Args:
boxes (nx4):
Returns:
[tf.Tensor]: 4 tensors for level 2-5. Each tensor is a vector of indices of boxes in its level.
[tf.Tensor]: 4 tensors, the gathered boxes in each level.
Be careful that the retur... | [
"def",
"fpn_map_rois_to_levels",
"(",
"boxes",
")",
":",
"sqrtarea",
"=",
"tf",
".",
"sqrt",
"(",
"tf_area",
"(",
"boxes",
")",
")",
"level",
"=",
"tf",
".",
"cast",
"(",
"tf",
".",
"floor",
"(",
"4",
"+",
"tf",
".",
"log",
"(",
"sqrtarea",
"*",
... | Assign boxes to level 2~5.
Args:
boxes (nx4):
Returns:
[tf.Tensor]: 4 tensors for level 2-5. Each tensor is a vector of indices of boxes in its level.
[tf.Tensor]: 4 tensors, the gathered boxes in each level.
Be careful that the returned tensor could be empty. | [
"Assign",
"boxes",
"to",
"level",
"2~5",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/model_fpn.py#L70-L100 |
27,376 | tensorpack/tensorpack | examples/FasterRCNN/model_frcnn.py | proposal_metrics | def proposal_metrics(iou):
"""
Add summaries for RPN proposals.
Args:
iou: nxm, #proposal x #gt
"""
# find best roi for each gt, for summary only
best_iou = tf.reduce_max(iou, axis=0)
mean_best_iou = tf.reduce_mean(best_iou, name='best_iou_per_gt')
summaries = [mean_best_iou]
... | python | def proposal_metrics(iou):
"""
Add summaries for RPN proposals.
Args:
iou: nxm, #proposal x #gt
"""
# find best roi for each gt, for summary only
best_iou = tf.reduce_max(iou, axis=0)
mean_best_iou = tf.reduce_mean(best_iou, name='best_iou_per_gt')
summaries = [mean_best_iou]
... | [
"def",
"proposal_metrics",
"(",
"iou",
")",
":",
"# find best roi for each gt, for summary only",
"best_iou",
"=",
"tf",
".",
"reduce_max",
"(",
"iou",
",",
"axis",
"=",
"0",
")",
"mean_best_iou",
"=",
"tf",
".",
"reduce_mean",
"(",
"best_iou",
",",
"name",
"=... | Add summaries for RPN proposals.
Args:
iou: nxm, #proposal x #gt | [
"Add",
"summaries",
"for",
"RPN",
"proposals",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/model_frcnn.py#L20-L38 |
27,377 | tensorpack/tensorpack | examples/FasterRCNN/model_frcnn.py | fastrcnn_predictions | def fastrcnn_predictions(boxes, scores):
"""
Generate final results from predictions of all proposals.
Args:
boxes: n#classx4 floatbox in float32
scores: nx#class
Returns:
boxes: Kx4
scores: K
labels: K
"""
assert boxes.shape[1] == cfg.DATA.NUM_CLASS
... | python | def fastrcnn_predictions(boxes, scores):
"""
Generate final results from predictions of all proposals.
Args:
boxes: n#classx4 floatbox in float32
scores: nx#class
Returns:
boxes: Kx4
scores: K
labels: K
"""
assert boxes.shape[1] == cfg.DATA.NUM_CLASS
... | [
"def",
"fastrcnn_predictions",
"(",
"boxes",
",",
"scores",
")",
":",
"assert",
"boxes",
".",
"shape",
"[",
"1",
"]",
"==",
"cfg",
".",
"DATA",
".",
"NUM_CLASS",
"assert",
"scores",
".",
"shape",
"[",
"1",
"]",
"==",
"cfg",
".",
"DATA",
".",
"NUM_CLA... | Generate final results from predictions of all proposals.
Args:
boxes: n#classx4 floatbox in float32
scores: nx#class
Returns:
boxes: Kx4
scores: K
labels: K | [
"Generate",
"final",
"results",
"from",
"predictions",
"of",
"all",
"proposals",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/model_frcnn.py#L176-L247 |
27,378 | tensorpack/tensorpack | examples/A3C-Gym/train-atari.py | MySimulatorMaster._on_state | def _on_state(self, state, client):
"""
Launch forward prediction for the new state given by some client.
"""
def cb(outputs):
try:
distrib, value = outputs.result()
except CancelledError:
logger.info("Client {} cancelled.".format(c... | python | def _on_state(self, state, client):
"""
Launch forward prediction for the new state given by some client.
"""
def cb(outputs):
try:
distrib, value = outputs.result()
except CancelledError:
logger.info("Client {} cancelled.".format(c... | [
"def",
"_on_state",
"(",
"self",
",",
"state",
",",
"client",
")",
":",
"def",
"cb",
"(",
"outputs",
")",
":",
"try",
":",
"distrib",
",",
"value",
"=",
"outputs",
".",
"result",
"(",
")",
"except",
"CancelledError",
":",
"logger",
".",
"info",
"(",
... | Launch forward prediction for the new state given by some client. | [
"Launch",
"forward",
"prediction",
"for",
"the",
"new",
"state",
"given",
"by",
"some",
"client",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/A3C-Gym/train-atari.py#L159-L174 |
27,379 | tensorpack/tensorpack | examples/A3C-Gym/train-atari.py | MySimulatorMaster._process_msg | def _process_msg(self, client, state, reward, isOver):
"""
Process a message sent from some client.
"""
# in the first message, only state is valid,
# reward&isOver should be discarded
if len(client.memory) > 0:
client.memory[-1].reward = reward
if... | python | def _process_msg(self, client, state, reward, isOver):
"""
Process a message sent from some client.
"""
# in the first message, only state is valid,
# reward&isOver should be discarded
if len(client.memory) > 0:
client.memory[-1].reward = reward
if... | [
"def",
"_process_msg",
"(",
"self",
",",
"client",
",",
"state",
",",
"reward",
",",
"isOver",
")",
":",
"# in the first message, only state is valid,",
"# reward&isOver should be discarded",
"if",
"len",
"(",
"client",
".",
"memory",
")",
">",
"0",
":",
"client",... | Process a message sent from some client. | [
"Process",
"a",
"message",
"sent",
"from",
"some",
"client",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/A3C-Gym/train-atari.py#L176-L192 |
27,380 | tensorpack/tensorpack | tensorpack/tfutils/export.py | ModelExporter.export_serving | def export_serving(self, filename,
tags=[tf.saved_model.SERVING if is_tfv2() else tf.saved_model.tag_constants.SERVING],
signature_name='prediction_pipeline'):
"""
Converts a checkpoint and graph to a servable for TensorFlow Serving.
Use TF's `SavedM... | python | def export_serving(self, filename,
tags=[tf.saved_model.SERVING if is_tfv2() else tf.saved_model.tag_constants.SERVING],
signature_name='prediction_pipeline'):
"""
Converts a checkpoint and graph to a servable for TensorFlow Serving.
Use TF's `SavedM... | [
"def",
"export_serving",
"(",
"self",
",",
"filename",
",",
"tags",
"=",
"[",
"tf",
".",
"saved_model",
".",
"SERVING",
"if",
"is_tfv2",
"(",
")",
"else",
"tf",
".",
"saved_model",
".",
"tag_constants",
".",
"SERVING",
"]",
",",
"signature_name",
"=",
"'... | Converts a checkpoint and graph to a servable for TensorFlow Serving.
Use TF's `SavedModelBuilder` to export a trained model without tensorpack dependency.
Args:
filename (str): path for export directory
tags (list): list of user specified tags
signature_name (str): ... | [
"Converts",
"a",
"checkpoint",
"and",
"graph",
"to",
"a",
"servable",
"for",
"TensorFlow",
"Serving",
".",
"Use",
"TF",
"s",
"SavedModelBuilder",
"to",
"export",
"a",
"trained",
"model",
"without",
"tensorpack",
"dependency",
"."
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/tfutils/export.py#L91-L146 |
27,381 | modin-project/modin | ci/benchmarks/utils.py | time_logger | def time_logger(name):
"""This logs the time usage of a code block"""
start_time = time.time()
yield
end_time = time.time()
total_time = end_time - start_time
logging.info("%s; time: %ss", name, total_time) | python | def time_logger(name):
"""This logs the time usage of a code block"""
start_time = time.time()
yield
end_time = time.time()
total_time = end_time - start_time
logging.info("%s; time: %ss", name, total_time) | [
"def",
"time_logger",
"(",
"name",
")",
":",
"start_time",
"=",
"time",
".",
"time",
"(",
")",
"yield",
"end_time",
"=",
"time",
".",
"time",
"(",
")",
"total_time",
"=",
"end_time",
"-",
"start_time",
"logging",
".",
"info",
"(",
"\"%s; time: %ss\"",
",... | This logs the time usage of a code block | [
"This",
"logs",
"the",
"time",
"usage",
"of",
"a",
"code",
"block"
] | 5b77d242596560c646b8405340c9ce64acb183cb | https://github.com/modin-project/modin/blob/5b77d242596560c646b8405340c9ce64acb183cb/ci/benchmarks/utils.py#L12-L19 |
27,382 | modin-project/modin | modin/pandas/__init__.py | initialize_ray | def initialize_ray():
"""Initializes ray based on environment variables and internal defaults."""
if threading.current_thread().name == "MainThread":
plasma_directory = None
object_store_memory = os.environ.get("MODIN_MEMORY", None)
if os.environ.get("MODIN_OUT_OF_CORE", "False").title()... | python | def initialize_ray():
"""Initializes ray based on environment variables and internal defaults."""
if threading.current_thread().name == "MainThread":
plasma_directory = None
object_store_memory = os.environ.get("MODIN_MEMORY", None)
if os.environ.get("MODIN_OUT_OF_CORE", "False").title()... | [
"def",
"initialize_ray",
"(",
")",
":",
"if",
"threading",
".",
"current_thread",
"(",
")",
".",
"name",
"==",
"\"MainThread\"",
":",
"plasma_directory",
"=",
"None",
"object_store_memory",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"\"MODIN_MEMORY\"",
",",
... | Initializes ray based on environment variables and internal defaults. | [
"Initializes",
"ray",
"based",
"on",
"environment",
"variables",
"and",
"internal",
"defaults",
"."
] | 5b77d242596560c646b8405340c9ce64acb183cb | https://github.com/modin-project/modin/blob/5b77d242596560c646b8405340c9ce64acb183cb/modin/pandas/__init__.py#L133-L168 |
27,383 | modin-project/modin | modin/engines/dask/pandas_on_dask_delayed/frame/axis_partition.py | DaskFrameAxisPartition.apply | def apply(
self,
func,
num_splits=None,
other_axis_partition=None,
maintain_partitioning=True,
**kwargs
):
"""Applies func to the object.
See notes in Parent class about this method.
Args:
func: The function to apply.
... | python | def apply(
self,
func,
num_splits=None,
other_axis_partition=None,
maintain_partitioning=True,
**kwargs
):
"""Applies func to the object.
See notes in Parent class about this method.
Args:
func: The function to apply.
... | [
"def",
"apply",
"(",
"self",
",",
"func",
",",
"num_splits",
"=",
"None",
",",
"other_axis_partition",
"=",
"None",
",",
"maintain_partitioning",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"import",
"dask",
"if",
"num_splits",
"is",
"None",
":",
"nu... | Applies func to the object.
See notes in Parent class about this method.
Args:
func: The function to apply.
num_splits: The number of times to split the result object.
other_axis_partition: Another `DaskFrameAxisPartition` object to apply to
func wit... | [
"Applies",
"func",
"to",
"the",
"object",
"."
] | 5b77d242596560c646b8405340c9ce64acb183cb | https://github.com/modin-project/modin/blob/5b77d242596560c646b8405340c9ce64acb183cb/modin/engines/dask/pandas_on_dask_delayed/frame/axis_partition.py#L15-L63 |
27,384 | modin-project/modin | modin/pandas/reshape.py | get_dummies | def get_dummies(
data,
prefix=None,
prefix_sep="_",
dummy_na=False,
columns=None,
sparse=False,
drop_first=False,
dtype=None,
):
"""Convert categorical variable into indicator variables.
Args:
data (array-like, Series, or DataFrame): data to encode.
prefix (strin... | python | def get_dummies(
data,
prefix=None,
prefix_sep="_",
dummy_na=False,
columns=None,
sparse=False,
drop_first=False,
dtype=None,
):
"""Convert categorical variable into indicator variables.
Args:
data (array-like, Series, or DataFrame): data to encode.
prefix (strin... | [
"def",
"get_dummies",
"(",
"data",
",",
"prefix",
"=",
"None",
",",
"prefix_sep",
"=",
"\"_\"",
",",
"dummy_na",
"=",
"False",
",",
"columns",
"=",
"None",
",",
"sparse",
"=",
"False",
",",
"drop_first",
"=",
"False",
",",
"dtype",
"=",
"None",
",",
... | Convert categorical variable into indicator variables.
Args:
data (array-like, Series, or DataFrame): data to encode.
prefix (string, [string]): Prefix to apply to each encoded column
label.
prefix_sep (string, [string]): Separator between prefix and value... | [
"Convert",
"categorical",
"variable",
"into",
"indicator",
"variables",
"."
] | 5b77d242596560c646b8405340c9ce64acb183cb | https://github.com/modin-project/modin/blob/5b77d242596560c646b8405340c9ce64acb183cb/modin/pandas/reshape.py#L12-L67 |
27,385 | modin-project/modin | modin/engines/base/frame/axis_partition.py | PandasFrameAxisPartition.shuffle | def shuffle(self, func, lengths, **kwargs):
"""Shuffle the order of the data in this axis based on the `lengths`.
Extends `BaseFrameAxisPartition.shuffle`.
Args:
func: The function to apply before splitting.
lengths: The list of partition lengths to split the result int... | python | def shuffle(self, func, lengths, **kwargs):
"""Shuffle the order of the data in this axis based on the `lengths`.
Extends `BaseFrameAxisPartition.shuffle`.
Args:
func: The function to apply before splitting.
lengths: The list of partition lengths to split the result int... | [
"def",
"shuffle",
"(",
"self",
",",
"func",
",",
"lengths",
",",
"*",
"*",
"kwargs",
")",
":",
"num_splits",
"=",
"len",
"(",
"lengths",
")",
"# We add these to kwargs and will pop them off before performing the operation.",
"kwargs",
"[",
"\"manual_partition\"",
"]",... | Shuffle the order of the data in this axis based on the `lengths`.
Extends `BaseFrameAxisPartition.shuffle`.
Args:
func: The function to apply before splitting.
lengths: The list of partition lengths to split the result into.
Returns:
A list of RemotePartit... | [
"Shuffle",
"the",
"order",
"of",
"the",
"data",
"in",
"this",
"axis",
"based",
"on",
"the",
"lengths",
"."
] | 5b77d242596560c646b8405340c9ce64acb183cb | https://github.com/modin-project/modin/blob/5b77d242596560c646b8405340c9ce64acb183cb/modin/engines/base/frame/axis_partition.py#L143-L161 |
27,386 | modin-project/modin | modin/experimental/engines/pyarrow_on_ray/frame/axis_partition.py | PyarrowOnRayFrameAxisPartition.shuffle | def shuffle(self, func, num_splits=None, **kwargs):
"""Shuffle the order of the data in this axis based on the `func`.
Extends `BaseFrameAxisPartition.shuffle`.
:param func:
:param num_splits:
:param kwargs:
:return:
"""
if num_splits is None:
... | python | def shuffle(self, func, num_splits=None, **kwargs):
"""Shuffle the order of the data in this axis based on the `func`.
Extends `BaseFrameAxisPartition.shuffle`.
:param func:
:param num_splits:
:param kwargs:
:return:
"""
if num_splits is None:
... | [
"def",
"shuffle",
"(",
"self",
",",
"func",
",",
"num_splits",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"num_splits",
"is",
"None",
":",
"num_splits",
"=",
"len",
"(",
"self",
".",
"list_of_blocks",
")",
"args",
"=",
"[",
"self",
".",
... | Shuffle the order of the data in this axis based on the `func`.
Extends `BaseFrameAxisPartition.shuffle`.
:param func:
:param num_splits:
:param kwargs:
:return: | [
"Shuffle",
"the",
"order",
"of",
"the",
"data",
"in",
"this",
"axis",
"based",
"on",
"the",
"func",
"."
] | 5b77d242596560c646b8405340c9ce64acb183cb | https://github.com/modin-project/modin/blob/5b77d242596560c646b8405340c9ce64acb183cb/modin/experimental/engines/pyarrow_on_ray/frame/axis_partition.py#L50-L68 |
27,387 | modin-project/modin | modin/experimental/engines/pyarrow_on_ray/frame/partition.py | PyarrowOnRayFramePartition.apply | def apply(self, func, **kwargs):
"""Apply a function to the object stored in this partition.
Note: It does not matter if func is callable or an ObjectID. Ray will
handle it correctly either way. The keyword arguments are sent as a
dictionary.
Args:
func: The... | python | def apply(self, func, **kwargs):
"""Apply a function to the object stored in this partition.
Note: It does not matter if func is callable or an ObjectID. Ray will
handle it correctly either way. The keyword arguments are sent as a
dictionary.
Args:
func: The... | [
"def",
"apply",
"(",
"self",
",",
"func",
",",
"*",
"*",
"kwargs",
")",
":",
"oid",
"=",
"self",
".",
"oid",
"self",
".",
"call_queue",
".",
"append",
"(",
"(",
"func",
",",
"kwargs",
")",
")",
"def",
"call_queue_closure",
"(",
"oid_obj",
",",
"cal... | Apply a function to the object stored in this partition.
Note: It does not matter if func is callable or an ObjectID. Ray will
handle it correctly either way. The keyword arguments are sent as a
dictionary.
Args:
func: The function to apply.
Returns:
... | [
"Apply",
"a",
"function",
"to",
"the",
"object",
"stored",
"in",
"this",
"partition",
"."
] | 5b77d242596560c646b8405340c9ce64acb183cb | https://github.com/modin-project/modin/blob/5b77d242596560c646b8405340c9ce64acb183cb/modin/experimental/engines/pyarrow_on_ray/frame/partition.py#L30-L62 |
27,388 | modin-project/modin | modin/experimental/engines/pyarrow_on_ray/frame/partition.py | PyarrowOnRayFramePartition.to_pandas | def to_pandas(self):
"""Convert the object stored in this partition to a Pandas DataFrame.
Returns:
A Pandas DataFrame.
"""
dataframe = self.get().to_pandas()
assert type(dataframe) is pandas.DataFrame or type(dataframe) is pandas.Series
return dataframe | python | def to_pandas(self):
"""Convert the object stored in this partition to a Pandas DataFrame.
Returns:
A Pandas DataFrame.
"""
dataframe = self.get().to_pandas()
assert type(dataframe) is pandas.DataFrame or type(dataframe) is pandas.Series
return dataframe | [
"def",
"to_pandas",
"(",
"self",
")",
":",
"dataframe",
"=",
"self",
".",
"get",
"(",
")",
".",
"to_pandas",
"(",
")",
"assert",
"type",
"(",
"dataframe",
")",
"is",
"pandas",
".",
"DataFrame",
"or",
"type",
"(",
"dataframe",
")",
"is",
"pandas",
"."... | Convert the object stored in this partition to a Pandas DataFrame.
Returns:
A Pandas DataFrame. | [
"Convert",
"the",
"object",
"stored",
"in",
"this",
"partition",
"to",
"a",
"Pandas",
"DataFrame",
"."
] | 5b77d242596560c646b8405340c9ce64acb183cb | https://github.com/modin-project/modin/blob/5b77d242596560c646b8405340c9ce64acb183cb/modin/experimental/engines/pyarrow_on_ray/frame/partition.py#L71-L80 |
27,389 | modin-project/modin | modin/experimental/engines/pyarrow_on_ray/frame/partition.py | PyarrowOnRayFramePartition.put | def put(cls, obj):
"""Put an object in the Plasma store and wrap it in this object.
Args:
obj: The object to be put.
Returns:
A `RayRemotePartition` object.
"""
return PyarrowOnRayFramePartition(ray.put(pyarrow.Table.from_pandas(obj))) | python | def put(cls, obj):
"""Put an object in the Plasma store and wrap it in this object.
Args:
obj: The object to be put.
Returns:
A `RayRemotePartition` object.
"""
return PyarrowOnRayFramePartition(ray.put(pyarrow.Table.from_pandas(obj))) | [
"def",
"put",
"(",
"cls",
",",
"obj",
")",
":",
"return",
"PyarrowOnRayFramePartition",
"(",
"ray",
".",
"put",
"(",
"pyarrow",
".",
"Table",
".",
"from_pandas",
"(",
"obj",
")",
")",
")"
] | Put an object in the Plasma store and wrap it in this object.
Args:
obj: The object to be put.
Returns:
A `RayRemotePartition` object. | [
"Put",
"an",
"object",
"in",
"the",
"Plasma",
"store",
"and",
"wrap",
"it",
"in",
"this",
"object",
"."
] | 5b77d242596560c646b8405340c9ce64acb183cb | https://github.com/modin-project/modin/blob/5b77d242596560c646b8405340c9ce64acb183cb/modin/experimental/engines/pyarrow_on_ray/frame/partition.py#L83-L92 |
27,390 | modin-project/modin | modin/pandas/general.py | merge | def merge(
left,
right,
how="inner",
on=None,
left_on=None,
right_on=None,
left_index=False,
right_index=False,
sort=False,
suffixes=("_x", "_y"),
copy=True,
indicator=False,
validate=None,
):
"""Database style join, where common columns in "on" are merged.
A... | python | def merge(
left,
right,
how="inner",
on=None,
left_on=None,
right_on=None,
left_index=False,
right_index=False,
sort=False,
suffixes=("_x", "_y"),
copy=True,
indicator=False,
validate=None,
):
"""Database style join, where common columns in "on" are merged.
A... | [
"def",
"merge",
"(",
"left",
",",
"right",
",",
"how",
"=",
"\"inner\"",
",",
"on",
"=",
"None",
",",
"left_on",
"=",
"None",
",",
"right_on",
"=",
"None",
",",
"left_index",
"=",
"False",
",",
"right_index",
"=",
"False",
",",
"sort",
"=",
"False",
... | Database style join, where common columns in "on" are merged.
Args:
left: DataFrame.
right: DataFrame.
how: What type of join to use.
on: The common column name(s) to join on. If None, and left_on and
right_on are also None, will default to all commonly named
... | [
"Database",
"style",
"join",
"where",
"common",
"columns",
"in",
"on",
"are",
"merged",
"."
] | 5b77d242596560c646b8405340c9ce64acb183cb | https://github.com/modin-project/modin/blob/5b77d242596560c646b8405340c9ce64acb183cb/modin/pandas/general.py#L41-L97 |
27,391 | modin-project/modin | modin/experimental/engines/pandas_on_ray/sql.py | is_distributed | def is_distributed(partition_column, lower_bound, upper_bound):
""" Check if is possible distribute a query given that args
Args:
partition_column: column used to share the data between the workers
lower_bound: the minimum value to be requested from the partition_column
upper_bound: the... | python | def is_distributed(partition_column, lower_bound, upper_bound):
""" Check if is possible distribute a query given that args
Args:
partition_column: column used to share the data between the workers
lower_bound: the minimum value to be requested from the partition_column
upper_bound: the... | [
"def",
"is_distributed",
"(",
"partition_column",
",",
"lower_bound",
",",
"upper_bound",
")",
":",
"if",
"(",
"(",
"partition_column",
"is",
"not",
"None",
")",
"and",
"(",
"lower_bound",
"is",
"not",
"None",
")",
"and",
"(",
"upper_bound",
"is",
"not",
"... | Check if is possible distribute a query given that args
Args:
partition_column: column used to share the data between the workers
lower_bound: the minimum value to be requested from the partition_column
upper_bound: the maximum value to be requested from the partition_column
Returns:
... | [
"Check",
"if",
"is",
"possible",
"distribute",
"a",
"query",
"given",
"that",
"args"
] | 5b77d242596560c646b8405340c9ce64acb183cb | https://github.com/modin-project/modin/blob/5b77d242596560c646b8405340c9ce64acb183cb/modin/experimental/engines/pandas_on_ray/sql.py#L5-L31 |
27,392 | modin-project/modin | modin/experimental/engines/pandas_on_ray/sql.py | is_table | def is_table(engine, sql):
""" Check with the given sql arg is query or table
Args:
engine: SQLAlchemy connection engine
sql: SQL query or table name
Returns:
True for table or False if not
"""
if engine.dialect.has_table(engine, sql):
return True
return False | python | def is_table(engine, sql):
""" Check with the given sql arg is query or table
Args:
engine: SQLAlchemy connection engine
sql: SQL query or table name
Returns:
True for table or False if not
"""
if engine.dialect.has_table(engine, sql):
return True
return False | [
"def",
"is_table",
"(",
"engine",
",",
"sql",
")",
":",
"if",
"engine",
".",
"dialect",
".",
"has_table",
"(",
"engine",
",",
"sql",
")",
":",
"return",
"True",
"return",
"False"
] | Check with the given sql arg is query or table
Args:
engine: SQLAlchemy connection engine
sql: SQL query or table name
Returns:
True for table or False if not | [
"Check",
"with",
"the",
"given",
"sql",
"arg",
"is",
"query",
"or",
"table"
] | 5b77d242596560c646b8405340c9ce64acb183cb | https://github.com/modin-project/modin/blob/5b77d242596560c646b8405340c9ce64acb183cb/modin/experimental/engines/pandas_on_ray/sql.py#L34-L46 |
27,393 | modin-project/modin | modin/experimental/engines/pandas_on_ray/sql.py | get_table_metadata | def get_table_metadata(engine, table):
""" Extract all useful infos from the given table
Args:
engine: SQLAlchemy connection engine
table: table name
Returns:
Dictionary of infos
"""
metadata = MetaData()
metadata.reflect(bind=engine, only=[table])
table_metadata = ... | python | def get_table_metadata(engine, table):
""" Extract all useful infos from the given table
Args:
engine: SQLAlchemy connection engine
table: table name
Returns:
Dictionary of infos
"""
metadata = MetaData()
metadata.reflect(bind=engine, only=[table])
table_metadata = ... | [
"def",
"get_table_metadata",
"(",
"engine",
",",
"table",
")",
":",
"metadata",
"=",
"MetaData",
"(",
")",
"metadata",
".",
"reflect",
"(",
"bind",
"=",
"engine",
",",
"only",
"=",
"[",
"table",
"]",
")",
"table_metadata",
"=",
"Table",
"(",
"table",
"... | Extract all useful infos from the given table
Args:
engine: SQLAlchemy connection engine
table: table name
Returns:
Dictionary of infos | [
"Extract",
"all",
"useful",
"infos",
"from",
"the",
"given",
"table"
] | 5b77d242596560c646b8405340c9ce64acb183cb | https://github.com/modin-project/modin/blob/5b77d242596560c646b8405340c9ce64acb183cb/modin/experimental/engines/pandas_on_ray/sql.py#L49-L62 |
27,394 | modin-project/modin | modin/experimental/engines/pandas_on_ray/sql.py | get_table_columns | def get_table_columns(metadata):
""" Extract columns names and python typos from metadata
Args:
metadata: Table metadata
Returns:
dict with columns names and python types
"""
cols = OrderedDict()
for col in metadata.c:
name = str(col).rpartition(".")[2]
cols[nam... | python | def get_table_columns(metadata):
""" Extract columns names and python typos from metadata
Args:
metadata: Table metadata
Returns:
dict with columns names and python types
"""
cols = OrderedDict()
for col in metadata.c:
name = str(col).rpartition(".")[2]
cols[nam... | [
"def",
"get_table_columns",
"(",
"metadata",
")",
":",
"cols",
"=",
"OrderedDict",
"(",
")",
"for",
"col",
"in",
"metadata",
".",
"c",
":",
"name",
"=",
"str",
"(",
"col",
")",
".",
"rpartition",
"(",
"\".\"",
")",
"[",
"2",
"]",
"cols",
"[",
"name... | Extract columns names and python typos from metadata
Args:
metadata: Table metadata
Returns:
dict with columns names and python types | [
"Extract",
"columns",
"names",
"and",
"python",
"typos",
"from",
"metadata"
] | 5b77d242596560c646b8405340c9ce64acb183cb | https://github.com/modin-project/modin/blob/5b77d242596560c646b8405340c9ce64acb183cb/modin/experimental/engines/pandas_on_ray/sql.py#L65-L78 |
27,395 | modin-project/modin | modin/experimental/engines/pandas_on_ray/sql.py | check_query | def check_query(query):
""" Check query sanity
Args:
query: query string
Returns:
None
"""
q = query.lower()
if "select " not in q:
raise InvalidQuery("SELECT word not found in the query: {0}".format(query))
if " from " not in q:
raise InvalidQuery("FROM wor... | python | def check_query(query):
""" Check query sanity
Args:
query: query string
Returns:
None
"""
q = query.lower()
if "select " not in q:
raise InvalidQuery("SELECT word not found in the query: {0}".format(query))
if " from " not in q:
raise InvalidQuery("FROM wor... | [
"def",
"check_query",
"(",
"query",
")",
":",
"q",
"=",
"query",
".",
"lower",
"(",
")",
"if",
"\"select \"",
"not",
"in",
"q",
":",
"raise",
"InvalidQuery",
"(",
"\"SELECT word not found in the query: {0}\"",
".",
"format",
"(",
"query",
")",
")",
"if",
"... | Check query sanity
Args:
query: query string
Returns:
None | [
"Check",
"query",
"sanity"
] | 5b77d242596560c646b8405340c9ce64acb183cb | https://github.com/modin-project/modin/blob/5b77d242596560c646b8405340c9ce64acb183cb/modin/experimental/engines/pandas_on_ray/sql.py#L93-L106 |
27,396 | modin-project/modin | modin/experimental/engines/pandas_on_ray/sql.py | get_query_columns | def get_query_columns(engine, query):
""" Extract columns names and python typos from query
Args:
engine: SQLAlchemy connection engine
query: SQL query
Returns:
dict with columns names and python types
"""
con = engine.connect()
result = con.execute(query).fetchone()
... | python | def get_query_columns(engine, query):
""" Extract columns names and python typos from query
Args:
engine: SQLAlchemy connection engine
query: SQL query
Returns:
dict with columns names and python types
"""
con = engine.connect()
result = con.execute(query).fetchone()
... | [
"def",
"get_query_columns",
"(",
"engine",
",",
"query",
")",
":",
"con",
"=",
"engine",
".",
"connect",
"(",
")",
"result",
"=",
"con",
".",
"execute",
"(",
"query",
")",
".",
"fetchone",
"(",
")",
"values",
"=",
"list",
"(",
"result",
")",
"cols_na... | Extract columns names and python typos from query
Args:
engine: SQLAlchemy connection engine
query: SQL query
Returns:
dict with columns names and python types | [
"Extract",
"columns",
"names",
"and",
"python",
"typos",
"from",
"query"
] | 5b77d242596560c646b8405340c9ce64acb183cb | https://github.com/modin-project/modin/blob/5b77d242596560c646b8405340c9ce64acb183cb/modin/experimental/engines/pandas_on_ray/sql.py#L109-L126 |
27,397 | modin-project/modin | modin/experimental/engines/pandas_on_ray/sql.py | check_partition_column | def check_partition_column(partition_column, cols):
""" Check partition_column existence and type
Args:
partition_column: partition_column name
cols: dict with columns names and python types
Returns:
None
"""
for k, v in cols.items():
if k == partition_column:
... | python | def check_partition_column(partition_column, cols):
""" Check partition_column existence and type
Args:
partition_column: partition_column name
cols: dict with columns names and python types
Returns:
None
"""
for k, v in cols.items():
if k == partition_column:
... | [
"def",
"check_partition_column",
"(",
"partition_column",
",",
"cols",
")",
":",
"for",
"k",
",",
"v",
"in",
"cols",
".",
"items",
"(",
")",
":",
"if",
"k",
"==",
"partition_column",
":",
"if",
"v",
"==",
"\"int\"",
":",
"return",
"else",
":",
"raise",... | Check partition_column existence and type
Args:
partition_column: partition_column name
cols: dict with columns names and python types
Returns:
None | [
"Check",
"partition_column",
"existence",
"and",
"type"
] | 5b77d242596560c646b8405340c9ce64acb183cb | https://github.com/modin-project/modin/blob/5b77d242596560c646b8405340c9ce64acb183cb/modin/experimental/engines/pandas_on_ray/sql.py#L129-L149 |
27,398 | modin-project/modin | modin/experimental/engines/pandas_on_ray/sql.py | get_query_info | def get_query_info(sql, con, partition_column):
""" Return a columns name list and the query string
Args:
sql: SQL query or table name
con: database connection or url string
partition_column: column used to share the data between the workers
Returns:
Columns name list and q... | python | def get_query_info(sql, con, partition_column):
""" Return a columns name list and the query string
Args:
sql: SQL query or table name
con: database connection or url string
partition_column: column used to share the data between the workers
Returns:
Columns name list and q... | [
"def",
"get_query_info",
"(",
"sql",
",",
"con",
",",
"partition_column",
")",
":",
"engine",
"=",
"create_engine",
"(",
"con",
")",
"if",
"is_table",
"(",
"engine",
",",
"sql",
")",
":",
"table_metadata",
"=",
"get_table_metadata",
"(",
"engine",
",",
"sq... | Return a columns name list and the query string
Args:
sql: SQL query or table name
con: database connection or url string
partition_column: column used to share the data between the workers
Returns:
Columns name list and query string | [
"Return",
"a",
"columns",
"name",
"list",
"and",
"the",
"query",
"string"
] | 5b77d242596560c646b8405340c9ce64acb183cb | https://github.com/modin-project/modin/blob/5b77d242596560c646b8405340c9ce64acb183cb/modin/experimental/engines/pandas_on_ray/sql.py#L152-L175 |
27,399 | modin-project/modin | modin/experimental/engines/pandas_on_ray/sql.py | query_put_bounders | def query_put_bounders(query, partition_column, start, end):
""" Put bounders in the query
Args:
query: SQL query string
partition_column: partition_column name
start: lower_bound
end: upper_bound
Returns:
Query with bounders
"""
where = " WHERE TMP_TABLE.{0... | python | def query_put_bounders(query, partition_column, start, end):
""" Put bounders in the query
Args:
query: SQL query string
partition_column: partition_column name
start: lower_bound
end: upper_bound
Returns:
Query with bounders
"""
where = " WHERE TMP_TABLE.{0... | [
"def",
"query_put_bounders",
"(",
"query",
",",
"partition_column",
",",
"start",
",",
"end",
")",
":",
"where",
"=",
"\" WHERE TMP_TABLE.{0} >= {1} AND TMP_TABLE.{0} <= {2}\"",
".",
"format",
"(",
"partition_column",
",",
"start",
",",
"end",
")",
"query_with_bounder... | Put bounders in the query
Args:
query: SQL query string
partition_column: partition_column name
start: lower_bound
end: upper_bound
Returns:
Query with bounders | [
"Put",
"bounders",
"in",
"the",
"query"
] | 5b77d242596560c646b8405340c9ce64acb183cb | https://github.com/modin-project/modin/blob/5b77d242596560c646b8405340c9ce64acb183cb/modin/experimental/engines/pandas_on_ray/sql.py#L178-L194 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.