partition stringclasses 3
values | func_name stringlengths 1 134 | docstring stringlengths 1 46.9k | path stringlengths 4 223 | original_string stringlengths 75 104k | code stringlengths 75 104k | docstring_tokens listlengths 1 1.97k | repo stringlengths 7 55 | language stringclasses 1
value | url stringlengths 87 315 | code_tokens listlengths 19 28.4k | sha stringlengths 40 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|
train | EnvRunnerManager.reset_stats | Returns:
mean, max: two stats of the runners, to be added to backend | examples/DeepQNetwork/expreplay.py | def reset_stats(self):
"""
Returns:
mean, max: two stats of the runners, to be added to backend
"""
scores = list(itertools.chain.from_iterable([v.total_scores for v in self._runners]))
for v in self._runners:
v.total_scores.clear()
try:
... | def reset_stats(self):
"""
Returns:
mean, max: two stats of the runners, to be added to backend
"""
scores = list(itertools.chain.from_iterable([v.total_scores for v in self._runners]))
for v in self._runners:
v.total_scores.clear()
try:
... | [
"Returns",
":",
"mean",
"max",
":",
"two",
"stats",
"of",
"the",
"runners",
"to",
"be",
"added",
"to",
"backend"
] | tensorpack/tensorpack | python | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/DeepQNetwork/expreplay.py#L242-L255 | [
"def",
"reset_stats",
"(",
"self",
")",
":",
"scores",
"=",
"list",
"(",
"itertools",
".",
"chain",
".",
"from_iterable",
"(",
"[",
"v",
".",
"total_scores",
"for",
"v",
"in",
"self",
".",
"_runners",
"]",
")",
")",
"for",
"v",
"in",
"self",
".",
"... | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f |
train | CallbackTimeLogger.log | log the time of some heavy callbacks | tensorpack/callbacks/group.py | 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):
""" 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... | [
"log",
"the",
"time",
"of",
"some",
"heavy",
"callbacks"
] | tensorpack/tensorpack | python | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/callbacks/group.py#L37-L48 | [
"def",
"log",
"(",
"self",
")",
":",
"if",
"self",
".",
"tot",
"<",
"3",
":",
"return",
"msgs",
"=",
"[",
"]",
"for",
"name",
",",
"t",
"in",
"self",
".",
"times",
":",
"if",
"t",
"/",
"self",
".",
"tot",
">",
"0.3",
"and",
"t",
">",
"1",
... | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f |
train | TowerContext | The context for a tower function, containing metadata about the current tower.
Tensorpack trainers use :class:`TowerContext` to manage tower function.
Many tensorpack layers have to be called under a :class:`TowerContext`.
Example:
.. code-block:: python
with TowerContext('', is_training=True... | tensorpack/tfutils/tower.py | def TowerContext(tower_name, is_training, vs_name=''):
"""
The context for a tower function, containing metadata about the current tower.
Tensorpack trainers use :class:`TowerContext` to manage tower function.
Many tensorpack layers have to be called under a :class:`TowerContext`.
Example:
.. ... | def TowerContext(tower_name, is_training, vs_name=''):
"""
The context for a tower function, containing metadata about the current tower.
Tensorpack trainers use :class:`TowerContext` to manage tower function.
Many tensorpack layers have to be called under a :class:`TowerContext`.
Example:
.. ... | [
"The",
"context",
"for",
"a",
"tower",
"function",
"containing",
"metadata",
"about",
"the",
"current",
"tower",
".",
"Tensorpack",
"trainers",
"use",
":",
"class",
":",
"TowerContext",
"to",
"manage",
"tower",
"function",
".",
"Many",
"tensorpack",
"layers",
... | tensorpack/tensorpack | python | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/tfutils/tower.py#L229-L245 | [
"def",
"TowerContext",
"(",
"tower_name",
",",
"is_training",
",",
"vs_name",
"=",
"''",
")",
":",
"if",
"is_training",
":",
"return",
"TrainTowerContext",
"(",
"tower_name",
",",
"vs_name",
"=",
"vs_name",
")",
"else",
":",
"return",
"PredictTowerContext",
"(... | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f |
train | TowerTensorHandles.training | Returns:
A :class:`TowerTensorHandles`, containing only the training towers. | tensorpack/tfutils/tower.py | def training(self):
"""
Returns:
A :class:`TowerTensorHandles`, containing only the training towers.
"""
handles = [h for h in self._handles if h.is_training]
return TowerTensorHandles(handles) | def training(self):
"""
Returns:
A :class:`TowerTensorHandles`, containing only the training towers.
"""
handles = [h for h in self._handles if h.is_training]
return TowerTensorHandles(handles) | [
"Returns",
":",
"A",
":",
"class",
":",
"TowerTensorHandles",
"containing",
"only",
"the",
"training",
"towers",
"."
] | tensorpack/tensorpack | python | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/tfutils/tower.py#L338-L344 | [
"def",
"training",
"(",
"self",
")",
":",
"handles",
"=",
"[",
"h",
"for",
"h",
"in",
"self",
".",
"_handles",
"if",
"h",
".",
"is_training",
"]",
"return",
"TowerTensorHandles",
"(",
"handles",
")"
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f |
train | TowerTensorHandles.inference | Returns:
A :class:`TowerTensorHandles`, containing only the inference towers. | tensorpack/tfutils/tower.py | def inference(self):
"""
Returns:
A :class:`TowerTensorHandles`, containing only the inference towers.
"""
handles = [h for h in self._handles if not h.is_training]
return TowerTensorHandles(handles) | def inference(self):
"""
Returns:
A :class:`TowerTensorHandles`, containing only the inference towers.
"""
handles = [h for h in self._handles if not h.is_training]
return TowerTensorHandles(handles) | [
"Returns",
":",
"A",
":",
"class",
":",
"TowerTensorHandles",
"containing",
"only",
"the",
"inference",
"towers",
"."
] | tensorpack/tensorpack | python | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/tfutils/tower.py#L346-L352 | [
"def",
"inference",
"(",
"self",
")",
":",
"handles",
"=",
"[",
"h",
"for",
"h",
"in",
"self",
".",
"_handles",
"if",
"not",
"h",
".",
"is_training",
"]",
"return",
"TowerTensorHandles",
"(",
"handles",
")"
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f |
train | TowerTensorHandle.get_tensor | Get a tensor in this tower. The name can be:
1. The name of the tensor without any tower prefix.
2. A name in the input signature, if it is used when building the tower.
In the second case, this method will return the tensor that's used as the corresponding
input to the tower. Note th... | tensorpack/tfutils/tower.py | def get_tensor(self, name):
"""
Get a tensor in this tower. The name can be:
1. The name of the tensor without any tower prefix.
2. A name in the input signature, if it is used when building the tower.
In the second case, this method will return the tensor that's used as the c... | def get_tensor(self, name):
"""
Get a tensor in this tower. The name can be:
1. The name of the tensor without any tower prefix.
2. A name in the input signature, if it is used when building the tower.
In the second case, this method will return the tensor that's used as the c... | [
"Get",
"a",
"tensor",
"in",
"this",
"tower",
".",
"The",
"name",
"can",
"be",
":"
] | tensorpack/tensorpack | python | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/tfutils/tower.py#L384-L415 | [
"def",
"get_tensor",
"(",
"self",
",",
"name",
")",
":",
"name",
"=",
"get_op_tensor_name",
"(",
"name",
")",
"[",
"1",
"]",
"if",
"len",
"(",
"self",
".",
"ns_name",
")",
":",
"name_with_ns",
"=",
"self",
".",
"ns_name",
"+",
"\"/\"",
"+",
"name",
... | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f |
train | TowerTensorHandle.get_variable | 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`. | tensorpack/tfutils/tower.py | 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):
"""
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_... | [
"Get",
"a",
"variable",
"used",
"in",
"this",
"tower",
".",
"The",
"name",
"should",
"not",
"contain",
"the",
"variable",
"scope",
"prefix",
"of",
"the",
"tower",
"."
] | tensorpack/tensorpack | python | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/tfutils/tower.py#L429-L442 | [
"def",
"get_variable",
"(",
"self",
",",
"name",
")",
":",
"name",
"=",
"get_op_tensor_name",
"(",
"name",
")",
"[",
"1",
"]",
"if",
"len",
"(",
"self",
".",
"vs_name",
")",
":",
"name_with_vs",
"=",
"self",
".",
"vs_name",
"+",
"\"/\"",
"+",
"name",... | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f |
train | TowerTensorHandle.get_collection | See :meth:`BaseTowerContext.get_collection_in_tower`.
Args:
key (str): the key of the collection
name: deprecated | tensorpack/tfutils/tower.py | def get_collection(self, key=None, name=None):
"""
See :meth:`BaseTowerContext.get_collection_in_tower`.
Args:
key (str): the key of the collection
name: deprecated
"""
if name is not None:
logger.warn("TowerTensorHandle.get_collection(name=..... | def get_collection(self, key=None, name=None):
"""
See :meth:`BaseTowerContext.get_collection_in_tower`.
Args:
key (str): the key of the collection
name: deprecated
"""
if name is not None:
logger.warn("TowerTensorHandle.get_collection(name=..... | [
"See",
":",
"meth",
":",
"BaseTowerContext",
".",
"get_collection_in_tower",
"."
] | tensorpack/tensorpack | python | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/tfutils/tower.py#L450-L461 | [
"def",
"get_collection",
"(",
"self",
",",
"key",
"=",
"None",
",",
"name",
"=",
"None",
")",
":",
"if",
"name",
"is",
"not",
"None",
":",
"logger",
".",
"warn",
"(",
"\"TowerTensorHandle.get_collection(name=..) was renamed to (key=..) !\"",
")",
"key",
"=",
"... | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f |
train | mkdir_p | Like "mkdir -p", make a dir recursively, but do nothing if the dir exists
Args:
dirname(str): | tensorpack/utils/fs.py | 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):
""" 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... | [
"Like",
"mkdir",
"-",
"p",
"make",
"a",
"dir",
"recursively",
"but",
"do",
"nothing",
"if",
"the",
"dir",
"exists"
] | tensorpack/tensorpack | python | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/fs.py#L16-L29 | [
"def",
"mkdir_p",
"(",
"dirname",
")",
":",
"assert",
"dirname",
"is",
"not",
"None",
"if",
"dirname",
"==",
"''",
"or",
"os",
".",
"path",
".",
"isdir",
"(",
"dirname",
")",
":",
"return",
"try",
":",
"os",
".",
"makedirs",
"(",
"dirname",
")",
"e... | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f |
train | download | Download URL to a directory.
Will figure out the filename automatically from URL, if not given. | tensorpack/utils/fs.py | 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):
"""
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(... | [
"Download",
"URL",
"to",
"a",
"directory",
".",
"Will",
"figure",
"out",
"the",
"filename",
"automatically",
"from",
"URL",
"if",
"not",
"given",
"."
] | tensorpack/tensorpack | python | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/fs.py#L32-L74 | [
"def",
"download",
"(",
"url",
",",
"dir",
",",
"filename",
"=",
"None",
",",
"expect_size",
"=",
"None",
")",
":",
"mkdir_p",
"(",
"dir",
")",
"if",
"filename",
"is",
"None",
":",
"filename",
"=",
"url",
".",
"split",
"(",
"'/'",
")",
"[",
"-",
... | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f |
train | recursive_walk | Yields:
str: All files in rootdir, recursively. | tensorpack/utils/fs.py | def recursive_walk(rootdir):
"""
Yields:
str: All files in rootdir, recursively.
"""
for r, dirs, files in os.walk(rootdir):
for f in files:
yield os.path.join(r, f) | def recursive_walk(rootdir):
"""
Yields:
str: All files in rootdir, recursively.
"""
for r, dirs, files in os.walk(rootdir):
for f in files:
yield os.path.join(r, f) | [
"Yields",
":",
"str",
":",
"All",
"files",
"in",
"rootdir",
"recursively",
"."
] | tensorpack/tensorpack | python | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/fs.py#L77-L84 | [
"def",
"recursive_walk",
"(",
"rootdir",
")",
":",
"for",
"r",
",",
"dirs",
",",
"files",
"in",
"os",
".",
"walk",
"(",
"rootdir",
")",
":",
"for",
"f",
"in",
"files",
":",
"yield",
"os",
".",
"path",
".",
"join",
"(",
"r",
",",
"f",
")"
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f |
train | get_dataset_path | Get the path to some dataset under ``$TENSORPACK_DATASET``.
Args:
args: strings to be joined to form path.
Returns:
str: path to the dataset. | tensorpack/utils/fs.py | def get_dataset_path(*args):
"""
Get the path to some dataset under ``$TENSORPACK_DATASET``.
Args:
args: strings to be joined to form path.
Returns:
str: path to the dataset.
"""
d = os.environ.get('TENSORPACK_DATASET', None)
if d is None:
d = os.path.join(os.path.e... | def get_dataset_path(*args):
"""
Get the path to some dataset under ``$TENSORPACK_DATASET``.
Args:
args: strings to be joined to form path.
Returns:
str: path to the dataset.
"""
d = os.environ.get('TENSORPACK_DATASET', None)
if d is None:
d = os.path.join(os.path.e... | [
"Get",
"the",
"path",
"to",
"some",
"dataset",
"under",
"$TENSORPACK_DATASET",
"."
] | tensorpack/tensorpack | python | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/fs.py#L87-L106 | [
"def",
"get_dataset_path",
"(",
"*",
"args",
")",
":",
"d",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"'TENSORPACK_DATASET'",
",",
"None",
")",
"if",
"d",
"is",
"None",
":",
"d",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",... | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f |
train | backup_collection | Args:
keys (list): list of collection keys to backup.
Defaults to all keys in the graph.
Returns:
dict: the backup | tensorpack/tfutils/collection.py | def backup_collection(keys=None):
"""
Args:
keys (list): list of collection keys to backup.
Defaults to all keys in the graph.
Returns:
dict: the backup
"""
if keys is None:
keys = tf.get_default_graph().get_all_collection_keys()
ret = {}
assert isinstanc... | def backup_collection(keys=None):
"""
Args:
keys (list): list of collection keys to backup.
Defaults to all keys in the graph.
Returns:
dict: the backup
"""
if keys is None:
keys = tf.get_default_graph().get_all_collection_keys()
ret = {}
assert isinstanc... | [
"Args",
":",
"keys",
"(",
"list",
")",
":",
"list",
"of",
"collection",
"keys",
"to",
"backup",
".",
"Defaults",
"to",
"all",
"keys",
"in",
"the",
"graph",
"."
] | tensorpack/tensorpack | python | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/tfutils/collection.py#L19-L34 | [
"def",
"backup_collection",
"(",
"keys",
"=",
"None",
")",
":",
"if",
"keys",
"is",
"None",
":",
"keys",
"=",
"tf",
".",
"get_default_graph",
"(",
")",
".",
"get_all_collection_keys",
"(",
")",
"ret",
"=",
"{",
"}",
"assert",
"isinstance",
"(",
"keys",
... | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f |
train | restore_collection | Restore from a collection backup.
Args:
backup (dict): | tensorpack/tfutils/collection.py | 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):
"""
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) | [
"Restore",
"from",
"a",
"collection",
"backup",
"."
] | tensorpack/tensorpack | python | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/tfutils/collection.py#L37-L46 | [
"def",
"restore_collection",
"(",
"backup",
")",
":",
"for",
"k",
",",
"v",
"in",
"six",
".",
"iteritems",
"(",
"backup",
")",
":",
"del",
"tf",
".",
"get_collection_ref",
"(",
"k",
")",
"[",
":",
"]",
"tf",
".",
"get_collection_ref",
"(",
"k",
")",
... | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f |
train | CollectionGuard.get_collection_in_tower | Get items from this collection that are added in the current tower. | tensorpack/tfutils/collection.py | 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):
"""
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] | [
"Get",
"items",
"from",
"this",
"collection",
"that",
"are",
"added",
"in",
"the",
"current",
"tower",
"."
] | tensorpack/tensorpack | python | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/tfutils/collection.py#L168-L175 | [
"def",
"get_collection_in_tower",
"(",
"self",
",",
"key",
")",
":",
"new",
"=",
"tf",
".",
"get_collection",
"(",
"key",
")",
"old",
"=",
"set",
"(",
"self",
".",
"original",
".",
"get",
"(",
"key",
",",
"[",
"]",
")",
")",
"# persist the order in new... | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f |
train | ptb_producer | 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... | examples/PennTreebank/reader.py | 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):
"""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_... | [
"Iterate",
"on",
"the",
"raw",
"PTB",
"data",
"."
] | tensorpack/tensorpack | python | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/PennTreebank/reader.py#L78-L119 | [
"def",
"ptb_producer",
"(",
"raw_data",
",",
"batch_size",
",",
"num_steps",
",",
"name",
"=",
"None",
")",
":",
"with",
"tf",
".",
"name_scope",
"(",
"name",
",",
"\"PTBProducer\"",
",",
"[",
"raw_data",
",",
"batch_size",
",",
"num_steps",
"]",
")",
":... | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f |
train | set_logger_dir | Set the directory for global logging.
Args:
dirname(str): log directory
action(str): an action of ["k","d","q"] to be performed
when the directory exists. Will ask user by default.
"d": delete the directory. Note that the deletion may fail when
the direc... | tensorpack/utils/logger.py | def set_logger_dir(dirname, action=None):
"""
Set the directory for global logging.
Args:
dirname(str): log directory
action(str): an action of ["k","d","q"] to be performed
when the directory exists. Will ask user by default.
"d": delete the directory. Note tha... | def set_logger_dir(dirname, action=None):
"""
Set the directory for global logging.
Args:
dirname(str): log directory
action(str): an action of ["k","d","q"] to be performed
when the directory exists. Will ask user by default.
"d": delete the directory. Note tha... | [
"Set",
"the",
"directory",
"for",
"global",
"logging",
"."
] | tensorpack/tensorpack | python | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/logger.py#L93-L150 | [
"def",
"set_logger_dir",
"(",
"dirname",
",",
"action",
"=",
"None",
")",
":",
"global",
"LOG_DIR",
",",
"_FILE_HANDLER",
"if",
"_FILE_HANDLER",
":",
"# unload and close the old file handler, so that we may safely delete the logger directory",
"_logger",
".",
"removeHandler",... | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f |
train | auto_set_dir | Use :func:`logger.set_logger_dir` to set log directory to
"./train_log/{scriptname}:{name}". "scriptname" is the name of the main python file currently running | tensorpack/utils/logger.py | def auto_set_dir(action=None, name=None):
"""
Use :func:`logger.set_logger_dir` to set log directory to
"./train_log/{scriptname}:{name}". "scriptname" is the name of the main python file currently running"""
mod = sys.modules['__main__']
basename = os.path.basename(mod.__file__)
auto_dirname = ... | def auto_set_dir(action=None, name=None):
"""
Use :func:`logger.set_logger_dir` to set log directory to
"./train_log/{scriptname}:{name}". "scriptname" is the name of the main python file currently running"""
mod = sys.modules['__main__']
basename = os.path.basename(mod.__file__)
auto_dirname = ... | [
"Use",
":",
"func",
":",
"logger",
".",
"set_logger_dir",
"to",
"set",
"log",
"directory",
"to",
".",
"/",
"train_log",
"/",
"{",
"scriptname",
"}",
":",
"{",
"name",
"}",
".",
"scriptname",
"is",
"the",
"name",
"of",
"the",
"main",
"python",
"file",
... | tensorpack/tensorpack | python | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/logger.py#L153-L162 | [
"def",
"auto_set_dir",
"(",
"action",
"=",
"None",
",",
"name",
"=",
"None",
")",
":",
"mod",
"=",
"sys",
".",
"modules",
"[",
"'__main__'",
"]",
"basename",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"mod",
".",
"__file__",
")",
"auto_dirname",
"... | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f |
train | class_balanced_sigmoid_cross_entropy | The class-balanced cross entropy loss,
as in `Holistically-Nested Edge Detection
<http://arxiv.org/abs/1504.06375>`_.
Args:
logits: of shape (b, ...).
label: of the same shape. the ground truth in {0,1}.
Returns:
class-balanced cross entropy loss. | examples/HED/hed.py | def class_balanced_sigmoid_cross_entropy(logits, label, name='cross_entropy_loss'):
"""
The class-balanced cross entropy loss,
as in `Holistically-Nested Edge Detection
<http://arxiv.org/abs/1504.06375>`_.
Args:
logits: of shape (b, ...).
label: of the same shape. the ground truth i... | def class_balanced_sigmoid_cross_entropy(logits, label, name='cross_entropy_loss'):
"""
The class-balanced cross entropy loss,
as in `Holistically-Nested Edge Detection
<http://arxiv.org/abs/1504.06375>`_.
Args:
logits: of shape (b, ...).
label: of the same shape. the ground truth i... | [
"The",
"class",
"-",
"balanced",
"cross",
"entropy",
"loss",
"as",
"in",
"Holistically",
"-",
"Nested",
"Edge",
"Detection",
"<http",
":",
"//",
"arxiv",
".",
"org",
"/",
"abs",
"/",
"1504",
".",
"06375",
">",
"_",
"."
] | tensorpack/tensorpack | python | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/HED/hed.py#L21-L44 | [
"def",
"class_balanced_sigmoid_cross_entropy",
"(",
"logits",
",",
"label",
",",
"name",
"=",
"'cross_entropy_loss'",
")",
":",
"with",
"tf",
".",
"name_scope",
"(",
"'class_balanced_sigmoid_cross_entropy'",
")",
":",
"y",
"=",
"tf",
".",
"cast",
"(",
"label",
"... | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f |
train | CaffeBilinearUpSample | 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. | examples/HED/hed.py | 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):
"""
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:
... | [
"Deterministic",
"bilinearly",
"-",
"upsample",
"the",
"input",
"images",
".",
"It",
"is",
"implemented",
"by",
"deconvolution",
"with",
"BilinearFiller",
"in",
"Caffe",
".",
"It",
"is",
"aimed",
"to",
"mimic",
"caffe",
"behavior",
"."
] | tensorpack/tensorpack | python | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/HED/hed.py#L48-L101 | [
"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... | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f |
train | _MultiProcessZMQDataFlow.reset_state | All forked dataflows should only be reset **once and only once** in spawned processes.
Subclasses should call this method with super. | tensorpack/dataflow/parallel.py | def reset_state(self):
"""
All forked dataflows should only be reset **once and only once** in spawned processes.
Subclasses should call this method with super.
"""
assert not self._reset_done, "reset_state() was called twice! This violates the API of DataFlow!"
self._res... | def reset_state(self):
"""
All forked dataflows should only be reset **once and only once** in spawned processes.
Subclasses should call this method with super.
"""
assert not self._reset_done, "reset_state() was called twice! This violates the API of DataFlow!"
self._res... | [
"All",
"forked",
"dataflows",
"should",
"only",
"be",
"reset",
"**",
"once",
"and",
"only",
"once",
"**",
"in",
"spawned",
"processes",
".",
"Subclasses",
"should",
"call",
"this",
"method",
"with",
"super",
"."
] | tensorpack/tensorpack | python | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/dataflow/parallel.py#L92-L101 | [
"def",
"reset_state",
"(",
"self",
")",
":",
"assert",
"not",
"self",
".",
"_reset_done",
",",
"\"reset_state() was called twice! This violates the API of DataFlow!\"",
"self",
".",
"_reset_done",
"=",
"True",
"# __del__ not guaranteed to get called at exit",
"atexit",
".",
... | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f |
train | TensorSpec.is_compatible_with | 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... | tensorpack/compat/tensor_spec.py | 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):
"""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... | [
"Returns",
"True",
"if",
"spec_or_tensor",
"is",
"compatible",
"with",
"this",
"TensorSpec",
"."
] | tensorpack/tensorpack | python | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/compat/tensor_spec.py#L75-L88 | [
"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",
... | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f |
train | 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. | tensorpack/tfutils/model_utils.py | 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():
"""
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... | [
"Print",
"a",
"description",
"of",
"the",
"current",
"model",
"parameters",
".",
"Skip",
"variables",
"starting",
"with",
"tower",
"as",
"they",
"are",
"just",
"duplicates",
"built",
"by",
"data",
"-",
"parallel",
"logic",
"."
] | tensorpack/tensorpack | python | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/tfutils/model_utils.py#L15-L67 | [
"def",
"describe_trainable_vars",
"(",
")",
":",
"train_vars",
"=",
"tf",
".",
"get_collection",
"(",
"tf",
".",
"GraphKeys",
".",
"TRAINABLE_VARIABLES",
")",
"if",
"len",
"(",
"train_vars",
")",
"==",
"0",
":",
"logger",
".",
"warn",
"(",
"\"No trainable va... | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f |
train | get_shape_str | Internally used by layer registry, to print shapes of inputs/outputs of layers.
Args:
tensors (list or tf.Tensor): a tensor or a list of tensors
Returns:
str: a string to describe the shape | tensorpack/tfutils/model_utils.py | def get_shape_str(tensors):
"""
Internally used by layer registry, to print shapes of inputs/outputs of layers.
Args:
tensors (list or tf.Tensor): a tensor or a list of tensors
Returns:
str: a string to describe the shape
"""
if isinstance(tensors, (list, tuple)):
for v ... | def get_shape_str(tensors):
"""
Internally used by layer registry, to print shapes of inputs/outputs of layers.
Args:
tensors (list or tf.Tensor): a tensor or a list of tensors
Returns:
str: a string to describe the shape
"""
if isinstance(tensors, (list, tuple)):
for v ... | [
"Internally",
"used",
"by",
"layer",
"registry",
"to",
"print",
"shapes",
"of",
"inputs",
"/",
"outputs",
"of",
"layers",
"."
] | tensorpack/tensorpack | python | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/tfutils/model_utils.py#L70-L87 | [
"def",
"get_shape_str",
"(",
"tensors",
")",
":",
"if",
"isinstance",
"(",
"tensors",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"for",
"v",
"in",
"tensors",
":",
"assert",
"isinstance",
"(",
"v",
",",
"(",
"tf",
".",
"Tensor",
",",
"tf",
".",
... | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f |
train | contrastive_loss | r"""Loss for Siamese networks as described in the paper:
`Learning a Similarity Metric Discriminatively, with Application to Face
Verification <http://yann.lecun.com/exdb/publis/pdf/chopra-05.pdf>`_ by Chopra et al.
.. math::
\frac{1}{2} [y \cdot d^2 + (1-y) \cdot \max(0, m - d)^2], d = \Vert l - r... | examples/SimilarityLearning/mnist-embeddings.py | def contrastive_loss(left, right, y, margin, extra=False, scope="constrastive_loss"):
r"""Loss for Siamese networks as described in the paper:
`Learning a Similarity Metric Discriminatively, with Application to Face
Verification <http://yann.lecun.com/exdb/publis/pdf/chopra-05.pdf>`_ by Chopra et al.
.... | def contrastive_loss(left, right, y, margin, extra=False, scope="constrastive_loss"):
r"""Loss for Siamese networks as described in the paper:
`Learning a Similarity Metric Discriminatively, with Application to Face
Verification <http://yann.lecun.com/exdb/publis/pdf/chopra-05.pdf>`_ by Chopra et al.
.... | [
"r",
"Loss",
"for",
"Siamese",
"networks",
"as",
"described",
"in",
"the",
"paper",
":",
"Learning",
"a",
"Similarity",
"Metric",
"Discriminatively",
"with",
"Application",
"to",
"Face",
"Verification",
"<http",
":",
"//",
"yann",
".",
"lecun",
".",
"com",
"... | tensorpack/tensorpack | python | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/SimilarityLearning/mnist-embeddings.py#L25-L65 | [
"def",
"contrastive_loss",
"(",
"left",
",",
"right",
",",
"y",
",",
"margin",
",",
"extra",
"=",
"False",
",",
"scope",
"=",
"\"constrastive_loss\"",
")",
":",
"with",
"tf",
".",
"name_scope",
"(",
"scope",
")",
":",
"y",
"=",
"tf",
".",
"cast",
"("... | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f |
train | siamese_cosine_loss | r"""Loss for Siamese networks (cosine version).
Same as :func:`contrastive_loss` but with different similarity measurement.
.. math::
[\frac{l \cdot r}{\lVert l\rVert \lVert r\rVert} - (2y-1)]^2
Args:
left (tf.Tensor): left feature vectors of shape [Batch, N].
right (tf.Tensor): ri... | examples/SimilarityLearning/mnist-embeddings.py | def siamese_cosine_loss(left, right, y, scope="cosine_loss"):
r"""Loss for Siamese networks (cosine version).
Same as :func:`contrastive_loss` but with different similarity measurement.
.. math::
[\frac{l \cdot r}{\lVert l\rVert \lVert r\rVert} - (2y-1)]^2
Args:
left (tf.Tensor): left ... | def siamese_cosine_loss(left, right, y, scope="cosine_loss"):
r"""Loss for Siamese networks (cosine version).
Same as :func:`contrastive_loss` but with different similarity measurement.
.. math::
[\frac{l \cdot r}{\lVert l\rVert \lVert r\rVert} - (2y-1)]^2
Args:
left (tf.Tensor): left ... | [
"r",
"Loss",
"for",
"Siamese",
"networks",
"(",
"cosine",
"version",
")",
".",
"Same",
"as",
":",
"func",
":",
"contrastive_loss",
"but",
"with",
"different",
"similarity",
"measurement",
"."
] | tensorpack/tensorpack | python | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/SimilarityLearning/mnist-embeddings.py#L68-L96 | [
"def",
"siamese_cosine_loss",
"(",
"left",
",",
"right",
",",
"y",
",",
"scope",
"=",
"\"cosine_loss\"",
")",
":",
"def",
"l2_norm",
"(",
"t",
",",
"eps",
"=",
"1e-12",
")",
":",
"\"\"\"\n Returns:\n tf.Tensor: norm of 2D input tensor on axis 1\n ... | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f |
train | triplet_loss | r"""Loss for Triplet networks as described in the paper:
`FaceNet: A Unified Embedding for Face Recognition and Clustering
<https://arxiv.org/abs/1503.03832>`_
by Schroff et al.
Learn embeddings from an anchor point and a similar input (positive) as
well as a not-similar input (negative).
Intui... | examples/SimilarityLearning/mnist-embeddings.py | def triplet_loss(anchor, positive, negative, margin, extra=False, scope="triplet_loss"):
r"""Loss for Triplet networks as described in the paper:
`FaceNet: A Unified Embedding for Face Recognition and Clustering
<https://arxiv.org/abs/1503.03832>`_
by Schroff et al.
Learn embeddings from an anchor ... | def triplet_loss(anchor, positive, negative, margin, extra=False, scope="triplet_loss"):
r"""Loss for Triplet networks as described in the paper:
`FaceNet: A Unified Embedding for Face Recognition and Clustering
<https://arxiv.org/abs/1503.03832>`_
by Schroff et al.
Learn embeddings from an anchor ... | [
"r",
"Loss",
"for",
"Triplet",
"networks",
"as",
"described",
"in",
"the",
"paper",
":",
"FaceNet",
":",
"A",
"Unified",
"Embedding",
"for",
"Face",
"Recognition",
"and",
"Clustering",
"<https",
":",
"//",
"arxiv",
".",
"org",
"/",
"abs",
"/",
"1503",
".... | tensorpack/tensorpack | python | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/SimilarityLearning/mnist-embeddings.py#L99-L135 | [
"def",
"triplet_loss",
"(",
"anchor",
",",
"positive",
",",
"negative",
",",
"margin",
",",
"extra",
"=",
"False",
",",
"scope",
"=",
"\"triplet_loss\"",
")",
":",
"with",
"tf",
".",
"name_scope",
"(",
"scope",
")",
":",
"d_pos",
"=",
"tf",
".",
"reduc... | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f |
train | soft_triplet_loss | r"""Loss for triplet networks as described in the paper:
`Deep Metric Learning using Triplet Network
<https://arxiv.org/abs/1412.6622>`_ by Hoffer et al.
It is a softmax loss using :math:`(anchor-positive)^2` and
:math:`(anchor-negative)^2` as logits.
Args:
anchor (tf.Tensor): anchor featu... | examples/SimilarityLearning/mnist-embeddings.py | def soft_triplet_loss(anchor, positive, negative, extra=True, scope="soft_triplet_loss"):
r"""Loss for triplet networks as described in the paper:
`Deep Metric Learning using Triplet Network
<https://arxiv.org/abs/1412.6622>`_ by Hoffer et al.
It is a softmax loss using :math:`(anchor-positive)^2` and
... | def soft_triplet_loss(anchor, positive, negative, extra=True, scope="soft_triplet_loss"):
r"""Loss for triplet networks as described in the paper:
`Deep Metric Learning using Triplet Network
<https://arxiv.org/abs/1412.6622>`_ by Hoffer et al.
It is a softmax loss using :math:`(anchor-positive)^2` and
... | [
"r",
"Loss",
"for",
"triplet",
"networks",
"as",
"described",
"in",
"the",
"paper",
":",
"Deep",
"Metric",
"Learning",
"using",
"Triplet",
"Network",
"<https",
":",
"//",
"arxiv",
".",
"org",
"/",
"abs",
"/",
"1412",
".",
"6622",
">",
"_",
"by",
"Hoffe... | tensorpack/tensorpack | python | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/SimilarityLearning/mnist-embeddings.py#L138-L171 | [
"def",
"soft_triplet_loss",
"(",
"anchor",
",",
"positive",
",",
"negative",
",",
"extra",
"=",
"True",
",",
"scope",
"=",
"\"soft_triplet_loss\"",
")",
":",
"eps",
"=",
"1e-10",
"with",
"tf",
".",
"name_scope",
"(",
"scope",
")",
":",
"d_pos",
"=",
"tf"... | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f |
train | center_loss | r"""Center-Loss as described in the paper
`A Discriminative Feature Learning Approach for Deep Face Recognition`
<http://ydwen.github.io/papers/WenECCV16.pdf> by Wen et al.
Args:
embedding (tf.Tensor): features produced by the network
label (tf.Tensor): ground-truth label for each feature
... | examples/SimilarityLearning/mnist-embeddings.py | def center_loss(embedding, label, num_classes, alpha=0.1, scope="center_loss"):
r"""Center-Loss as described in the paper
`A Discriminative Feature Learning Approach for Deep Face Recognition`
<http://ydwen.github.io/papers/WenECCV16.pdf> by Wen et al.
Args:
embedding (tf.Tensor): features prod... | def center_loss(embedding, label, num_classes, alpha=0.1, scope="center_loss"):
r"""Center-Loss as described in the paper
`A Discriminative Feature Learning Approach for Deep Face Recognition`
<http://ydwen.github.io/papers/WenECCV16.pdf> by Wen et al.
Args:
embedding (tf.Tensor): features prod... | [
"r",
"Center",
"-",
"Loss",
"as",
"described",
"in",
"the",
"paper",
"A",
"Discriminative",
"Feature",
"Learning",
"Approach",
"for",
"Deep",
"Face",
"Recognition",
"<http",
":",
"//",
"ydwen",
".",
"github",
".",
"io",
"/",
"papers",
"/",
"WenECCV16",
"."... | tensorpack/tensorpack | python | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/SimilarityLearning/mnist-embeddings.py#L174-L196 | [
"def",
"center_loss",
"(",
"embedding",
",",
"label",
",",
"num_classes",
",",
"alpha",
"=",
"0.1",
",",
"scope",
"=",
"\"center_loss\"",
")",
":",
"nrof_features",
"=",
"embedding",
".",
"get_shape",
"(",
")",
"[",
"1",
"]",
"centers",
"=",
"tf",
".",
... | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f |
train | EmbeddingModel.embed | Embed all given tensors into an nfeatures-dim space. | examples/SimilarityLearning/mnist-embeddings.py | 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):
"""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
... | [
"Embed",
"all",
"given",
"tensors",
"into",
"an",
"nfeatures",
"-",
"dim",
"space",
"."
] | tensorpack/tensorpack | python | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/SimilarityLearning/mnist-embeddings.py#L200-L224 | [
"def",
"embed",
"(",
"self",
",",
"x",
",",
"nfeatures",
"=",
"2",
")",
":",
"list_split",
"=",
"0",
"if",
"isinstance",
"(",
"x",
",",
"list",
")",
":",
"list_split",
"=",
"len",
"(",
"x",
")",
"x",
"=",
"tf",
".",
"concat",
"(",
"x",
",",
"... | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f |
train | generate_anchors | Generate anchor (reference) windows by enumerating aspect ratios X
scales wrt a reference (0, 0, 15, 15) window. | examples/FasterRCNN/utils/generate_anchors.py | def generate_anchors(base_size=16, ratios=[0.5, 1, 2],
scales=2**np.arange(3, 6)):
"""
Generate anchor (reference) windows by enumerating aspect ratios X
scales wrt a reference (0, 0, 15, 15) window.
"""
base_anchor = np.array([1, 1, base_size, base_size], dtype='float32') - 1
... | def generate_anchors(base_size=16, ratios=[0.5, 1, 2],
scales=2**np.arange(3, 6)):
"""
Generate anchor (reference) windows by enumerating aspect ratios X
scales wrt a reference (0, 0, 15, 15) window.
"""
base_anchor = np.array([1, 1, base_size, base_size], dtype='float32') - 1
... | [
"Generate",
"anchor",
"(",
"reference",
")",
"windows",
"by",
"enumerating",
"aspect",
"ratios",
"X",
"scales",
"wrt",
"a",
"reference",
"(",
"0",
"0",
"15",
"15",
")",
"window",
"."
] | tensorpack/tensorpack | python | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/utils/generate_anchors.py#L41-L52 | [
"def",
"generate_anchors",
"(",
"base_size",
"=",
"16",
",",
"ratios",
"=",
"[",
"0.5",
",",
"1",
",",
"2",
"]",
",",
"scales",
"=",
"2",
"**",
"np",
".",
"arange",
"(",
"3",
",",
"6",
")",
")",
":",
"base_anchor",
"=",
"np",
".",
"array",
"(",... | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f |
train | Model.build_graph | This function should build the model which takes the input variables
and return cost at the end | examples/basics/mnist-tflayers.py | def build_graph(self, image, label):
"""This function should build the model which takes the input variables
and return cost at the end"""
# In tensorflow, inputs to convolution function are assumed to be
# NHWC. Add a single channel here.
image = tf.expand_dims(image, 3)
... | def build_graph(self, image, label):
"""This function should build the model which takes the input variables
and return cost at the end"""
# In tensorflow, inputs to convolution function are assumed to be
# NHWC. Add a single channel here.
image = tf.expand_dims(image, 3)
... | [
"This",
"function",
"should",
"build",
"the",
"model",
"which",
"takes",
"the",
"input",
"variables",
"and",
"return",
"cost",
"at",
"the",
"end"
] | tensorpack/tensorpack | python | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/basics/mnist-tflayers.py#L32-L83 | [
"def",
"build_graph",
"(",
"self",
",",
"image",
",",
"label",
")",
":",
"# In tensorflow, inputs to convolution function are assumed to be",
"# NHWC. Add a single channel here.",
"image",
"=",
"tf",
".",
"expand_dims",
"(",
"image",
",",
"3",
")",
"image",
"=",
"imag... | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f |
train | print_class_histogram | Args:
roidbs (list[dict]): the same format as the output of `load_training_roidbs`. | examples/FasterRCNN/data.py | def print_class_histogram(roidbs):
"""
Args:
roidbs (list[dict]): the same format as the output of `load_training_roidbs`.
"""
dataset = DetectionDataset()
hist_bins = np.arange(dataset.num_classes + 1)
# Histogram of ground-truth objects
gt_hist = np.zeros((dataset.num_classes,), d... | def print_class_histogram(roidbs):
"""
Args:
roidbs (list[dict]): the same format as the output of `load_training_roidbs`.
"""
dataset = DetectionDataset()
hist_bins = np.arange(dataset.num_classes + 1)
# Histogram of ground-truth objects
gt_hist = np.zeros((dataset.num_classes,), d... | [
"Args",
":",
"roidbs",
"(",
"list",
"[",
"dict",
"]",
")",
":",
"the",
"same",
"format",
"as",
"the",
"output",
"of",
"load_training_roidbs",
"."
] | tensorpack/tensorpack | python | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/data.py#L30-L50 | [
"def",
"print_class_histogram",
"(",
"roidbs",
")",
":",
"dataset",
"=",
"DetectionDataset",
"(",
")",
"hist_bins",
"=",
"np",
".",
"arange",
"(",
"dataset",
".",
"num_classes",
"+",
"1",
")",
"# Histogram of ground-truth objects",
"gt_hist",
"=",
"np",
".",
"... | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f |
train | get_all_anchors | Get all anchors in the largest possible image, shifted, floatbox
Args:
stride (int): the stride of anchors.
sizes (tuple[int]): the sizes (sqrt area) of anchors
Returns:
anchors: SxSxNUM_ANCHORx4, where S == ceil(MAX_SIZE/STRIDE), floatbox
The layout in the NUM_ANCHOR dim is NUM... | examples/FasterRCNN/data.py | def get_all_anchors(stride=None, sizes=None):
"""
Get all anchors in the largest possible image, shifted, floatbox
Args:
stride (int): the stride of anchors.
sizes (tuple[int]): the sizes (sqrt area) of anchors
Returns:
anchors: SxSxNUM_ANCHORx4, where S == ceil(MAX_SIZE/STRIDE)... | def get_all_anchors(stride=None, sizes=None):
"""
Get all anchors in the largest possible image, shifted, floatbox
Args:
stride (int): the stride of anchors.
sizes (tuple[int]): the sizes (sqrt area) of anchors
Returns:
anchors: SxSxNUM_ANCHORx4, where S == ceil(MAX_SIZE/STRIDE)... | [
"Get",
"all",
"anchors",
"in",
"the",
"largest",
"possible",
"image",
"shifted",
"floatbox",
"Args",
":",
"stride",
"(",
"int",
")",
":",
"the",
"stride",
"of",
"anchors",
".",
"sizes",
"(",
"tuple",
"[",
"int",
"]",
")",
":",
"the",
"sizes",
"(",
"s... | tensorpack/tensorpack | python | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/data.py#L54-L100 | [
"def",
"get_all_anchors",
"(",
"stride",
"=",
"None",
",",
"sizes",
"=",
"None",
")",
":",
"if",
"stride",
"is",
"None",
":",
"stride",
"=",
"cfg",
".",
"RPN",
".",
"ANCHOR_STRIDE",
"if",
"sizes",
"is",
"None",
":",
"sizes",
"=",
"cfg",
".",
"RPN",
... | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f |
train | get_all_anchors_fpn | Returns:
[anchors]: each anchors is a SxSx NUM_ANCHOR_RATIOS x4 array. | examples/FasterRCNN/data.py | def get_all_anchors_fpn(strides=None, sizes=None):
"""
Returns:
[anchors]: each anchors is a SxSx NUM_ANCHOR_RATIOS x4 array.
"""
if strides is None:
strides = cfg.FPN.ANCHOR_STRIDES
if sizes is None:
sizes = cfg.RPN.ANCHOR_SIZES
assert len(strides) == len(sizes)
foas... | def get_all_anchors_fpn(strides=None, sizes=None):
"""
Returns:
[anchors]: each anchors is a SxSx NUM_ANCHOR_RATIOS x4 array.
"""
if strides is None:
strides = cfg.FPN.ANCHOR_STRIDES
if sizes is None:
sizes = cfg.RPN.ANCHOR_SIZES
assert len(strides) == len(sizes)
foas... | [
"Returns",
":",
"[",
"anchors",
"]",
":",
"each",
"anchors",
"is",
"a",
"SxSx",
"NUM_ANCHOR_RATIOS",
"x4",
"array",
"."
] | tensorpack/tensorpack | python | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/data.py#L104-L118 | [
"def",
"get_all_anchors_fpn",
"(",
"strides",
"=",
"None",
",",
"sizes",
"=",
"None",
")",
":",
"if",
"strides",
"is",
"None",
":",
"strides",
"=",
"cfg",
".",
"FPN",
".",
"ANCHOR_STRIDES",
"if",
"sizes",
"is",
"None",
":",
"sizes",
"=",
"cfg",
".",
... | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f |
train | get_anchor_labels | Label each anchor as fg/bg/ignore.
Args:
anchors: Ax4 float
gt_boxes: Bx4 float, non-crowd
crowd_boxes: Cx4 float
Returns:
anchor_labels: (A,) int. Each element is {-1, 0, 1}
anchor_boxes: Ax4. Contains the target gt_box for each anchor when the anchor is fg. | examples/FasterRCNN/data.py | def get_anchor_labels(anchors, gt_boxes, crowd_boxes):
"""
Label each anchor as fg/bg/ignore.
Args:
anchors: Ax4 float
gt_boxes: Bx4 float, non-crowd
crowd_boxes: Cx4 float
Returns:
anchor_labels: (A,) int. Each element is {-1, 0, 1}
anchor_boxes: Ax4. Contains t... | def get_anchor_labels(anchors, gt_boxes, crowd_boxes):
"""
Label each anchor as fg/bg/ignore.
Args:
anchors: Ax4 float
gt_boxes: Bx4 float, non-crowd
crowd_boxes: Cx4 float
Returns:
anchor_labels: (A,) int. Each element is {-1, 0, 1}
anchor_boxes: Ax4. Contains t... | [
"Label",
"each",
"anchor",
"as",
"fg",
"/",
"bg",
"/",
"ignore",
".",
"Args",
":",
"anchors",
":",
"Ax4",
"float",
"gt_boxes",
":",
"Bx4",
"float",
"non",
"-",
"crowd",
"crowd_boxes",
":",
"Cx4",
"float"
] | tensorpack/tensorpack | python | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/data.py#L121-L189 | [
"def",
"get_anchor_labels",
"(",
"anchors",
",",
"gt_boxes",
",",
"crowd_boxes",
")",
":",
"# This function will modify labels and return the filtered inds",
"def",
"filter_box_label",
"(",
"labels",
",",
"value",
",",
"max_num",
")",
":",
"curr_inds",
"=",
"np",
".",... | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f |
train | get_rpn_anchor_input | Args:
im: an image
boxes: nx4, floatbox, gt. shoudn't be changed
is_crowd: n,
Returns:
The anchor labels and target boxes for each pixel in the featuremap.
fm_labels: fHxfWxNA
fm_boxes: fHxfWxNAx4
NA will be NUM_ANCHOR_SIZES x NUM_ANCHOR_RATIOS | examples/FasterRCNN/data.py | def get_rpn_anchor_input(im, boxes, is_crowd):
"""
Args:
im: an image
boxes: nx4, floatbox, gt. shoudn't be changed
is_crowd: n,
Returns:
The anchor labels and target boxes for each pixel in the featuremap.
fm_labels: fHxfWxNA
fm_boxes: fHxfWxNAx4
NA ... | def get_rpn_anchor_input(im, boxes, is_crowd):
"""
Args:
im: an image
boxes: nx4, floatbox, gt. shoudn't be changed
is_crowd: n,
Returns:
The anchor labels and target boxes for each pixel in the featuremap.
fm_labels: fHxfWxNA
fm_boxes: fHxfWxNAx4
NA ... | [
"Args",
":",
"im",
":",
"an",
"image",
"boxes",
":",
"nx4",
"floatbox",
"gt",
".",
"shoudn",
"t",
"be",
"changed",
"is_crowd",
":",
"n"
] | tensorpack/tensorpack | python | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/data.py#L192-L223 | [
"def",
"get_rpn_anchor_input",
"(",
"im",
",",
"boxes",
",",
"is_crowd",
")",
":",
"boxes",
"=",
"boxes",
".",
"copy",
"(",
")",
"all_anchors",
"=",
"np",
".",
"copy",
"(",
"get_all_anchors",
"(",
")",
")",
"# fHxfWxAx4 -> (-1, 4)",
"featuremap_anchors_flatten... | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f |
train | get_multilevel_rpn_anchor_input | Args:
im: an image
boxes: nx4, floatbox, gt. shoudn't be changed
is_crowd: n,
Returns:
[(fm_labels, fm_boxes)]: Returns a tuple for each FPN level.
Each tuple contains the anchor labels and target boxes for each pixel in the featuremap.
fm_labels: fHxfWx NUM_ANCHOR_... | examples/FasterRCNN/data.py | def get_multilevel_rpn_anchor_input(im, boxes, is_crowd):
"""
Args:
im: an image
boxes: nx4, floatbox, gt. shoudn't be changed
is_crowd: n,
Returns:
[(fm_labels, fm_boxes)]: Returns a tuple for each FPN level.
Each tuple contains the anchor labels and target boxes fo... | def get_multilevel_rpn_anchor_input(im, boxes, is_crowd):
"""
Args:
im: an image
boxes: nx4, floatbox, gt. shoudn't be changed
is_crowd: n,
Returns:
[(fm_labels, fm_boxes)]: Returns a tuple for each FPN level.
Each tuple contains the anchor labels and target boxes fo... | [
"Args",
":",
"im",
":",
"an",
"image",
"boxes",
":",
"nx4",
"floatbox",
"gt",
".",
"shoudn",
"t",
"be",
"changed",
"is_crowd",
":",
"n"
] | tensorpack/tensorpack | python | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/data.py#L226-L268 | [
"def",
"get_multilevel_rpn_anchor_input",
"(",
"im",
",",
"boxes",
",",
"is_crowd",
")",
":",
"boxes",
"=",
"boxes",
".",
"copy",
"(",
")",
"anchors_per_level",
"=",
"get_all_anchors_fpn",
"(",
")",
"flatten_anchors_per_level",
"=",
"[",
"k",
".",
"reshape",
"... | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f |
train | get_train_dataflow | Return a training dataflow. Each datapoint consists of the following:
An image: (h, w, 3),
1 or more pairs of (anchor_labels, anchor_boxes):
anchor_labels: (h', w', NA)
anchor_boxes: (h', w', NA, 4)
gt_boxes: (N, 4)
gt_labels: (N,)
If MODE_MASK, gt_masks: (N, h, w) | examples/FasterRCNN/data.py | def get_train_dataflow():
"""
Return a training dataflow. Each datapoint consists of the following:
An image: (h, w, 3),
1 or more pairs of (anchor_labels, anchor_boxes):
anchor_labels: (h', w', NA)
anchor_boxes: (h', w', NA, 4)
gt_boxes: (N, 4)
gt_labels: (N,)
If MODE_MASK, gt_m... | def get_train_dataflow():
"""
Return a training dataflow. Each datapoint consists of the following:
An image: (h, w, 3),
1 or more pairs of (anchor_labels, anchor_boxes):
anchor_labels: (h', w', NA)
anchor_boxes: (h', w', NA, 4)
gt_boxes: (N, 4)
gt_labels: (N,)
If MODE_MASK, gt_m... | [
"Return",
"a",
"training",
"dataflow",
".",
"Each",
"datapoint",
"consists",
"of",
"the",
"following",
":"
] | tensorpack/tensorpack | python | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/data.py#L271-L380 | [
"def",
"get_train_dataflow",
"(",
")",
":",
"roidbs",
"=",
"DetectionDataset",
"(",
")",
".",
"load_training_roidbs",
"(",
"cfg",
".",
"DATA",
".",
"TRAIN",
")",
"print_class_histogram",
"(",
"roidbs",
")",
"# Valid training images should have at least one fg box.",
"... | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f |
train | get_eval_dataflow | Args:
name (str): name of the dataset to evaluate
shard, num_shards: to get subset of evaluation data | examples/FasterRCNN/data.py | def get_eval_dataflow(name, shard=0, num_shards=1):
"""
Args:
name (str): name of the dataset to evaluate
shard, num_shards: to get subset of evaluation data
"""
roidbs = DetectionDataset().load_inference_roidbs(name)
num_imgs = len(roidbs)
img_per_shard = num_imgs // num_shards... | def get_eval_dataflow(name, shard=0, num_shards=1):
"""
Args:
name (str): name of the dataset to evaluate
shard, num_shards: to get subset of evaluation data
"""
roidbs = DetectionDataset().load_inference_roidbs(name)
num_imgs = len(roidbs)
img_per_shard = num_imgs // num_shards... | [
"Args",
":",
"name",
"(",
"str",
")",
":",
"name",
"of",
"the",
"dataset",
"to",
"evaluate",
"shard",
"num_shards",
":",
"to",
"get",
"subset",
"of",
"evaluation",
"data"
] | tensorpack/tensorpack | python | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/data.py#L383-L404 | [
"def",
"get_eval_dataflow",
"(",
"name",
",",
"shard",
"=",
"0",
",",
"num_shards",
"=",
"1",
")",
":",
"roidbs",
"=",
"DetectionDataset",
"(",
")",
".",
"load_inference_roidbs",
"(",
"name",
")",
"num_imgs",
"=",
"len",
"(",
"roidbs",
")",
"img_per_shard"... | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f |
train | override_to_local_variable | Returns:
a context where all variables will be created as local. | tensorpack/graph_builder/utils.py | def override_to_local_variable(enable=True):
"""
Returns:
a context where all variables will be created as local.
"""
if enable:
def custom_getter(getter, name, *args, **kwargs):
_replace_global_by_local(kwargs)
return getter(name, *args, **kwargs)
with ... | def override_to_local_variable(enable=True):
"""
Returns:
a context where all variables will be created as local.
"""
if enable:
def custom_getter(getter, name, *args, **kwargs):
_replace_global_by_local(kwargs)
return getter(name, *args, **kwargs)
with ... | [
"Returns",
":",
"a",
"context",
"where",
"all",
"variables",
"will",
"be",
"created",
"as",
"local",
"."
] | tensorpack/tensorpack | python | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/graph_builder/utils.py#L43-L57 | [
"def",
"override_to_local_variable",
"(",
"enable",
"=",
"True",
")",
":",
"if",
"enable",
":",
"def",
"custom_getter",
"(",
"getter",
",",
"name",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"_replace_global_by_local",
"(",
"kwargs",
")",
"return... | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f |
train | split_grad_list | Args:
grad_list: K x N x 2
Returns:
K x N: gradients
K x N: variables | tensorpack/graph_builder/utils.py | def split_grad_list(grad_list):
"""
Args:
grad_list: K x N x 2
Returns:
K x N: gradients
K x N: variables
"""
g = []
v = []
for tower in grad_list:
g.append([x[0] for x in tower])
v.append([x[1] for x in tower])
return g, v | def split_grad_list(grad_list):
"""
Args:
grad_list: K x N x 2
Returns:
K x N: gradients
K x N: variables
"""
g = []
v = []
for tower in grad_list:
g.append([x[0] for x in tower])
v.append([x[1] for x in tower])
return g, v | [
"Args",
":",
"grad_list",
":",
"K",
"x",
"N",
"x",
"2"
] | tensorpack/tensorpack | python | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/graph_builder/utils.py#L109-L123 | [
"def",
"split_grad_list",
"(",
"grad_list",
")",
":",
"g",
"=",
"[",
"]",
"v",
"=",
"[",
"]",
"for",
"tower",
"in",
"grad_list",
":",
"g",
".",
"append",
"(",
"[",
"x",
"[",
"0",
"]",
"for",
"x",
"in",
"tower",
"]",
")",
"v",
".",
"append",
"... | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f |
train | merge_grad_list | Args:
all_grads (K x N): gradients
all_vars(K x N): variables
Return:
K x N x 2: list of list of (grad, var) pairs | tensorpack/graph_builder/utils.py | def merge_grad_list(all_grads, all_vars):
"""
Args:
all_grads (K x N): gradients
all_vars(K x N): variables
Return:
K x N x 2: list of list of (grad, var) pairs
"""
return [list(zip(gs, vs)) for gs, vs in zip(all_grads, all_vars)] | def merge_grad_list(all_grads, all_vars):
"""
Args:
all_grads (K x N): gradients
all_vars(K x N): variables
Return:
K x N x 2: list of list of (grad, var) pairs
"""
return [list(zip(gs, vs)) for gs, vs in zip(all_grads, all_vars)] | [
"Args",
":",
"all_grads",
"(",
"K",
"x",
"N",
")",
":",
"gradients",
"all_vars",
"(",
"K",
"x",
"N",
")",
":",
"variables"
] | tensorpack/tensorpack | python | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/graph_builder/utils.py#L126-L135 | [
"def",
"merge_grad_list",
"(",
"all_grads",
",",
"all_vars",
")",
":",
"return",
"[",
"list",
"(",
"zip",
"(",
"gs",
",",
"vs",
")",
")",
"for",
"gs",
",",
"vs",
"in",
"zip",
"(",
"all_grads",
",",
"all_vars",
")",
"]"
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f |
train | allreduce_grads | 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 ... | tensorpack/graph_builder/utils.py | 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):
"""
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... | [
"All",
"-",
"reduce",
"average",
"the",
"gradients",
"among",
"K",
"devices",
".",
"Results",
"are",
"broadcasted",
"to",
"all",
"devices",
"."
] | tensorpack/tensorpack | python | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/graph_builder/utils.py#L139-L173 | [
"def",
"allreduce_grads",
"(",
"all_grads",
",",
"average",
")",
":",
"if",
"get_tf_version_tuple",
"(",
")",
"<=",
"(",
"1",
",",
"12",
")",
":",
"from",
"tensorflow",
".",
"contrib",
"import",
"nccl",
"else",
":",
"from",
"tensorflow",
".",
"python",
"... | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f |
train | allreduce_grads_hierarchical | 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... | tensorpack/graph_builder/utils.py | 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):
"""
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.
... | [
"Hierarchical",
"allreduce",
"for",
"DGX",
"-",
"1",
"system",
"."
] | tensorpack/tensorpack | python | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/graph_builder/utils.py#L177-L235 | [
"def",
"allreduce_grads_hierarchical",
"(",
"all_grads",
",",
"devices",
",",
"average",
"=",
"False",
")",
":",
"num_gpu",
"=",
"len",
"(",
"devices",
")",
"assert",
"num_gpu",
"==",
"8",
",",
"num_gpu",
"assert",
"len",
"(",
"all_grads",
")",
"==",
"num_... | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f |
train | aggregate_grads | 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... | tensorpack/graph_builder/utils.py | 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):
"""
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 ... | [
"Average",
"the",
"gradients",
"."
] | tensorpack/tensorpack | python | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/graph_builder/utils.py#L239-L287 | [
"def",
"aggregate_grads",
"(",
"all_grads",
",",
"colocation",
"=",
"False",
",",
"devices",
"=",
"None",
",",
"average",
"=",
"True",
")",
":",
"assert",
"not",
"(",
"devices",
"is",
"not",
"None",
"and",
"colocation",
")",
"if",
"devices",
"is",
"not",... | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f |
train | GradientPacker.compute_strategy | Returns:
bool - False if grads cannot be packed due to various reasons. | tensorpack/graph_builder/utils.py | def compute_strategy(self, grads):
"""
Returns:
bool - False if grads cannot be packed due to various reasons.
"""
for g in grads:
assert g.shape.is_fully_defined(), "Shape of {} is {}!".format(g.name, g.shape)
self._shapes = [g.shape for g in grads]
... | def compute_strategy(self, grads):
"""
Returns:
bool - False if grads cannot be packed due to various reasons.
"""
for g in grads:
assert g.shape.is_fully_defined(), "Shape of {} is {}!".format(g.name, g.shape)
self._shapes = [g.shape for g in grads]
... | [
"Returns",
":",
"bool",
"-",
"False",
"if",
"grads",
"cannot",
"be",
"packed",
"due",
"to",
"various",
"reasons",
"."
] | tensorpack/tensorpack | python | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/graph_builder/utils.py#L337-L364 | [
"def",
"compute_strategy",
"(",
"self",
",",
"grads",
")",
":",
"for",
"g",
"in",
"grads",
":",
"assert",
"g",
".",
"shape",
".",
"is_fully_defined",
"(",
")",
",",
"\"Shape of {} is {}!\"",
".",
"format",
"(",
"g",
".",
"name",
",",
"g",
".",
"shape",... | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f |
train | GradientPacker.pack | Args:
grads (list): list of gradient tensors
Returns:
packed list of gradient tensors to be aggregated. | tensorpack/graph_builder/utils.py | def pack(self, grads):
"""
Args:
grads (list): list of gradient tensors
Returns:
packed list of gradient tensors to be aggregated.
"""
for i, g in enumerate(grads):
assert g.shape == self._shapes[i]
with cached_name_scope("GradientPac... | def pack(self, grads):
"""
Args:
grads (list): list of gradient tensors
Returns:
packed list of gradient tensors to be aggregated.
"""
for i, g in enumerate(grads):
assert g.shape == self._shapes[i]
with cached_name_scope("GradientPac... | [
"Args",
":",
"grads",
"(",
"list",
")",
":",
"list",
"of",
"gradient",
"tensors"
] | tensorpack/tensorpack | python | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/graph_builder/utils.py#L366-L381 | [
"def",
"pack",
"(",
"self",
",",
"grads",
")",
":",
"for",
"i",
",",
"g",
"in",
"enumerate",
"(",
"grads",
")",
":",
"assert",
"g",
".",
"shape",
"==",
"self",
".",
"_shapes",
"[",
"i",
"]",
"with",
"cached_name_scope",
"(",
"\"GradientPacker\"",
","... | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f |
train | GradientPacker.pack_all | Args:
all_grads: K x N, K lists of gradients to be packed | tensorpack/graph_builder/utils.py | def pack_all(self, all_grads, devices):
"""
Args:
all_grads: K x N, K lists of gradients to be packed
"""
ret = [] # #GPU x #split
for dev, grads in zip(devices, all_grads):
with tf.device(dev):
ret.append(self.pack(grads))
retur... | def pack_all(self, all_grads, devices):
"""
Args:
all_grads: K x N, K lists of gradients to be packed
"""
ret = [] # #GPU x #split
for dev, grads in zip(devices, all_grads):
with tf.device(dev):
ret.append(self.pack(grads))
retur... | [
"Args",
":",
"all_grads",
":",
"K",
"x",
"N",
"K",
"lists",
"of",
"gradients",
"to",
"be",
"packed"
] | tensorpack/tensorpack | python | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/graph_builder/utils.py#L391-L400 | [
"def",
"pack_all",
"(",
"self",
",",
"all_grads",
",",
"devices",
")",
":",
"ret",
"=",
"[",
"]",
"# #GPU x #split",
"for",
"dev",
",",
"grads",
"in",
"zip",
"(",
"devices",
",",
"all_grads",
")",
":",
"with",
"tf",
".",
"device",
"(",
"dev",
")",
... | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f |
train | GradientPacker.unpack_all | Args:
all_packed: K lists of packed gradients. | tensorpack/graph_builder/utils.py | def unpack_all(self, all_packed, devices):
"""
Args:
all_packed: K lists of packed gradients.
"""
all_grads = [] # #GPU x #Var
for dev, packed_grads_single_device in zip(devices, all_packed):
with tf.device(dev):
all_grads.append(self.unpa... | def unpack_all(self, all_packed, devices):
"""
Args:
all_packed: K lists of packed gradients.
"""
all_grads = [] # #GPU x #Var
for dev, packed_grads_single_device in zip(devices, all_packed):
with tf.device(dev):
all_grads.append(self.unpa... | [
"Args",
":",
"all_packed",
":",
"K",
"lists",
"of",
"packed",
"gradients",
"."
] | tensorpack/tensorpack | python | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/graph_builder/utils.py#L402-L411 | [
"def",
"unpack_all",
"(",
"self",
",",
"all_packed",
",",
"devices",
")",
":",
"all_grads",
"=",
"[",
"]",
"# #GPU x #Var",
"for",
"dev",
",",
"packed_grads_single_device",
"in",
"zip",
"(",
"devices",
",",
"all_packed",
")",
":",
"with",
"tf",
".",
"devic... | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f |
train | fpn_model | Args:
features ([tf.Tensor]): ResNet features c2-c5
Returns:
[tf.Tensor]: FPN features p2-p6 | examples/FasterRCNN/model_fpn.py | def fpn_model(features):
"""
Args:
features ([tf.Tensor]): ResNet features c2-c5
Returns:
[tf.Tensor]: FPN features p2-p6
"""
assert len(features) == 4, features
num_channel = cfg.FPN.NUM_CHANNEL
use_gn = cfg.FPN.NORM == 'GN'
def upsample2x(name, x):
return Fix... | def fpn_model(features):
"""
Args:
features ([tf.Tensor]): ResNet features c2-c5
Returns:
[tf.Tensor]: FPN features p2-p6
"""
assert len(features) == 4, features
num_channel = cfg.FPN.NUM_CHANNEL
use_gn = cfg.FPN.NORM == 'GN'
def upsample2x(name, x):
return Fix... | [
"Args",
":",
"features",
"(",
"[",
"tf",
".",
"Tensor",
"]",
")",
":",
"ResNet",
"features",
"c2",
"-",
"c5"
] | tensorpack/tensorpack | python | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/model_fpn.py#L21-L66 | [
"def",
"fpn_model",
"(",
"features",
")",
":",
"assert",
"len",
"(",
"features",
")",
"==",
"4",
",",
"features",
"num_channel",
"=",
"cfg",
".",
"FPN",
".",
"NUM_CHANNEL",
"use_gn",
"=",
"cfg",
".",
"FPN",
".",
"NORM",
"==",
"'GN'",
"def",
"upsample2x... | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f |
train | fpn_map_rois_to_levels | 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. | examples/FasterRCNN/model_fpn.py | 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):
"""
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... | [
"Assign",
"boxes",
"to",
"level",
"2~5",
"."
] | tensorpack/tensorpack | python | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/model_fpn.py#L70-L100 | [
"def",
"fpn_map_rois_to_levels",
"(",
"boxes",
")",
":",
"sqrtarea",
"=",
"tf",
".",
"sqrt",
"(",
"tf_area",
"(",
"boxes",
")",
")",
"level",
"=",
"tf",
".",
"cast",
"(",
"tf",
".",
"floor",
"(",
"4",
"+",
"tf",
".",
"log",
"(",
"sqrtarea",
"*",
... | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f |
train | multilevel_roi_align | Args:
features ([tf.Tensor]): 4 FPN feature level 2-5
rcnn_boxes (tf.Tensor): nx4 boxes
resolution (int): output spatial resolution
Returns:
NxC x res x res | examples/FasterRCNN/model_fpn.py | def multilevel_roi_align(features, rcnn_boxes, resolution):
"""
Args:
features ([tf.Tensor]): 4 FPN feature level 2-5
rcnn_boxes (tf.Tensor): nx4 boxes
resolution (int): output spatial resolution
Returns:
NxC x res x res
"""
assert len(features) == 4, features
# R... | def multilevel_roi_align(features, rcnn_boxes, resolution):
"""
Args:
features ([tf.Tensor]): 4 FPN feature level 2-5
rcnn_boxes (tf.Tensor): nx4 boxes
resolution (int): output spatial resolution
Returns:
NxC x res x res
"""
assert len(features) == 4, features
# R... | [
"Args",
":",
"features",
"(",
"[",
"tf",
".",
"Tensor",
"]",
")",
":",
"4",
"FPN",
"feature",
"level",
"2",
"-",
"5",
"rcnn_boxes",
"(",
"tf",
".",
"Tensor",
")",
":",
"nx4",
"boxes",
"resolution",
"(",
"int",
")",
":",
"output",
"spatial",
"resolu... | tensorpack/tensorpack | python | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/model_fpn.py#L104-L130 | [
"def",
"multilevel_roi_align",
"(",
"features",
",",
"rcnn_boxes",
",",
"resolution",
")",
":",
"assert",
"len",
"(",
"features",
")",
"==",
"4",
",",
"features",
"# Reassign rcnn_boxes to levels",
"level_ids",
",",
"level_boxes",
"=",
"fpn_map_rois_to_levels",
"(",... | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f |
train | multilevel_rpn_losses | Args:
multilevel_anchors: #lvl RPNAnchors
multilevel_label_logits: #lvl tensors of shape HxWxA
multilevel_box_logits: #lvl tensors of shape HxWxAx4
Returns:
label_loss, box_loss | examples/FasterRCNN/model_fpn.py | def multilevel_rpn_losses(
multilevel_anchors, multilevel_label_logits, multilevel_box_logits):
"""
Args:
multilevel_anchors: #lvl RPNAnchors
multilevel_label_logits: #lvl tensors of shape HxWxA
multilevel_box_logits: #lvl tensors of shape HxWxAx4
Returns:
label_loss... | def multilevel_rpn_losses(
multilevel_anchors, multilevel_label_logits, multilevel_box_logits):
"""
Args:
multilevel_anchors: #lvl RPNAnchors
multilevel_label_logits: #lvl tensors of shape HxWxA
multilevel_box_logits: #lvl tensors of shape HxWxAx4
Returns:
label_loss... | [
"Args",
":",
"multilevel_anchors",
":",
"#lvl",
"RPNAnchors",
"multilevel_label_logits",
":",
"#lvl",
"tensors",
"of",
"shape",
"HxWxA",
"multilevel_box_logits",
":",
"#lvl",
"tensors",
"of",
"shape",
"HxWxAx4"
] | tensorpack/tensorpack | python | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/model_fpn.py#L133-L162 | [
"def",
"multilevel_rpn_losses",
"(",
"multilevel_anchors",
",",
"multilevel_label_logits",
",",
"multilevel_box_logits",
")",
":",
"num_lvl",
"=",
"len",
"(",
"cfg",
".",
"FPN",
".",
"ANCHOR_STRIDES",
")",
"assert",
"len",
"(",
"multilevel_anchors",
")",
"==",
"nu... | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f |
train | generate_fpn_proposals | Args:
multilevel_pred_boxes: #lvl HxWxAx4 boxes
multilevel_label_logits: #lvl tensors of shape HxWxA
Returns:
boxes: kx4 float
scores: k logits | examples/FasterRCNN/model_fpn.py | def generate_fpn_proposals(
multilevel_pred_boxes, multilevel_label_logits, image_shape2d):
"""
Args:
multilevel_pred_boxes: #lvl HxWxAx4 boxes
multilevel_label_logits: #lvl tensors of shape HxWxA
Returns:
boxes: kx4 float
scores: k logits
"""
num_lvl = len(c... | def generate_fpn_proposals(
multilevel_pred_boxes, multilevel_label_logits, image_shape2d):
"""
Args:
multilevel_pred_boxes: #lvl HxWxAx4 boxes
multilevel_label_logits: #lvl tensors of shape HxWxA
Returns:
boxes: kx4 float
scores: k logits
"""
num_lvl = len(c... | [
"Args",
":",
"multilevel_pred_boxes",
":",
"#lvl",
"HxWxAx4",
"boxes",
"multilevel_label_logits",
":",
"#lvl",
"tensors",
"of",
"shape",
"HxWxA"
] | tensorpack/tensorpack | python | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/model_fpn.py#L166-L219 | [
"def",
"generate_fpn_proposals",
"(",
"multilevel_pred_boxes",
",",
"multilevel_label_logits",
",",
"image_shape2d",
")",
":",
"num_lvl",
"=",
"len",
"(",
"cfg",
".",
"FPN",
".",
"ANCHOR_STRIDES",
")",
"assert",
"len",
"(",
"multilevel_pred_boxes",
")",
"==",
"num... | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f |
train | LayerNorm | Layer Normalization layer, as described in the paper:
`Layer Normalization <https://arxiv.org/abs/1607.06450>`_.
Args:
x (tf.Tensor): a 4D or 2D tensor. When 4D, the layout should match data_format.
epsilon (float): epsilon to avoid divide-by-zero.
use_scale, use_bias (bool): whether to... | tensorpack/models/layer_norm.py | def LayerNorm(
x, epsilon=1e-5,
use_bias=True, use_scale=True,
gamma_init=None, data_format='channels_last'):
"""
Layer Normalization layer, as described in the paper:
`Layer Normalization <https://arxiv.org/abs/1607.06450>`_.
Args:
x (tf.Tensor): a 4D or 2D tensor. When... | def LayerNorm(
x, epsilon=1e-5,
use_bias=True, use_scale=True,
gamma_init=None, data_format='channels_last'):
"""
Layer Normalization layer, as described in the paper:
`Layer Normalization <https://arxiv.org/abs/1607.06450>`_.
Args:
x (tf.Tensor): a 4D or 2D tensor. When... | [
"Layer",
"Normalization",
"layer",
"as",
"described",
"in",
"the",
"paper",
":",
"Layer",
"Normalization",
"<https",
":",
"//",
"arxiv",
".",
"org",
"/",
"abs",
"/",
"1607",
".",
"06450",
">",
"_",
"."
] | tensorpack/tensorpack | python | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/models/layer_norm.py#L14-L63 | [
"def",
"LayerNorm",
"(",
"x",
",",
"epsilon",
"=",
"1e-5",
",",
"use_bias",
"=",
"True",
",",
"use_scale",
"=",
"True",
",",
"gamma_init",
"=",
"None",
",",
"data_format",
"=",
"'channels_last'",
")",
":",
"data_format",
"=",
"get_data_format",
"(",
"data_... | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f |
train | InstanceNorm | Instance Normalization, as in the paper:
`Instance Normalization: The Missing Ingredient for Fast Stylization
<https://arxiv.org/abs/1607.08022>`_.
Args:
x (tf.Tensor): a 4D tensor.
epsilon (float): avoid divide-by-zero
use_affine (bool): whether to apply learnable affine transforma... | tensorpack/models/layer_norm.py | def InstanceNorm(x, epsilon=1e-5, use_affine=True, gamma_init=None, data_format='channels_last'):
"""
Instance Normalization, as in the paper:
`Instance Normalization: The Missing Ingredient for Fast Stylization
<https://arxiv.org/abs/1607.08022>`_.
Args:
x (tf.Tensor): a 4D tensor.
... | def InstanceNorm(x, epsilon=1e-5, use_affine=True, gamma_init=None, data_format='channels_last'):
"""
Instance Normalization, as in the paper:
`Instance Normalization: The Missing Ingredient for Fast Stylization
<https://arxiv.org/abs/1607.08022>`_.
Args:
x (tf.Tensor): a 4D tensor.
... | [
"Instance",
"Normalization",
"as",
"in",
"the",
"paper",
":",
"Instance",
"Normalization",
":",
"The",
"Missing",
"Ingredient",
"for",
"Fast",
"Stylization",
"<https",
":",
"//",
"arxiv",
".",
"org",
"/",
"abs",
"/",
"1607",
".",
"08022",
">",
"_",
"."
] | tensorpack/tensorpack | python | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/models/layer_norm.py#L67-L109 | [
"def",
"InstanceNorm",
"(",
"x",
",",
"epsilon",
"=",
"1e-5",
",",
"use_affine",
"=",
"True",
",",
"gamma_init",
"=",
"None",
",",
"data_format",
"=",
"'channels_last'",
")",
":",
"data_format",
"=",
"get_data_format",
"(",
"data_format",
",",
"keras_mode",
... | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f |
train | proposal_metrics | Add summaries for RPN proposals.
Args:
iou: nxm, #proposal x #gt | examples/FasterRCNN/model_frcnn.py | 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):
"""
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]
... | [
"Add",
"summaries",
"for",
"RPN",
"proposals",
"."
] | tensorpack/tensorpack | python | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/model_frcnn.py#L20-L38 | [
"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",
"=... | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f |
train | sample_fast_rcnn_targets | Sample some boxes from all proposals for training.
#fg is guaranteed to be > 0, because ground truth boxes will be added as proposals.
Args:
boxes: nx4 region proposals, floatbox
gt_boxes: mx4, floatbox
gt_labels: m, int32
Returns:
A BoxProposals instance.
sampled_b... | examples/FasterRCNN/model_frcnn.py | def sample_fast_rcnn_targets(boxes, gt_boxes, gt_labels):
"""
Sample some boxes from all proposals for training.
#fg is guaranteed to be > 0, because ground truth boxes will be added as proposals.
Args:
boxes: nx4 region proposals, floatbox
gt_boxes: mx4, floatbox
gt_labels: m, ... | def sample_fast_rcnn_targets(boxes, gt_boxes, gt_labels):
"""
Sample some boxes from all proposals for training.
#fg is guaranteed to be > 0, because ground truth boxes will be added as proposals.
Args:
boxes: nx4 region proposals, floatbox
gt_boxes: mx4, floatbox
gt_labels: m, ... | [
"Sample",
"some",
"boxes",
"from",
"all",
"proposals",
"for",
"training",
".",
"#fg",
"is",
"guaranteed",
"to",
"be",
">",
"0",
"because",
"ground",
"truth",
"boxes",
"will",
"be",
"added",
"as",
"proposals",
"."
] | tensorpack/tensorpack | python | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/model_frcnn.py#L42-L101 | [
"def",
"sample_fast_rcnn_targets",
"(",
"boxes",
",",
"gt_boxes",
",",
"gt_labels",
")",
":",
"iou",
"=",
"pairwise_iou",
"(",
"boxes",
",",
"gt_boxes",
")",
"# nxm",
"proposal_metrics",
"(",
"iou",
")",
"# add ground truth as proposals as well",
"boxes",
"=",
"tf... | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f |
train | fastrcnn_outputs | Args:
feature (any shape):
num_classes(int): num_category + 1
class_agnostic_regression (bool): if True, regression to N x 1 x 4
Returns:
cls_logits: N x num_class classification logits
reg_logits: N x num_classx4 or Nx2x4 if class agnostic | examples/FasterRCNN/model_frcnn.py | def fastrcnn_outputs(feature, num_classes, class_agnostic_regression=False):
"""
Args:
feature (any shape):
num_classes(int): num_category + 1
class_agnostic_regression (bool): if True, regression to N x 1 x 4
Returns:
cls_logits: N x num_class classification logits
... | def fastrcnn_outputs(feature, num_classes, class_agnostic_regression=False):
"""
Args:
feature (any shape):
num_classes(int): num_category + 1
class_agnostic_regression (bool): if True, regression to N x 1 x 4
Returns:
cls_logits: N x num_class classification logits
... | [
"Args",
":",
"feature",
"(",
"any",
"shape",
")",
":",
"num_classes",
"(",
"int",
")",
":",
"num_category",
"+",
"1",
"class_agnostic_regression",
"(",
"bool",
")",
":",
"if",
"True",
"regression",
"to",
"N",
"x",
"1",
"x",
"4"
] | tensorpack/tensorpack | python | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/model_frcnn.py#L105-L124 | [
"def",
"fastrcnn_outputs",
"(",
"feature",
",",
"num_classes",
",",
"class_agnostic_regression",
"=",
"False",
")",
":",
"classification",
"=",
"FullyConnected",
"(",
"'class'",
",",
"feature",
",",
"num_classes",
",",
"kernel_initializer",
"=",
"tf",
".",
"random... | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f |
train | fastrcnn_losses | Args:
labels: n,
label_logits: nxC
fg_boxes: nfgx4, encoded
fg_box_logits: nfgxCx4 or nfgx1x4 if class agnostic
Returns:
label_loss, box_loss | examples/FasterRCNN/model_frcnn.py | def fastrcnn_losses(labels, label_logits, fg_boxes, fg_box_logits):
"""
Args:
labels: n,
label_logits: nxC
fg_boxes: nfgx4, encoded
fg_box_logits: nfgxCx4 or nfgx1x4 if class agnostic
Returns:
label_loss, box_loss
"""
label_loss = tf.nn.sparse_softmax_cross_e... | def fastrcnn_losses(labels, label_logits, fg_boxes, fg_box_logits):
"""
Args:
labels: n,
label_logits: nxC
fg_boxes: nfgx4, encoded
fg_box_logits: nfgxCx4 or nfgx1x4 if class agnostic
Returns:
label_loss, box_loss
"""
label_loss = tf.nn.sparse_softmax_cross_e... | [
"Args",
":",
"labels",
":",
"n",
"label_logits",
":",
"nxC",
"fg_boxes",
":",
"nfgx4",
"encoded",
"fg_box_logits",
":",
"nfgxCx4",
"or",
"nfgx1x4",
"if",
"class",
"agnostic"
] | tensorpack/tensorpack | python | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/model_frcnn.py#L128-L172 | [
"def",
"fastrcnn_losses",
"(",
"labels",
",",
"label_logits",
",",
"fg_boxes",
",",
"fg_box_logits",
")",
":",
"label_loss",
"=",
"tf",
".",
"nn",
".",
"sparse_softmax_cross_entropy_with_logits",
"(",
"labels",
"=",
"labels",
",",
"logits",
"=",
"label_logits",
... | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f |
train | fastrcnn_predictions | 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 | examples/FasterRCNN/model_frcnn.py | 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):
"""
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
... | [
"Generate",
"final",
"results",
"from",
"predictions",
"of",
"all",
"proposals",
"."
] | tensorpack/tensorpack | python | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/model_frcnn.py#L176-L247 | [
"def",
"fastrcnn_predictions",
"(",
"boxes",
",",
"scores",
")",
":",
"assert",
"boxes",
".",
"shape",
"[",
"1",
"]",
"==",
"cfg",
".",
"DATA",
".",
"NUM_CLASS",
"assert",
"scores",
".",
"shape",
"[",
"1",
"]",
"==",
"cfg",
".",
"DATA",
".",
"NUM_CLA... | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f |
train | fastrcnn_2fc_head | Args:
feature (any shape):
Returns:
2D head feature | examples/FasterRCNN/model_frcnn.py | def fastrcnn_2fc_head(feature):
"""
Args:
feature (any shape):
Returns:
2D head feature
"""
dim = cfg.FPN.FRCNN_FC_HEAD_DIM
init = tf.variance_scaling_initializer()
hidden = FullyConnected('fc6', feature, dim, kernel_initializer=init, activation=tf.nn.relu)
hidden = Full... | def fastrcnn_2fc_head(feature):
"""
Args:
feature (any shape):
Returns:
2D head feature
"""
dim = cfg.FPN.FRCNN_FC_HEAD_DIM
init = tf.variance_scaling_initializer()
hidden = FullyConnected('fc6', feature, dim, kernel_initializer=init, activation=tf.nn.relu)
hidden = Full... | [
"Args",
":",
"feature",
"(",
"any",
"shape",
")",
":"
] | tensorpack/tensorpack | python | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/model_frcnn.py#L256-L268 | [
"def",
"fastrcnn_2fc_head",
"(",
"feature",
")",
":",
"dim",
"=",
"cfg",
".",
"FPN",
".",
"FRCNN_FC_HEAD_DIM",
"init",
"=",
"tf",
".",
"variance_scaling_initializer",
"(",
")",
"hidden",
"=",
"FullyConnected",
"(",
"'fc6'",
",",
"feature",
",",
"dim",
",",
... | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f |
train | fastrcnn_Xconv1fc_head | Args:
feature (NCHW):
num_classes(int): num_category + 1
num_convs (int): number of conv layers
norm (str or None): either None or 'GN'
Returns:
2D head feature | examples/FasterRCNN/model_frcnn.py | def fastrcnn_Xconv1fc_head(feature, num_convs, norm=None):
"""
Args:
feature (NCHW):
num_classes(int): num_category + 1
num_convs (int): number of conv layers
norm (str or None): either None or 'GN'
Returns:
2D head feature
"""
assert norm in [None, 'GN'], no... | def fastrcnn_Xconv1fc_head(feature, num_convs, norm=None):
"""
Args:
feature (NCHW):
num_classes(int): num_category + 1
num_convs (int): number of conv layers
norm (str or None): either None or 'GN'
Returns:
2D head feature
"""
assert norm in [None, 'GN'], no... | [
"Args",
":",
"feature",
"(",
"NCHW",
")",
":",
"num_classes",
"(",
"int",
")",
":",
"num_category",
"+",
"1",
"num_convs",
"(",
"int",
")",
":",
"number",
"of",
"conv",
"layers",
"norm",
"(",
"str",
"or",
"None",
")",
":",
"either",
"None",
"or",
"... | tensorpack/tensorpack | python | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/model_frcnn.py#L272-L295 | [
"def",
"fastrcnn_Xconv1fc_head",
"(",
"feature",
",",
"num_convs",
",",
"norm",
"=",
"None",
")",
":",
"assert",
"norm",
"in",
"[",
"None",
",",
"'GN'",
"]",
",",
"norm",
"l",
"=",
"feature",
"with",
"argscope",
"(",
"Conv2D",
",",
"data_format",
"=",
... | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f |
train | FastRCNNHead.fg_box_logits | Returns: #fg x ? x 4 | examples/FasterRCNN/model_frcnn.py | def fg_box_logits(self):
""" Returns: #fg x ? x 4 """
return tf.gather(self.box_logits, self.proposals.fg_inds(), name='fg_box_logits') | def fg_box_logits(self):
""" Returns: #fg x ? x 4 """
return tf.gather(self.box_logits, self.proposals.fg_inds(), name='fg_box_logits') | [
"Returns",
":",
"#fg",
"x",
"?",
"x",
"4"
] | tensorpack/tensorpack | python | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/model_frcnn.py#L358-L360 | [
"def",
"fg_box_logits",
"(",
"self",
")",
":",
"return",
"tf",
".",
"gather",
"(",
"self",
".",
"box_logits",
",",
"self",
".",
"proposals",
".",
"fg_inds",
"(",
")",
",",
"name",
"=",
"'fg_box_logits'",
")"
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f |
train | FastRCNNHead.decoded_output_boxes | Returns: N x #class x 4 | examples/FasterRCNN/model_frcnn.py | def decoded_output_boxes(self):
""" Returns: N x #class x 4 """
anchors = tf.tile(tf.expand_dims(self.proposals.boxes, 1),
[1, cfg.DATA.NUM_CLASS, 1]) # N x #class x 4
decoded_boxes = decode_bbox_target(
self.box_logits / self.bbox_regression_weights,
... | def decoded_output_boxes(self):
""" Returns: N x #class x 4 """
anchors = tf.tile(tf.expand_dims(self.proposals.boxes, 1),
[1, cfg.DATA.NUM_CLASS, 1]) # N x #class x 4
decoded_boxes = decode_bbox_target(
self.box_logits / self.bbox_regression_weights,
... | [
"Returns",
":",
"N",
"x",
"#class",
"x",
"4"
] | tensorpack/tensorpack | python | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/model_frcnn.py#L373-L381 | [
"def",
"decoded_output_boxes",
"(",
"self",
")",
":",
"anchors",
"=",
"tf",
".",
"tile",
"(",
"tf",
".",
"expand_dims",
"(",
"self",
".",
"proposals",
".",
"boxes",
",",
"1",
")",
",",
"[",
"1",
",",
"cfg",
".",
"DATA",
".",
"NUM_CLASS",
",",
"1",
... | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f |
train | FastRCNNHead.decoded_output_boxes_class_agnostic | Returns: Nx4 | examples/FasterRCNN/model_frcnn.py | def decoded_output_boxes_class_agnostic(self):
""" Returns: Nx4 """
assert self._bbox_class_agnostic
box_logits = tf.reshape(self.box_logits, [-1, 4])
decoded = decode_bbox_target(
box_logits / self.bbox_regression_weights,
self.proposals.boxes
)
r... | def decoded_output_boxes_class_agnostic(self):
""" Returns: Nx4 """
assert self._bbox_class_agnostic
box_logits = tf.reshape(self.box_logits, [-1, 4])
decoded = decode_bbox_target(
box_logits / self.bbox_regression_weights,
self.proposals.boxes
)
r... | [
"Returns",
":",
"Nx4"
] | tensorpack/tensorpack | python | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/model_frcnn.py#L408-L416 | [
"def",
"decoded_output_boxes_class_agnostic",
"(",
"self",
")",
":",
"assert",
"self",
".",
"_bbox_class_agnostic",
"box_logits",
"=",
"tf",
".",
"reshape",
"(",
"self",
".",
"box_logits",
",",
"[",
"-",
"1",
",",
"4",
"]",
")",
"decoded",
"=",
"decode_bbox_... | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f |
train | FastRCNNHead.output_scores | Returns: N x #class scores, summed to one for each box. | examples/FasterRCNN/model_frcnn.py | def output_scores(self, name=None):
""" Returns: N x #class scores, summed to one for each box."""
return tf.nn.softmax(self.label_logits, name=name) | def output_scores(self, name=None):
""" Returns: N x #class scores, summed to one for each box."""
return tf.nn.softmax(self.label_logits, name=name) | [
"Returns",
":",
"N",
"x",
"#class",
"scores",
"summed",
"to",
"one",
"for",
"each",
"box",
"."
] | tensorpack/tensorpack | python | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/model_frcnn.py#L419-L421 | [
"def",
"output_scores",
"(",
"self",
",",
"name",
"=",
"None",
")",
":",
"return",
"tf",
".",
"nn",
".",
"softmax",
"(",
"self",
".",
"label_logits",
",",
"name",
"=",
"name",
")"
] | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f |
train | MySimulatorMaster._on_state | Launch forward prediction for the new state given by some client. | examples/A3C-Gym/train-atari.py | 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):
"""
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... | [
"Launch",
"forward",
"prediction",
"for",
"the",
"new",
"state",
"given",
"by",
"some",
"client",
"."
] | tensorpack/tensorpack | python | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/A3C-Gym/train-atari.py#L159-L174 | [
"def",
"_on_state",
"(",
"self",
",",
"state",
",",
"client",
")",
":",
"def",
"cb",
"(",
"outputs",
")",
":",
"try",
":",
"distrib",
",",
"value",
"=",
"outputs",
".",
"result",
"(",
")",
"except",
"CancelledError",
":",
"logger",
".",
"info",
"(",
... | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f |
train | MySimulatorMaster._process_msg | Process a message sent from some client. | examples/A3C-Gym/train-atari.py | 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):
"""
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... | [
"Process",
"a",
"message",
"sent",
"from",
"some",
"client",
"."
] | tensorpack/tensorpack | python | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/A3C-Gym/train-atari.py#L176-L192 | [
"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",... | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f |
train | Model.discriminator | return a (b, 1) logits | examples/GAN/ConditionalGAN-mnist.py | def discriminator(self, imgs, y):
""" return a (b, 1) logits"""
yv = y
y = tf.reshape(y, [-1, 1, 1, 10])
with argscope(Conv2D, kernel_size=5, strides=1):
l = (LinearWrap(imgs)
.ConcatWith(tf.tile(y, [1, 28, 28, 1]), 3)
.Conv2D('conv0', 11)
... | def discriminator(self, imgs, y):
""" return a (b, 1) logits"""
yv = y
y = tf.reshape(y, [-1, 1, 1, 10])
with argscope(Conv2D, kernel_size=5, strides=1):
l = (LinearWrap(imgs)
.ConcatWith(tf.tile(y, [1, 28, 28, 1]), 3)
.Conv2D('conv0', 11)
... | [
"return",
"a",
"(",
"b",
"1",
")",
"logits"
] | tensorpack/tensorpack | python | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/GAN/ConditionalGAN-mnist.py#L62-L85 | [
"def",
"discriminator",
"(",
"self",
",",
"imgs",
",",
"y",
")",
":",
"yv",
"=",
"y",
"y",
"=",
"tf",
".",
"reshape",
"(",
"y",
",",
"[",
"-",
"1",
",",
"1",
",",
"1",
",",
"10",
"]",
")",
"with",
"argscope",
"(",
"Conv2D",
",",
"kernel_size"... | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f |
train | ModelExporter.export_compact | Create a self-contained inference-only graph and write final graph (in pb format) to disk.
Args:
filename (str): path to the output graph
optimize (bool): whether to use TensorFlow's `optimize_for_inference`
to prune and optimize the graph. This does not work on all type... | tensorpack/tfutils/export.py | def export_compact(self, filename, optimize=True, toco_compatible=False):
"""Create a self-contained inference-only graph and write final graph (in pb format) to disk.
Args:
filename (str): path to the output graph
optimize (bool): whether to use TensorFlow's `optimize_for_infer... | def export_compact(self, filename, optimize=True, toco_compatible=False):
"""Create a self-contained inference-only graph and write final graph (in pb format) to disk.
Args:
filename (str): path to the output graph
optimize (bool): whether to use TensorFlow's `optimize_for_infer... | [
"Create",
"a",
"self",
"-",
"contained",
"inference",
"-",
"only",
"graph",
"and",
"write",
"final",
"graph",
"(",
"in",
"pb",
"format",
")",
"to",
"disk",
"."
] | tensorpack/tensorpack | python | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/tfutils/export.py#L38-L89 | [
"def",
"export_compact",
"(",
"self",
",",
"filename",
",",
"optimize",
"=",
"True",
",",
"toco_compatible",
"=",
"False",
")",
":",
"if",
"toco_compatible",
":",
"assert",
"optimize",
",",
"\"toco_compatible is only effective when optimize=True!\"",
"self",
".",
"g... | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f |
train | ModelExporter.export_serving | 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): ... | tensorpack/tfutils/export.py | 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='prediction_pipeline'):
"""
Converts a checkpoint and graph to a servable for TensorFlow Serving.
Use TF's `SavedM... | [
"Converts",
"a",
"checkpoint",
"and",
"graph",
"to",
"a",
"servable",
"for",
"TensorFlow",
"Serving",
".",
"Use",
"TF",
"s",
"SavedModelBuilder",
"to",
"export",
"a",
"trained",
"model",
"without",
"tensorpack",
"dependency",
"."
] | tensorpack/tensorpack | python | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/tfutils/export.py#L91-L146 | [
"def",
"export_serving",
"(",
"self",
",",
"filename",
",",
"tags",
"=",
"[",
"tf",
".",
"saved_model",
".",
"SERVING",
"if",
"is_tfv2",
"(",
")",
"else",
"tf",
".",
"saved_model",
".",
"tag_constants",
".",
"SERVING",
"]",
",",
"signature_name",
"=",
"'... | d7a13cb74c9066bc791d7aafc3b744b60ee79a9f |
train | _read_sql_with_offset_pandas_on_ray | Use a Ray task to read a chunk of SQL source.
Note: Ray functions are not detected by codecov (thus pragma: no cover) | modin/experimental/engines/pandas_on_ray/io_exp.py | def _read_sql_with_offset_pandas_on_ray(
partition_column,
start,
end,
num_splits,
sql,
con,
index_col=None,
coerce_float=True,
params=None,
parse_dates=None,
columns=None,
chunksize=None,
): # pragma: no cover
"""Use a Ray task to read a chunk of SQL source.
No... | def _read_sql_with_offset_pandas_on_ray(
partition_column,
start,
end,
num_splits,
sql,
con,
index_col=None,
coerce_float=True,
params=None,
parse_dates=None,
columns=None,
chunksize=None,
): # pragma: no cover
"""Use a Ray task to read a chunk of SQL source.
No... | [
"Use",
"a",
"Ray",
"task",
"to",
"read",
"a",
"chunk",
"of",
"SQL",
"source",
"."
] | modin-project/modin | python | https://github.com/modin-project/modin/blob/5b77d242596560c646b8405340c9ce64acb183cb/modin/experimental/engines/pandas_on_ray/io_exp.py#L119-L152 | [
"def",
"_read_sql_with_offset_pandas_on_ray",
"(",
"partition_column",
",",
"start",
",",
"end",
",",
"num_splits",
",",
"sql",
",",
"con",
",",
"index_col",
"=",
"None",
",",
"coerce_float",
"=",
"True",
",",
"params",
"=",
"None",
",",
"parse_dates",
"=",
... | 5b77d242596560c646b8405340c9ce64acb183cb |
train | ExperimentalPandasOnRayIO.read_sql | Read SQL query or database table into a DataFrame.
Args:
sql: string or SQLAlchemy Selectable (select or text object) SQL query to be executed or a table name.
con: SQLAlchemy connectable (engine/connection) or database string URI or DBAPI2 connection (fallback mode)
index_c... | modin/experimental/engines/pandas_on_ray/io_exp.py | def read_sql(
cls,
sql,
con,
index_col=None,
coerce_float=True,
params=None,
parse_dates=None,
columns=None,
chunksize=None,
partition_column=None,
lower_bound=None,
upper_bound=None,
max_sessions=None,
):
... | def read_sql(
cls,
sql,
con,
index_col=None,
coerce_float=True,
params=None,
parse_dates=None,
columns=None,
chunksize=None,
partition_column=None,
lower_bound=None,
upper_bound=None,
max_sessions=None,
):
... | [
"Read",
"SQL",
"query",
"or",
"database",
"table",
"into",
"a",
"DataFrame",
"."
] | modin-project/modin | python | https://github.com/modin-project/modin/blob/5b77d242596560c646b8405340c9ce64acb183cb/modin/experimental/engines/pandas_on_ray/io_exp.py#L12-L115 | [
"def",
"read_sql",
"(",
"cls",
",",
"sql",
",",
"con",
",",
"index_col",
"=",
"None",
",",
"coerce_float",
"=",
"True",
",",
"params",
"=",
"None",
",",
"parse_dates",
"=",
"None",
",",
"columns",
"=",
"None",
",",
"chunksize",
"=",
"None",
",",
"par... | 5b77d242596560c646b8405340c9ce64acb183cb |
train | _inherit_docstrings | Creates a decorator which overwrites a decorated class' __doc__
attribute with parent's __doc__ attribute. Also overwrites __doc__ of
methods and properties defined in the class with the __doc__ of matching
methods and properties in parent.
Args:
parent (object): Class from which the decorated ... | modin/pandas/utils.py | def _inherit_docstrings(parent, excluded=[]):
"""Creates a decorator which overwrites a decorated class' __doc__
attribute with parent's __doc__ attribute. Also overwrites __doc__ of
methods and properties defined in the class with the __doc__ of matching
methods and properties in parent.
Args:
... | def _inherit_docstrings(parent, excluded=[]):
"""Creates a decorator which overwrites a decorated class' __doc__
attribute with parent's __doc__ attribute. Also overwrites __doc__ of
methods and properties defined in the class with the __doc__ of matching
methods and properties in parent.
Args:
... | [
"Creates",
"a",
"decorator",
"which",
"overwrites",
"a",
"decorated",
"class",
"__doc__",
"attribute",
"with",
"parent",
"s",
"__doc__",
"attribute",
".",
"Also",
"overwrites",
"__doc__",
"of",
"methods",
"and",
"properties",
"defined",
"in",
"the",
"class",
"wi... | modin-project/modin | python | https://github.com/modin-project/modin/blob/5b77d242596560c646b8405340c9ce64acb183cb/modin/pandas/utils.py#L33-L65 | [
"def",
"_inherit_docstrings",
"(",
"parent",
",",
"excluded",
"=",
"[",
"]",
")",
":",
"def",
"decorator",
"(",
"cls",
")",
":",
"if",
"parent",
"not",
"in",
"excluded",
":",
"cls",
".",
"__doc__",
"=",
"parent",
".",
"__doc__",
"for",
"attr",
",",
"... | 5b77d242596560c646b8405340c9ce64acb183cb |
train | time_logger | This logs the time usage of a code block | ci/benchmarks/utils.py | 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):
"""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) | [
"This",
"logs",
"the",
"time",
"usage",
"of",
"a",
"code",
"block"
] | modin-project/modin | python | https://github.com/modin-project/modin/blob/5b77d242596560c646b8405340c9ce64acb183cb/ci/benchmarks/utils.py#L12-L19 | [
"def",
"time_logger",
"(",
"name",
")",
":",
"start_time",
"=",
"time",
".",
"time",
"(",
")",
"yield",
"end_time",
"=",
"time",
".",
"time",
"(",
")",
"total_time",
"=",
"end_time",
"-",
"start_time",
"logging",
".",
"info",
"(",
"\"%s; time: %ss\"",
",... | 5b77d242596560c646b8405340c9ce64acb183cb |
train | initialize_ray | Initializes ray based on environment variables and internal defaults. | modin/pandas/__init__.py | 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():
"""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()... | [
"Initializes",
"ray",
"based",
"on",
"environment",
"variables",
"and",
"internal",
"defaults",
"."
] | modin-project/modin | python | https://github.com/modin-project/modin/blob/5b77d242596560c646b8405340c9ce64acb183cb/modin/pandas/__init__.py#L133-L168 | [
"def",
"initialize_ray",
"(",
")",
":",
"if",
"threading",
".",
"current_thread",
"(",
")",
".",
"name",
"==",
"\"MainThread\"",
":",
"plasma_directory",
"=",
"None",
"object_store_memory",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"\"MODIN_MEMORY\"",
",",
... | 5b77d242596560c646b8405340c9ce64acb183cb |
train | DaskFrameAxisPartition.apply | 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... | modin/engines/dask/pandas_on_dask_delayed/frame/axis_partition.py | 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
):
"""Applies func to the object.
See notes in Parent class about this method.
Args:
func: The function to apply.
... | [
"Applies",
"func",
"to",
"the",
"object",
"."
] | modin-project/modin | python | https://github.com/modin-project/modin/blob/5b77d242596560c646b8405340c9ce64acb183cb/modin/engines/dask/pandas_on_dask_delayed/frame/axis_partition.py#L15-L63 | [
"def",
"apply",
"(",
"self",
",",
"func",
",",
"num_splits",
"=",
"None",
",",
"other_axis_partition",
"=",
"None",
",",
"maintain_partitioning",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"import",
"dask",
"if",
"num_splits",
"is",
"None",
":",
"nu... | 5b77d242596560c646b8405340c9ce64acb183cb |
train | get_dummies | 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... | modin/pandas/reshape.py | 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 (strin... | [
"Convert",
"categorical",
"variable",
"into",
"indicator",
"variables",
"."
] | modin-project/modin | python | https://github.com/modin-project/modin/blob/5b77d242596560c646b8405340c9ce64acb183cb/modin/pandas/reshape.py#L12-L67 | [
"def",
"get_dummies",
"(",
"data",
",",
"prefix",
"=",
"None",
",",
"prefix_sep",
"=",
"\"_\"",
",",
"dummy_na",
"=",
"False",
",",
"columns",
"=",
"None",
",",
"sparse",
"=",
"False",
",",
"drop_first",
"=",
"False",
",",
"dtype",
"=",
"None",
",",
... | 5b77d242596560c646b8405340c9ce64acb183cb |
train | PandasFrameAxisPartition.apply | Applies func to the object in the plasma store.
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 `PandasOnRayFrameAxisPartition` object to apply ... | modin/engines/base/frame/axis_partition.py | def apply(
self,
func,
num_splits=None,
other_axis_partition=None,
maintain_partitioning=True,
**kwargs
):
"""Applies func to the object in the plasma store.
See notes in Parent class about this method.
Args:
func: The function to... | def apply(
self,
func,
num_splits=None,
other_axis_partition=None,
maintain_partitioning=True,
**kwargs
):
"""Applies func to the object in the plasma store.
See notes in Parent class about this method.
Args:
func: The function to... | [
"Applies",
"func",
"to",
"the",
"object",
"in",
"the",
"plasma",
"store",
"."
] | modin-project/modin | python | https://github.com/modin-project/modin/blob/5b77d242596560c646b8405340c9ce64acb183cb/modin/engines/base/frame/axis_partition.py#L98-L141 | [
"def",
"apply",
"(",
"self",
",",
"func",
",",
"num_splits",
"=",
"None",
",",
"other_axis_partition",
"=",
"None",
",",
"maintain_partitioning",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"num_splits",
"is",
"None",
":",
"num_splits",
"=",
"l... | 5b77d242596560c646b8405340c9ce64acb183cb |
train | PandasFrameAxisPartition.shuffle | 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... | modin/engines/base/frame/axis_partition.py | 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):
"""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... | [
"Shuffle",
"the",
"order",
"of",
"the",
"data",
"in",
"this",
"axis",
"based",
"on",
"the",
"lengths",
"."
] | modin-project/modin | python | https://github.com/modin-project/modin/blob/5b77d242596560c646b8405340c9ce64acb183cb/modin/engines/base/frame/axis_partition.py#L143-L161 | [
"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\"",
"]",... | 5b77d242596560c646b8405340c9ce64acb183cb |
train | PandasFrameAxisPartition.deploy_axis_func | Deploy a function along a full axis in Ray.
Args:
axis: The axis to perform the function along.
func: The function to perform.
num_splits: The number of splits to return
(see `split_result_of_axis_func_pandas`)
kwargs: A di... | modin/engines/base/frame/axis_partition.py | def deploy_axis_func(
cls, axis, func, num_splits, kwargs, maintain_partitioning, *partitions
):
"""Deploy a function along a full axis in Ray.
Args:
axis: The axis to perform the function along.
func: The function to perform.
num_splits: ... | def deploy_axis_func(
cls, axis, func, num_splits, kwargs, maintain_partitioning, *partitions
):
"""Deploy a function along a full axis in Ray.
Args:
axis: The axis to perform the function along.
func: The function to perform.
num_splits: ... | [
"Deploy",
"a",
"function",
"along",
"a",
"full",
"axis",
"in",
"Ray",
"."
] | modin-project/modin | python | https://github.com/modin-project/modin/blob/5b77d242596560c646b8405340c9ce64acb183cb/modin/engines/base/frame/axis_partition.py#L164-L210 | [
"def",
"deploy_axis_func",
"(",
"cls",
",",
"axis",
",",
"func",
",",
"num_splits",
",",
"kwargs",
",",
"maintain_partitioning",
",",
"*",
"partitions",
")",
":",
"# Pop these off first because they aren't expected by the function.",
"manual_partition",
"=",
"kwargs",
"... | 5b77d242596560c646b8405340c9ce64acb183cb |
train | PandasFrameAxisPartition.deploy_func_between_two_axis_partitions | Deploy a function along a full axis between two data sets in Ray.
Args:
axis: The axis to perform the function along.
func: The function to perform.
num_splits: The number of splits to return
(see `split_result_of_axis_func_pandas`).
len_of_left: ... | modin/engines/base/frame/axis_partition.py | def deploy_func_between_two_axis_partitions(
cls, axis, func, num_splits, len_of_left, kwargs, *partitions
):
"""Deploy a function along a full axis between two data sets in Ray.
Args:
axis: The axis to perform the function along.
func: The function to perform.
... | def deploy_func_between_two_axis_partitions(
cls, axis, func, num_splits, len_of_left, kwargs, *partitions
):
"""Deploy a function along a full axis between two data sets in Ray.
Args:
axis: The axis to perform the function along.
func: The function to perform.
... | [
"Deploy",
"a",
"function",
"along",
"a",
"full",
"axis",
"between",
"two",
"data",
"sets",
"in",
"Ray",
"."
] | modin-project/modin | python | https://github.com/modin-project/modin/blob/5b77d242596560c646b8405340c9ce64acb183cb/modin/engines/base/frame/axis_partition.py#L213-L236 | [
"def",
"deploy_func_between_two_axis_partitions",
"(",
"cls",
",",
"axis",
",",
"func",
",",
"num_splits",
",",
"len_of_left",
",",
"kwargs",
",",
"*",
"partitions",
")",
":",
"lt_frame",
"=",
"pandas",
".",
"concat",
"(",
"list",
"(",
"partitions",
"[",
":"... | 5b77d242596560c646b8405340c9ce64acb183cb |
train | PyarrowQueryCompiler.query | Query columns of the DataManager with a boolean expression.
Args:
expr: Boolean expression to query the columns with.
Returns:
DataManager containing the rows where the boolean expression is satisfied. | modin/backends/pyarrow/query_compiler.py | def query(self, expr, **kwargs):
"""Query columns of the DataManager with a boolean expression.
Args:
expr: Boolean expression to query the columns with.
Returns:
DataManager containing the rows where the boolean expression is satisfied.
"""
d... | def query(self, expr, **kwargs):
"""Query columns of the DataManager with a boolean expression.
Args:
expr: Boolean expression to query the columns with.
Returns:
DataManager containing the rows where the boolean expression is satisfied.
"""
d... | [
"Query",
"columns",
"of",
"the",
"DataManager",
"with",
"a",
"boolean",
"expression",
".",
"Args",
":",
"expr",
":",
"Boolean",
"expression",
"to",
"query",
"the",
"columns",
"with",
".",
"Returns",
":",
"DataManager",
"containing",
"the",
"rows",
"where",
"... | modin-project/modin | python | https://github.com/modin-project/modin/blob/5b77d242596560c646b8405340c9ce64acb183cb/modin/backends/pyarrow/query_compiler.py#L17-L153 | [
"def",
"query",
"(",
"self",
",",
"expr",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"gen_table_expr",
"(",
"table",
",",
"expr",
")",
":",
"resolver",
"=",
"{",
"name",
":",
"FakeSeries",
"(",
"dtype",
".",
"to_pandas_dtype",
"(",
")",
")",
"for",
... | 5b77d242596560c646b8405340c9ce64acb183cb |
train | PyarrowQueryCompiler.to_pandas | Converts Modin DataFrame to Pandas DataFrame.
Returns:
Pandas DataFrame of the DataManager. | modin/backends/pyarrow/query_compiler.py | def to_pandas(self):
"""Converts Modin DataFrame to Pandas DataFrame.
Returns:
Pandas DataFrame of the DataManager.
"""
df = self.data.to_pandas(is_transposed=self._is_transposed)
if df.empty:
dtype_dict = {
col_name: pandas.Serie... | def to_pandas(self):
"""Converts Modin DataFrame to Pandas DataFrame.
Returns:
Pandas DataFrame of the DataManager.
"""
df = self.data.to_pandas(is_transposed=self._is_transposed)
if df.empty:
dtype_dict = {
col_name: pandas.Serie... | [
"Converts",
"Modin",
"DataFrame",
"to",
"Pandas",
"DataFrame",
".",
"Returns",
":",
"Pandas",
"DataFrame",
"of",
"the",
"DataManager",
"."
] | modin-project/modin | python | https://github.com/modin-project/modin/blob/5b77d242596560c646b8405340c9ce64acb183cb/modin/backends/pyarrow/query_compiler.py#L174-L193 | [
"def",
"to_pandas",
"(",
"self",
")",
":",
"df",
"=",
"self",
".",
"data",
".",
"to_pandas",
"(",
"is_transposed",
"=",
"self",
".",
"_is_transposed",
")",
"if",
"df",
".",
"empty",
":",
"dtype_dict",
"=",
"{",
"col_name",
":",
"pandas",
".",
"Series",... | 5b77d242596560c646b8405340c9ce64acb183cb |
train | deploy_ray_axis_func | Deploy a function along a full axis in Ray.
Args:
axis: The axis to perform the function along.
func: The function to perform.
num_splits: The number of splits to return
(see `split_result_of_axis_func_pandas`)
kwargs: A dictionary of keyword arguments.
partition... | modin/experimental/engines/pyarrow_on_ray/frame/axis_partition.py | def deploy_ray_axis_func(axis, func, num_splits, kwargs, *partitions):
"""Deploy a function along a full axis in Ray.
Args:
axis: The axis to perform the function along.
func: The function to perform.
num_splits: The number of splits to return
(see `split_result_of_axis_func... | def deploy_ray_axis_func(axis, func, num_splits, kwargs, *partitions):
"""Deploy a function along a full axis in Ray.
Args:
axis: The axis to perform the function along.
func: The function to perform.
num_splits: The number of splits to return
(see `split_result_of_axis_func... | [
"Deploy",
"a",
"function",
"along",
"a",
"full",
"axis",
"in",
"Ray",
"."
] | modin-project/modin | python | https://github.com/modin-project/modin/blob/5b77d242596560c646b8405340c9ce64acb183cb/modin/experimental/engines/pyarrow_on_ray/frame/axis_partition.py#L140-L161 | [
"def",
"deploy_ray_axis_func",
"(",
"axis",
",",
"func",
",",
"num_splits",
",",
"kwargs",
",",
"*",
"partitions",
")",
":",
"table",
"=",
"concat_arrow_table_partitions",
"(",
"axis",
",",
"partitions",
")",
"try",
":",
"result",
"=",
"func",
"(",
"table",
... | 5b77d242596560c646b8405340c9ce64acb183cb |
train | deploy_ray_func_between_two_axis_partitions | Deploy a function along a full axis between two data sets in Ray.
Args:
axis: The axis to perform the function along.
func: The function to perform.
num_splits: The number of splits to return
(see `split_result_of_axis_func_pandas`).
len_of_left: The number of values in ... | modin/experimental/engines/pyarrow_on_ray/frame/axis_partition.py | def deploy_ray_func_between_two_axis_partitions(
axis, func, num_splits, len_of_left, kwargs, *partitions
):
"""Deploy a function along a full axis between two data sets in Ray.
Args:
axis: The axis to perform the function along.
func: The function to perform.
num_splits: The number... | def deploy_ray_func_between_two_axis_partitions(
axis, func, num_splits, len_of_left, kwargs, *partitions
):
"""Deploy a function along a full axis between two data sets in Ray.
Args:
axis: The axis to perform the function along.
func: The function to perform.
num_splits: The number... | [
"Deploy",
"a",
"function",
"along",
"a",
"full",
"axis",
"between",
"two",
"data",
"sets",
"in",
"Ray",
"."
] | modin-project/modin | python | https://github.com/modin-project/modin/blob/5b77d242596560c646b8405340c9ce64acb183cb/modin/experimental/engines/pyarrow_on_ray/frame/axis_partition.py#L165-L194 | [
"def",
"deploy_ray_func_between_two_axis_partitions",
"(",
"axis",
",",
"func",
",",
"num_splits",
",",
"len_of_left",
",",
"kwargs",
",",
"*",
"partitions",
")",
":",
"lt_table",
"=",
"concat_arrow_table_partitions",
"(",
"axis",
",",
"partitions",
"[",
":",
"len... | 5b77d242596560c646b8405340c9ce64acb183cb |
train | PyarrowOnRayFrameAxisPartition.apply | Applies func to the object in the plasma store.
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 `PyarrowOnRayFrameAxisPartition` object to apply... | modin/experimental/engines/pyarrow_on_ray/frame/axis_partition.py | def apply(self, func, num_splits=None, other_axis_partition=None, **kwargs):
"""Applies func to the object in the plasma store.
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.
... | def apply(self, func, num_splits=None, other_axis_partition=None, **kwargs):
"""Applies func to the object in the plasma store.
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.
... | [
"Applies",
"func",
"to",
"the",
"object",
"in",
"the",
"plasma",
"store",
"."
] | modin-project/modin | python | https://github.com/modin-project/modin/blob/5b77d242596560c646b8405340c9ce64acb183cb/modin/experimental/engines/pyarrow_on_ray/frame/axis_partition.py#L16-L48 | [
"def",
"apply",
"(",
"self",
",",
"func",
",",
"num_splits",
"=",
"None",
",",
"other_axis_partition",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"num_splits",
"is",
"None",
":",
"num_splits",
"=",
"len",
"(",
"self",
".",
"list_of_blocks",
... | 5b77d242596560c646b8405340c9ce64acb183cb |
train | PyarrowOnRayFrameAxisPartition.shuffle | Shuffle the order of the data in this axis based on the `func`.
Extends `BaseFrameAxisPartition.shuffle`.
:param func:
:param num_splits:
:param kwargs:
:return: | modin/experimental/engines/pyarrow_on_ray/frame/axis_partition.py | 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):
"""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:
... | [
"Shuffle",
"the",
"order",
"of",
"the",
"data",
"in",
"this",
"axis",
"based",
"on",
"the",
"func",
"."
] | modin-project/modin | python | https://github.com/modin-project/modin/blob/5b77d242596560c646b8405340c9ce64acb183cb/modin/experimental/engines/pyarrow_on_ray/frame/axis_partition.py#L50-L68 | [
"def",
"shuffle",
"(",
"self",
",",
"func",
",",
"num_splits",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"num_splits",
"is",
"None",
":",
"num_splits",
"=",
"len",
"(",
"self",
".",
"list_of_blocks",
")",
"args",
"=",
"[",
"self",
".",
... | 5b77d242596560c646b8405340c9ce64acb183cb |
train | deploy_ray_func | Deploy a function to a partition in Ray.
Args:
func: The function to apply.
partition: The partition to apply the function to.
kwargs: A dictionary of keyword arguments for the function.
Returns:
The result of the function. | modin/experimental/engines/pyarrow_on_ray/frame/partition.py | def deploy_ray_func(func, partition, kwargs):
"""Deploy a function to a partition in Ray.
Args:
func: The function to apply.
partition: The partition to apply the function to.
kwargs: A dictionary of keyword arguments for the function.
Returns:
The result of the function.
... | def deploy_ray_func(func, partition, kwargs):
"""Deploy a function to a partition in Ray.
Args:
func: The function to apply.
partition: The partition to apply the function to.
kwargs: A dictionary of keyword arguments for the function.
Returns:
The result of the function.
... | [
"Deploy",
"a",
"function",
"to",
"a",
"partition",
"in",
"Ray",
"."
] | modin-project/modin | python | https://github.com/modin-project/modin/blob/5b77d242596560c646b8405340c9ce64acb183cb/modin/experimental/engines/pyarrow_on_ray/frame/partition.py#L120-L142 | [
"def",
"deploy_ray_func",
"(",
"func",
",",
"partition",
",",
"kwargs",
")",
":",
"try",
":",
"result",
"=",
"func",
"(",
"partition",
",",
"*",
"*",
"kwargs",
")",
"# Sometimes Arrow forces us to make a copy of an object before we operate",
"# on it. We don't want the ... | 5b77d242596560c646b8405340c9ce64acb183cb |
train | PyarrowOnRayFramePartition.get | Gets the object out of the plasma store.
Returns:
The object from the plasma store. | modin/experimental/engines/pyarrow_on_ray/frame/partition.py | def get(self):
"""Gets the object out of the plasma store.
Returns:
The object from the plasma store.
"""
if len(self.call_queue):
return self.apply(lambda x: x).get()
return ray.get(self.oid) | def get(self):
"""Gets the object out of the plasma store.
Returns:
The object from the plasma store.
"""
if len(self.call_queue):
return self.apply(lambda x: x).get()
return ray.get(self.oid) | [
"Gets",
"the",
"object",
"out",
"of",
"the",
"plasma",
"store",
"."
] | modin-project/modin | python | https://github.com/modin-project/modin/blob/5b77d242596560c646b8405340c9ce64acb183cb/modin/experimental/engines/pyarrow_on_ray/frame/partition.py#L19-L28 | [
"def",
"get",
"(",
"self",
")",
":",
"if",
"len",
"(",
"self",
".",
"call_queue",
")",
":",
"return",
"self",
".",
"apply",
"(",
"lambda",
"x",
":",
"x",
")",
".",
"get",
"(",
")",
"return",
"ray",
".",
"get",
"(",
"self",
".",
"oid",
")"
] | 5b77d242596560c646b8405340c9ce64acb183cb |
train | PyarrowOnRayFramePartition.apply | 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:
... | modin/experimental/engines/pyarrow_on_ray/frame/partition.py | 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):
"""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... | [
"Apply",
"a",
"function",
"to",
"the",
"object",
"stored",
"in",
"this",
"partition",
"."
] | modin-project/modin | python | https://github.com/modin-project/modin/blob/5b77d242596560c646b8405340c9ce64acb183cb/modin/experimental/engines/pyarrow_on_ray/frame/partition.py#L30-L62 | [
"def",
"apply",
"(",
"self",
",",
"func",
",",
"*",
"*",
"kwargs",
")",
":",
"oid",
"=",
"self",
".",
"oid",
"self",
".",
"call_queue",
".",
"append",
"(",
"(",
"func",
",",
"kwargs",
")",
")",
"def",
"call_queue_closure",
"(",
"oid_obj",
",",
"cal... | 5b77d242596560c646b8405340c9ce64acb183cb |
train | PyarrowOnRayFramePartition.to_pandas | Convert the object stored in this partition to a Pandas DataFrame.
Returns:
A Pandas DataFrame. | modin/experimental/engines/pyarrow_on_ray/frame/partition.py | 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):
"""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 | [
"Convert",
"the",
"object",
"stored",
"in",
"this",
"partition",
"to",
"a",
"Pandas",
"DataFrame",
"."
] | modin-project/modin | python | https://github.com/modin-project/modin/blob/5b77d242596560c646b8405340c9ce64acb183cb/modin/experimental/engines/pyarrow_on_ray/frame/partition.py#L71-L80 | [
"def",
"to_pandas",
"(",
"self",
")",
":",
"dataframe",
"=",
"self",
".",
"get",
"(",
")",
".",
"to_pandas",
"(",
")",
"assert",
"type",
"(",
"dataframe",
")",
"is",
"pandas",
".",
"DataFrame",
"or",
"type",
"(",
"dataframe",
")",
"is",
"pandas",
"."... | 5b77d242596560c646b8405340c9ce64acb183cb |
train | PyarrowOnRayFramePartition.put | Put an object in the Plasma store and wrap it in this object.
Args:
obj: The object to be put.
Returns:
A `RayRemotePartition` object. | modin/experimental/engines/pyarrow_on_ray/frame/partition.py | 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):
"""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))) | [
"Put",
"an",
"object",
"in",
"the",
"Plasma",
"store",
"and",
"wrap",
"it",
"in",
"this",
"object",
"."
] | modin-project/modin | python | https://github.com/modin-project/modin/blob/5b77d242596560c646b8405340c9ce64acb183cb/modin/experimental/engines/pyarrow_on_ray/frame/partition.py#L83-L92 | [
"def",
"put",
"(",
"cls",
",",
"obj",
")",
":",
"return",
"PyarrowOnRayFramePartition",
"(",
"ray",
".",
"put",
"(",
"pyarrow",
".",
"Table",
".",
"from_pandas",
"(",
"obj",
")",
")",
")"
] | 5b77d242596560c646b8405340c9ce64acb183cb |
train | isna | Detect missing values for an array-like object.
Args:
obj: Object to check for null or missing values.
Returns:
bool or array-like of bool | modin/pandas/general.py | def isna(obj):
"""
Detect missing values for an array-like object.
Args:
obj: Object to check for null or missing values.
Returns:
bool or array-like of bool
"""
if isinstance(obj, BasePandasDataset):
return obj.isna()
else:
return pandas.isna(obj) | def isna(obj):
"""
Detect missing values for an array-like object.
Args:
obj: Object to check for null or missing values.
Returns:
bool or array-like of bool
"""
if isinstance(obj, BasePandasDataset):
return obj.isna()
else:
return pandas.isna(obj) | [
"Detect",
"missing",
"values",
"for",
"an",
"array",
"-",
"like",
"object",
".",
"Args",
":",
"obj",
":",
"Object",
"to",
"check",
"for",
"null",
"or",
"missing",
"values",
"."
] | modin-project/modin | python | https://github.com/modin-project/modin/blob/5b77d242596560c646b8405340c9ce64acb183cb/modin/pandas/general.py#L13-L25 | [
"def",
"isna",
"(",
"obj",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"BasePandasDataset",
")",
":",
"return",
"obj",
".",
"isna",
"(",
")",
"else",
":",
"return",
"pandas",
".",
"isna",
"(",
"obj",
")"
] | 5b77d242596560c646b8405340c9ce64acb183cb |
train | merge | 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
... | modin/pandas/general.py | 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,
suffixes=("_x", "_y"),
copy=True,
indicator=False,
validate=None,
):
"""Database style join, where common columns in "on" are merged.
A... | [
"Database",
"style",
"join",
"where",
"common",
"columns",
"in",
"on",
"are",
"merged",
"."
] | modin-project/modin | python | https://github.com/modin-project/modin/blob/5b77d242596560c646b8405340c9ce64acb183cb/modin/pandas/general.py#L41-L97 | [
"def",
"merge",
"(",
"left",
",",
"right",
",",
"how",
"=",
"\"inner\"",
",",
"on",
"=",
"None",
",",
"left_on",
"=",
"None",
",",
"right_on",
"=",
"None",
",",
"left_index",
"=",
"False",
",",
"right_index",
"=",
"False",
",",
"sort",
"=",
"False",
... | 5b77d242596560c646b8405340c9ce64acb183cb |
train | is_distributed | 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:
... | modin/experimental/engines/pandas_on_ray/sql.py | 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):
""" 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... | [
"Check",
"if",
"is",
"possible",
"distribute",
"a",
"query",
"given",
"that",
"args"
] | modin-project/modin | python | https://github.com/modin-project/modin/blob/5b77d242596560c646b8405340c9ce64acb183cb/modin/experimental/engines/pandas_on_ray/sql.py#L5-L31 | [
"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",
"... | 5b77d242596560c646b8405340c9ce64acb183cb |
train | is_table | 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 | modin/experimental/engines/pandas_on_ray/sql.py | 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):
""" 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 | [
"Check",
"with",
"the",
"given",
"sql",
"arg",
"is",
"query",
"or",
"table"
] | modin-project/modin | python | https://github.com/modin-project/modin/blob/5b77d242596560c646b8405340c9ce64acb183cb/modin/experimental/engines/pandas_on_ray/sql.py#L34-L46 | [
"def",
"is_table",
"(",
"engine",
",",
"sql",
")",
":",
"if",
"engine",
".",
"dialect",
".",
"has_table",
"(",
"engine",
",",
"sql",
")",
":",
"return",
"True",
"return",
"False"
] | 5b77d242596560c646b8405340c9ce64acb183cb |
train | get_table_metadata | Extract all useful infos from the given table
Args:
engine: SQLAlchemy connection engine
table: table name
Returns:
Dictionary of infos | modin/experimental/engines/pandas_on_ray/sql.py | 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):
""" 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 = ... | [
"Extract",
"all",
"useful",
"infos",
"from",
"the",
"given",
"table"
] | modin-project/modin | python | https://github.com/modin-project/modin/blob/5b77d242596560c646b8405340c9ce64acb183cb/modin/experimental/engines/pandas_on_ray/sql.py#L49-L62 | [
"def",
"get_table_metadata",
"(",
"engine",
",",
"table",
")",
":",
"metadata",
"=",
"MetaData",
"(",
")",
"metadata",
".",
"reflect",
"(",
"bind",
"=",
"engine",
",",
"only",
"=",
"[",
"table",
"]",
")",
"table_metadata",
"=",
"Table",
"(",
"table",
"... | 5b77d242596560c646b8405340c9ce64acb183cb |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.