repo stringlengths 7 55 | path stringlengths 4 223 | func_name stringlengths 1 134 | original_string stringlengths 75 104k | language stringclasses 1
value | code stringlengths 75 104k | code_tokens listlengths 19 28.4k | docstring stringlengths 1 46.9k | docstring_tokens listlengths 1 1.97k | sha stringlengths 40 40 | url stringlengths 87 315 | partition stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|
apache/incubator-mxnet | example/ssd/dataset/concat_db.py | ConcatDB._check_classes | def _check_classes(self):
"""
check input imdbs, make sure they have same classes
"""
try:
self.classes = self.imdbs[0].classes
self.num_classes = len(self.classes)
except AttributeError:
# fine, if no classes is provided
pass
... | python | def _check_classes(self):
"""
check input imdbs, make sure they have same classes
"""
try:
self.classes = self.imdbs[0].classes
self.num_classes = len(self.classes)
except AttributeError:
# fine, if no classes is provided
pass
... | [
"def",
"_check_classes",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"classes",
"=",
"self",
".",
"imdbs",
"[",
"0",
"]",
".",
"classes",
"self",
".",
"num_classes",
"=",
"len",
"(",
"self",
".",
"classes",
")",
"except",
"AttributeError",
":",
"... | check input imdbs, make sure they have same classes | [
"check",
"input",
"imdbs",
"make",
"sure",
"they",
"have",
"same",
"classes"
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/ssd/dataset/concat_db.py#L40-L53 | train |
apache/incubator-mxnet | example/ssd/dataset/concat_db.py | ConcatDB._load_image_set_index | def _load_image_set_index(self, shuffle):
"""
get total number of images, init indices
Parameters
----------
shuffle : bool
whether to shuffle the initial indices
"""
self.num_images = 0
for db in self.imdbs:
self.num_images += db.... | python | def _load_image_set_index(self, shuffle):
"""
get total number of images, init indices
Parameters
----------
shuffle : bool
whether to shuffle the initial indices
"""
self.num_images = 0
for db in self.imdbs:
self.num_images += db.... | [
"def",
"_load_image_set_index",
"(",
"self",
",",
"shuffle",
")",
":",
"self",
".",
"num_images",
"=",
"0",
"for",
"db",
"in",
"self",
".",
"imdbs",
":",
"self",
".",
"num_images",
"+=",
"db",
".",
"num_images",
"indices",
"=",
"list",
"(",
"range",
"(... | get total number of images, init indices
Parameters
----------
shuffle : bool
whether to shuffle the initial indices | [
"get",
"total",
"number",
"of",
"images",
"init",
"indices"
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/ssd/dataset/concat_db.py#L55-L70 | train |
apache/incubator-mxnet | example/ssd/dataset/concat_db.py | ConcatDB._locate_index | def _locate_index(self, index):
"""
given index, find out sub-db and sub-index
Parameters
----------
index : int
index of a specific image
Returns
----------
a tuple (sub-db, sub-index)
"""
assert index >= 0 and index < self.n... | python | def _locate_index(self, index):
"""
given index, find out sub-db and sub-index
Parameters
----------
index : int
index of a specific image
Returns
----------
a tuple (sub-db, sub-index)
"""
assert index >= 0 and index < self.n... | [
"def",
"_locate_index",
"(",
"self",
",",
"index",
")",
":",
"assert",
"index",
">=",
"0",
"and",
"index",
"<",
"self",
".",
"num_images",
",",
"\"index out of range\"",
"pos",
"=",
"self",
".",
"image_set_index",
"[",
"index",
"]",
"for",
"k",
",",
"v",... | given index, find out sub-db and sub-index
Parameters
----------
index : int
index of a specific image
Returns
----------
a tuple (sub-db, sub-index) | [
"given",
"index",
"find",
"out",
"sub",
"-",
"db",
"and",
"sub",
"-",
"index"
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/ssd/dataset/concat_db.py#L72-L91 | train |
apache/incubator-mxnet | example/ssd/dataset/concat_db.py | ConcatDB.image_path_from_index | def image_path_from_index(self, index):
"""
given image index, find out full path
Parameters
----------
index: int
index of a specific image
Returns
----------
full path of this image
"""
assert self.image_set_index is not Non... | python | def image_path_from_index(self, index):
"""
given image index, find out full path
Parameters
----------
index: int
index of a specific image
Returns
----------
full path of this image
"""
assert self.image_set_index is not Non... | [
"def",
"image_path_from_index",
"(",
"self",
",",
"index",
")",
":",
"assert",
"self",
".",
"image_set_index",
"is",
"not",
"None",
",",
"\"Dataset not initialized\"",
"pos",
"=",
"self",
".",
"image_set_index",
"[",
"index",
"]",
"n_db",
",",
"n_index",
"=",
... | given image index, find out full path
Parameters
----------
index: int
index of a specific image
Returns
----------
full path of this image | [
"given",
"image",
"index",
"find",
"out",
"full",
"path"
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/ssd/dataset/concat_db.py#L93-L109 | train |
apache/incubator-mxnet | python/mxnet/callback.py | module_checkpoint | def module_checkpoint(mod, prefix, period=1, save_optimizer_states=False):
"""Callback to checkpoint Module to prefix every epoch.
Parameters
----------
mod : subclass of BaseModule
The module to checkpoint.
prefix : str
The file prefix for this checkpoint.
period : int
... | python | def module_checkpoint(mod, prefix, period=1, save_optimizer_states=False):
"""Callback to checkpoint Module to prefix every epoch.
Parameters
----------
mod : subclass of BaseModule
The module to checkpoint.
prefix : str
The file prefix for this checkpoint.
period : int
... | [
"def",
"module_checkpoint",
"(",
"mod",
",",
"prefix",
",",
"period",
"=",
"1",
",",
"save_optimizer_states",
"=",
"False",
")",
":",
"period",
"=",
"int",
"(",
"max",
"(",
"1",
",",
"period",
")",
")",
"# pylint: disable=unused-argument",
"def",
"_callback"... | Callback to checkpoint Module to prefix every epoch.
Parameters
----------
mod : subclass of BaseModule
The module to checkpoint.
prefix : str
The file prefix for this checkpoint.
period : int
How many epochs to wait before checkpointing. Defaults to 1.
save_optimizer_st... | [
"Callback",
"to",
"checkpoint",
"Module",
"to",
"prefix",
"every",
"epoch",
"."
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/callback.py#L27-L52 | train |
apache/incubator-mxnet | python/mxnet/callback.py | do_checkpoint | def do_checkpoint(prefix, period=1):
"""A callback that saves a model checkpoint every few epochs.
Each checkpoint is made up of a couple of binary files: a model description file and a
parameters (weights and biases) file. The model description file is named
`prefix`--symbol.json and the parameters fil... | python | def do_checkpoint(prefix, period=1):
"""A callback that saves a model checkpoint every few epochs.
Each checkpoint is made up of a couple of binary files: a model description file and a
parameters (weights and biases) file. The model description file is named
`prefix`--symbol.json and the parameters fil... | [
"def",
"do_checkpoint",
"(",
"prefix",
",",
"period",
"=",
"1",
")",
":",
"period",
"=",
"int",
"(",
"max",
"(",
"1",
",",
"period",
")",
")",
"def",
"_callback",
"(",
"iter_no",
",",
"sym",
",",
"arg",
",",
"aux",
")",
":",
"\"\"\"The checkpoint fun... | A callback that saves a model checkpoint every few epochs.
Each checkpoint is made up of a couple of binary files: a model description file and a
parameters (weights and biases) file. The model description file is named
`prefix`--symbol.json and the parameters file is named `prefix`-`epoch_number`.params
... | [
"A",
"callback",
"that",
"saves",
"a",
"model",
"checkpoint",
"every",
"few",
"epochs",
".",
"Each",
"checkpoint",
"is",
"made",
"up",
"of",
"a",
"couple",
"of",
"binary",
"files",
":",
"a",
"model",
"description",
"file",
"and",
"a",
"parameters",
"(",
... | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/callback.py#L55-L90 | train |
apache/incubator-mxnet | python/mxnet/callback.py | log_train_metric | def log_train_metric(period, auto_reset=False):
"""Callback to log the training evaluation result every period.
Parameters
----------
period : int
The number of batch to log the training evaluation metric.
auto_reset : bool
Reset the metric after each log.
Returns
-------
... | python | def log_train_metric(period, auto_reset=False):
"""Callback to log the training evaluation result every period.
Parameters
----------
period : int
The number of batch to log the training evaluation metric.
auto_reset : bool
Reset the metric after each log.
Returns
-------
... | [
"def",
"log_train_metric",
"(",
"period",
",",
"auto_reset",
"=",
"False",
")",
":",
"def",
"_callback",
"(",
"param",
")",
":",
"\"\"\"The checkpoint function.\"\"\"",
"if",
"param",
".",
"nbatch",
"%",
"period",
"==",
"0",
"and",
"param",
".",
"eval_metric",... | Callback to log the training evaluation result every period.
Parameters
----------
period : int
The number of batch to log the training evaluation metric.
auto_reset : bool
Reset the metric after each log.
Returns
-------
callback : function
The callback function th... | [
"Callback",
"to",
"log",
"the",
"training",
"evaluation",
"result",
"every",
"period",
"."
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/callback.py#L93-L117 | train |
apache/incubator-mxnet | python/mxnet/monitor.py | Monitor.install | def install(self, exe):
"""install callback to executor.
Supports installing to multiple exes.
Parameters
----------
exe : mx.executor.Executor
The Executor (returned by symbol.bind) to install to.
"""
exe.set_monitor_callback(self.stat_helper, self.m... | python | def install(self, exe):
"""install callback to executor.
Supports installing to multiple exes.
Parameters
----------
exe : mx.executor.Executor
The Executor (returned by symbol.bind) to install to.
"""
exe.set_monitor_callback(self.stat_helper, self.m... | [
"def",
"install",
"(",
"self",
",",
"exe",
")",
":",
"exe",
".",
"set_monitor_callback",
"(",
"self",
".",
"stat_helper",
",",
"self",
".",
"monitor_all",
")",
"self",
".",
"exes",
".",
"append",
"(",
"exe",
")"
] | install callback to executor.
Supports installing to multiple exes.
Parameters
----------
exe : mx.executor.Executor
The Executor (returned by symbol.bind) to install to. | [
"install",
"callback",
"to",
"executor",
".",
"Supports",
"installing",
"to",
"multiple",
"exes",
"."
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/monitor.py#L76-L86 | train |
apache/incubator-mxnet | python/mxnet/monitor.py | Monitor.tic | def tic(self):
"""Start collecting stats for current batch.
Call before calling forward."""
if self.step % self.interval == 0:
for exe in self.exes:
for array in exe.arg_arrays:
array.wait_to_read()
for array in exe.aux_arrays:
... | python | def tic(self):
"""Start collecting stats for current batch.
Call before calling forward."""
if self.step % self.interval == 0:
for exe in self.exes:
for array in exe.arg_arrays:
array.wait_to_read()
for array in exe.aux_arrays:
... | [
"def",
"tic",
"(",
"self",
")",
":",
"if",
"self",
".",
"step",
"%",
"self",
".",
"interval",
"==",
"0",
":",
"for",
"exe",
"in",
"self",
".",
"exes",
":",
"for",
"array",
"in",
"exe",
".",
"arg_arrays",
":",
"array",
".",
"wait_to_read",
"(",
")... | Start collecting stats for current batch.
Call before calling forward. | [
"Start",
"collecting",
"stats",
"for",
"current",
"batch",
".",
"Call",
"before",
"calling",
"forward",
"."
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/monitor.py#L88-L99 | train |
apache/incubator-mxnet | python/mxnet/monitor.py | Monitor.toc | def toc(self):
"""End collecting for current batch and return results.
Call after computation of current batch.
Returns
-------
res : list of """
if not self.activated:
return []
for exe in self.exes:
for array in exe.arg_arrays:
... | python | def toc(self):
"""End collecting for current batch and return results.
Call after computation of current batch.
Returns
-------
res : list of """
if not self.activated:
return []
for exe in self.exes:
for array in exe.arg_arrays:
... | [
"def",
"toc",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"activated",
":",
"return",
"[",
"]",
"for",
"exe",
"in",
"self",
".",
"exes",
":",
"for",
"array",
"in",
"exe",
".",
"arg_arrays",
":",
"array",
".",
"wait_to_read",
"(",
")",
"for",
... | End collecting for current batch and return results.
Call after computation of current batch.
Returns
-------
res : list of | [
"End",
"collecting",
"for",
"current",
"batch",
"and",
"return",
"results",
".",
"Call",
"after",
"computation",
"of",
"current",
"batch",
"."
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/monitor.py#L102-L140 | train |
apache/incubator-mxnet | python/mxnet/monitor.py | Monitor.toc_print | def toc_print(self):
"""End collecting and print results."""
res = self.toc()
for n, k, v in res:
logging.info('Batch: {:7d} {:30s} {:s}'.format(n, k, v)) | python | def toc_print(self):
"""End collecting and print results."""
res = self.toc()
for n, k, v in res:
logging.info('Batch: {:7d} {:30s} {:s}'.format(n, k, v)) | [
"def",
"toc_print",
"(",
"self",
")",
":",
"res",
"=",
"self",
".",
"toc",
"(",
")",
"for",
"n",
",",
"k",
",",
"v",
"in",
"res",
":",
"logging",
".",
"info",
"(",
"'Batch: {:7d} {:30s} {:s}'",
".",
"format",
"(",
"n",
",",
"k",
",",
"v",
")",
... | End collecting and print results. | [
"End",
"collecting",
"and",
"print",
"results",
"."
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/monitor.py#L142-L146 | train |
apache/incubator-mxnet | example/rnn/old/bucket_io.py | BucketSentenceIter.make_data_iter_plan | def make_data_iter_plan(self):
"make a random data iteration plan"
# truncate each bucket into multiple of batch-size
bucket_n_batches = []
for i in range(len(self.data)):
bucket_n_batches.append(np.floor((self.data[i]) / self.batch_size))
self.data[i] = self.data... | python | def make_data_iter_plan(self):
"make a random data iteration plan"
# truncate each bucket into multiple of batch-size
bucket_n_batches = []
for i in range(len(self.data)):
bucket_n_batches.append(np.floor((self.data[i]) / self.batch_size))
self.data[i] = self.data... | [
"def",
"make_data_iter_plan",
"(",
"self",
")",
":",
"# truncate each bucket into multiple of batch-size",
"bucket_n_batches",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"self",
".",
"data",
")",
")",
":",
"bucket_n_batches",
".",
"append",
"(",
... | make a random data iteration plan | [
"make",
"a",
"random",
"data",
"iteration",
"plan"
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/rnn/old/bucket_io.py#L200-L233 | train |
apache/incubator-mxnet | amalgamation/amalgamation.py | expand | def expand(x, pending, stage):
"""
Expand the pending files in the current stage.
Parameters
----------
x: str
The file to expand.
pending : str
The list of pending files to expand.
stage: str
The current stage for file expansion, used for matching the prefix of f... | python | def expand(x, pending, stage):
"""
Expand the pending files in the current stage.
Parameters
----------
x: str
The file to expand.
pending : str
The list of pending files to expand.
stage: str
The current stage for file expansion, used for matching the prefix of f... | [
"def",
"expand",
"(",
"x",
",",
"pending",
",",
"stage",
")",
":",
"if",
"x",
"in",
"history",
"and",
"x",
"not",
"in",
"[",
"'mshadow/mshadow/expr_scalar-inl.h'",
"]",
":",
"# MULTIPLE includes",
"return",
"if",
"x",
"in",
"pending",
":",
"#print('loop foun... | Expand the pending files in the current stage.
Parameters
----------
x: str
The file to expand.
pending : str
The list of pending files to expand.
stage: str
The current stage for file expansion, used for matching the prefix of files. | [
"Expand",
"the",
"pending",
"files",
"in",
"the",
"current",
"stage",
"."
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/amalgamation/amalgamation.py#L112-L182 | train |
apache/incubator-mxnet | example/gluon/data.py | get_imagenet_iterator | def get_imagenet_iterator(root, batch_size, num_workers, data_shape=224, dtype='float32'):
"""Dataset loader with preprocessing."""
train_dir = os.path.join(root, 'train')
train_transform, val_transform = get_imagenet_transforms(data_shape, dtype)
logging.info("Loading image folder %s, this may take a b... | python | def get_imagenet_iterator(root, batch_size, num_workers, data_shape=224, dtype='float32'):
"""Dataset loader with preprocessing."""
train_dir = os.path.join(root, 'train')
train_transform, val_transform = get_imagenet_transforms(data_shape, dtype)
logging.info("Loading image folder %s, this may take a b... | [
"def",
"get_imagenet_iterator",
"(",
"root",
",",
"batch_size",
",",
"num_workers",
",",
"data_shape",
"=",
"224",
",",
"dtype",
"=",
"'float32'",
")",
":",
"train_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"root",
",",
"'train'",
")",
"train_transfor... | Dataset loader with preprocessing. | [
"Dataset",
"loader",
"with",
"preprocessing",
"."
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/gluon/data.py#L76-L91 | train |
apache/incubator-mxnet | python/mxnet/contrib/text/embedding.py | create | def create(embedding_name, **kwargs):
"""Creates an instance of token embedding.
Creates a token embedding instance by loading embedding vectors from an externally hosted
pre-trained token embedding file, such as those of GloVe and FastText. To get all the valid
`embedding_name` and `pretrained_file_n... | python | def create(embedding_name, **kwargs):
"""Creates an instance of token embedding.
Creates a token embedding instance by loading embedding vectors from an externally hosted
pre-trained token embedding file, such as those of GloVe and FastText. To get all the valid
`embedding_name` and `pretrained_file_n... | [
"def",
"create",
"(",
"embedding_name",
",",
"*",
"*",
"kwargs",
")",
":",
"create_text_embedding",
"=",
"registry",
".",
"get_create_func",
"(",
"_TokenEmbedding",
",",
"'token embedding'",
")",
"return",
"create_text_embedding",
"(",
"embedding_name",
",",
"*",
... | Creates an instance of token embedding.
Creates a token embedding instance by loading embedding vectors from an externally hosted
pre-trained token embedding file, such as those of GloVe and FastText. To get all the valid
`embedding_name` and `pretrained_file_name`, use
`mxnet.contrib.text.embedding.g... | [
"Creates",
"an",
"instance",
"of",
"token",
"embedding",
"."
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/contrib/text/embedding.py#L63-L87 | train |
apache/incubator-mxnet | python/mxnet/contrib/text/embedding.py | get_pretrained_file_names | def get_pretrained_file_names(embedding_name=None):
"""Get valid token embedding names and their pre-trained file names.
To load token embedding vectors from an externally hosted pre-trained token embedding file,
such as those of GloVe and FastText, one should use
`mxnet.contrib.text.embedding.create(... | python | def get_pretrained_file_names(embedding_name=None):
"""Get valid token embedding names and their pre-trained file names.
To load token embedding vectors from an externally hosted pre-trained token embedding file,
such as those of GloVe and FastText, one should use
`mxnet.contrib.text.embedding.create(... | [
"def",
"get_pretrained_file_names",
"(",
"embedding_name",
"=",
"None",
")",
":",
"text_embedding_reg",
"=",
"registry",
".",
"get_registry",
"(",
"_TokenEmbedding",
")",
"if",
"embedding_name",
"is",
"not",
"None",
":",
"if",
"embedding_name",
"not",
"in",
"text_... | Get valid token embedding names and their pre-trained file names.
To load token embedding vectors from an externally hosted pre-trained token embedding file,
such as those of GloVe and FastText, one should use
`mxnet.contrib.text.embedding.create(embedding_name, pretrained_file_name)`.
This method ret... | [
"Get",
"valid",
"token",
"embedding",
"names",
"and",
"their",
"pre",
"-",
"trained",
"file",
"names",
"."
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/contrib/text/embedding.py#L90-L130 | train |
apache/incubator-mxnet | python/mxnet/contrib/text/embedding.py | _TokenEmbedding._load_embedding | def _load_embedding(self, pretrained_file_path, elem_delim, init_unknown_vec, encoding='utf8'):
"""Load embedding vectors from the pre-trained token embedding file.
For every unknown token, if its representation `self.unknown_token` is encountered in the
pre-trained token embedding file, index... | python | def _load_embedding(self, pretrained_file_path, elem_delim, init_unknown_vec, encoding='utf8'):
"""Load embedding vectors from the pre-trained token embedding file.
For every unknown token, if its representation `self.unknown_token` is encountered in the
pre-trained token embedding file, index... | [
"def",
"_load_embedding",
"(",
"self",
",",
"pretrained_file_path",
",",
"elem_delim",
",",
"init_unknown_vec",
",",
"encoding",
"=",
"'utf8'",
")",
":",
"pretrained_file_path",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"pretrained_file_path",
")",
"if",
"... | Load embedding vectors from the pre-trained token embedding file.
For every unknown token, if its representation `self.unknown_token` is encountered in the
pre-trained token embedding file, index 0 of `self.idx_to_vec` maps to the pre-trained token
embedding vector loaded from the file; otherw... | [
"Load",
"embedding",
"vectors",
"from",
"the",
"pre",
"-",
"trained",
"token",
"embedding",
"file",
"."
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/contrib/text/embedding.py#L232-L303 | train |
apache/incubator-mxnet | python/mxnet/contrib/text/embedding.py | _TokenEmbedding._set_idx_to_vec_by_embeddings | def _set_idx_to_vec_by_embeddings(self, token_embeddings, vocab_len, vocab_idx_to_token):
"""Sets the mapping between token indices and token embedding vectors.
Parameters
----------
token_embeddings : instance or list `mxnet.contrib.text.embedding._TokenEmbedding`
One or m... | python | def _set_idx_to_vec_by_embeddings(self, token_embeddings, vocab_len, vocab_idx_to_token):
"""Sets the mapping between token indices and token embedding vectors.
Parameters
----------
token_embeddings : instance or list `mxnet.contrib.text.embedding._TokenEmbedding`
One or m... | [
"def",
"_set_idx_to_vec_by_embeddings",
"(",
"self",
",",
"token_embeddings",
",",
"vocab_len",
",",
"vocab_idx_to_token",
")",
":",
"new_vec_len",
"=",
"sum",
"(",
"embed",
".",
"vec_len",
"for",
"embed",
"in",
"token_embeddings",
")",
"new_idx_to_vec",
"=",
"nd"... | Sets the mapping between token indices and token embedding vectors.
Parameters
----------
token_embeddings : instance or list `mxnet.contrib.text.embedding._TokenEmbedding`
One or multiple pre-trained token embeddings to load. If it is a list of multiple
embeddings, the... | [
"Sets",
"the",
"mapping",
"between",
"token",
"indices",
"and",
"token",
"embedding",
"vectors",
"."
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/contrib/text/embedding.py#L314-L343 | train |
apache/incubator-mxnet | python/mxnet/contrib/text/embedding.py | _TokenEmbedding.get_vecs_by_tokens | def get_vecs_by_tokens(self, tokens, lower_case_backup=False):
"""Look up embedding vectors of tokens.
Parameters
----------
tokens : str or list of strs
A token or a list of tokens.
lower_case_backup : bool, default False
If False, each token in the ori... | python | def get_vecs_by_tokens(self, tokens, lower_case_backup=False):
"""Look up embedding vectors of tokens.
Parameters
----------
tokens : str or list of strs
A token or a list of tokens.
lower_case_backup : bool, default False
If False, each token in the ori... | [
"def",
"get_vecs_by_tokens",
"(",
"self",
",",
"tokens",
",",
"lower_case_backup",
"=",
"False",
")",
":",
"to_reduce",
"=",
"False",
"if",
"not",
"isinstance",
"(",
"tokens",
",",
"list",
")",
":",
"tokens",
"=",
"[",
"tokens",
"]",
"to_reduce",
"=",
"T... | Look up embedding vectors of tokens.
Parameters
----------
tokens : str or list of strs
A token or a list of tokens.
lower_case_backup : bool, default False
If False, each token in the original case will be looked up; if True, each token in the
origi... | [
"Look",
"up",
"embedding",
"vectors",
"of",
"tokens",
"."
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/contrib/text/embedding.py#L366-L403 | train |
apache/incubator-mxnet | python/mxnet/contrib/text/embedding.py | _TokenEmbedding.update_token_vectors | def update_token_vectors(self, tokens, new_vectors):
"""Updates embedding vectors for tokens.
Parameters
----------
tokens : str or a list of strs
A token or a list of tokens whose embedding vector are to be updated.
new_vectors : mxnet.ndarray.NDArray
A... | python | def update_token_vectors(self, tokens, new_vectors):
"""Updates embedding vectors for tokens.
Parameters
----------
tokens : str or a list of strs
A token or a list of tokens whose embedding vector are to be updated.
new_vectors : mxnet.ndarray.NDArray
A... | [
"def",
"update_token_vectors",
"(",
"self",
",",
"tokens",
",",
"new_vectors",
")",
":",
"assert",
"self",
".",
"idx_to_vec",
"is",
"not",
"None",
",",
"'The property `idx_to_vec` has not been properly set.'",
"if",
"not",
"isinstance",
"(",
"tokens",
",",
"list",
... | Updates embedding vectors for tokens.
Parameters
----------
tokens : str or a list of strs
A token or a list of tokens whose embedding vector are to be updated.
new_vectors : mxnet.ndarray.NDArray
An NDArray to be assigned to the embedding vectors of `tokens`. I... | [
"Updates",
"embedding",
"vectors",
"for",
"tokens",
"."
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/contrib/text/embedding.py#L405-L447 | train |
apache/incubator-mxnet | python/mxnet/contrib/text/embedding.py | _TokenEmbedding._check_pretrained_file_names | def _check_pretrained_file_names(cls, pretrained_file_name):
"""Checks if a pre-trained token embedding file name is valid.
Parameters
----------
pretrained_file_name : str
The pre-trained token embedding file.
"""
embedding_name = cls.__name__.lower()
... | python | def _check_pretrained_file_names(cls, pretrained_file_name):
"""Checks if a pre-trained token embedding file name is valid.
Parameters
----------
pretrained_file_name : str
The pre-trained token embedding file.
"""
embedding_name = cls.__name__.lower()
... | [
"def",
"_check_pretrained_file_names",
"(",
"cls",
",",
"pretrained_file_name",
")",
":",
"embedding_name",
"=",
"cls",
".",
"__name__",
".",
"lower",
"(",
")",
"if",
"pretrained_file_name",
"not",
"in",
"cls",
".",
"pretrained_file_name_sha1",
":",
"raise",
"KeyE... | Checks if a pre-trained token embedding file name is valid.
Parameters
----------
pretrained_file_name : str
The pre-trained token embedding file. | [
"Checks",
"if",
"a",
"pre",
"-",
"trained",
"token",
"embedding",
"file",
"name",
"is",
"valid",
"."
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/contrib/text/embedding.py#L450-L465 | train |
apache/incubator-mxnet | example/bayesian-methods/algos.py | calc_grad | def calc_grad(exe, exe_grads, params, X, Y, label_name=None, outgrad_f=None):
"""Calculate gradient"""
exe.copy_params_from(params)
exe.arg_dict['data'][:] = X
if outgrad_f is None:
exe.arg_dict[label_name][:] = Y
exe.forward(is_train=True)
exe.backward()
else:
exe.fo... | python | def calc_grad(exe, exe_grads, params, X, Y, label_name=None, outgrad_f=None):
"""Calculate gradient"""
exe.copy_params_from(params)
exe.arg_dict['data'][:] = X
if outgrad_f is None:
exe.arg_dict[label_name][:] = Y
exe.forward(is_train=True)
exe.backward()
else:
exe.fo... | [
"def",
"calc_grad",
"(",
"exe",
",",
"exe_grads",
",",
"params",
",",
"X",
",",
"Y",
",",
"label_name",
"=",
"None",
",",
"outgrad_f",
"=",
"None",
")",
":",
"exe",
".",
"copy_params_from",
"(",
"params",
")",
"exe",
".",
"arg_dict",
"[",
"'data'",
"... | Calculate gradient | [
"Calculate",
"gradient"
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/bayesian-methods/algos.py#L37-L49 | train |
apache/incubator-mxnet | example/bayesian-methods/algos.py | step_HMC | def step_HMC(exe, exe_params, exe_grads, label_key, noise_precision, prior_precision, L=10, eps=1E-6):
"""Generate the implementation of step HMC"""
init_params = {k: v.copyto(v.context) for k, v in exe_params.items()}
end_params = {k: v.copyto(v.context) for k, v in exe_params.items()}
init_momentums =... | python | def step_HMC(exe, exe_params, exe_grads, label_key, noise_precision, prior_precision, L=10, eps=1E-6):
"""Generate the implementation of step HMC"""
init_params = {k: v.copyto(v.context) for k, v in exe_params.items()}
end_params = {k: v.copyto(v.context) for k, v in exe_params.items()}
init_momentums =... | [
"def",
"step_HMC",
"(",
"exe",
",",
"exe_params",
",",
"exe_grads",
",",
"label_key",
",",
"noise_precision",
",",
"prior_precision",
",",
"L",
"=",
"10",
",",
"eps",
"=",
"1E-6",
")",
":",
"init_params",
"=",
"{",
"k",
":",
"v",
".",
"copyto",
"(",
... | Generate the implementation of step HMC | [
"Generate",
"the",
"implementation",
"of",
"step",
"HMC"
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/bayesian-methods/algos.py#L52-L100 | train |
apache/incubator-mxnet | example/bayesian-methods/algos.py | HMC | def HMC(sym, data_inputs, X, Y, X_test, Y_test, sample_num,
initializer=None, noise_precision=1 / 9.0, prior_precision=0.1,
learning_rate=1E-6, L=10, dev=mx.gpu()):
"""Generate the implementation of HMC"""
label_key = list(set(data_inputs.keys()) - set(['data']))[0]
exe, exe_params, exe_grad... | python | def HMC(sym, data_inputs, X, Y, X_test, Y_test, sample_num,
initializer=None, noise_precision=1 / 9.0, prior_precision=0.1,
learning_rate=1E-6, L=10, dev=mx.gpu()):
"""Generate the implementation of HMC"""
label_key = list(set(data_inputs.keys()) - set(['data']))[0]
exe, exe_params, exe_grad... | [
"def",
"HMC",
"(",
"sym",
",",
"data_inputs",
",",
"X",
",",
"Y",
",",
"X_test",
",",
"Y_test",
",",
"sample_num",
",",
"initializer",
"=",
"None",
",",
"noise_precision",
"=",
"1",
"/",
"9.0",
",",
"prior_precision",
"=",
"0.1",
",",
"learning_rate",
... | Generate the implementation of HMC | [
"Generate",
"the",
"implementation",
"of",
"HMC"
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/bayesian-methods/algos.py#L103-L130 | train |
apache/incubator-mxnet | example/bayesian-methods/algos.py | SGD | def SGD(sym, data_inputs, X, Y, X_test, Y_test, total_iter_num,
lr=None,
lr_scheduler=None, prior_precision=1,
out_grad_f=None,
initializer=None,
minibatch_size=100, dev=mx.gpu()):
"""Generate the implementation of SGD"""
if out_grad_f is None:
label_key = list(se... | python | def SGD(sym, data_inputs, X, Y, X_test, Y_test, total_iter_num,
lr=None,
lr_scheduler=None, prior_precision=1,
out_grad_f=None,
initializer=None,
minibatch_size=100, dev=mx.gpu()):
"""Generate the implementation of SGD"""
if out_grad_f is None:
label_key = list(se... | [
"def",
"SGD",
"(",
"sym",
",",
"data_inputs",
",",
"X",
",",
"Y",
",",
"X_test",
",",
"Y_test",
",",
"total_iter_num",
",",
"lr",
"=",
"None",
",",
"lr_scheduler",
"=",
"None",
",",
"prior_precision",
"=",
"1",
",",
"out_grad_f",
"=",
"None",
",",
"i... | Generate the implementation of SGD | [
"Generate",
"the",
"implementation",
"of",
"SGD"
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/bayesian-methods/algos.py#L133-L168 | train |
apache/incubator-mxnet | example/bayesian-methods/algos.py | SGLD | def SGLD(sym, X, Y, X_test, Y_test, total_iter_num,
data_inputs=None,
learning_rate=None,
lr_scheduler=None, prior_precision=1,
out_grad_f=None,
initializer=None,
minibatch_size=100, thin_interval=100, burn_in_iter_num=1000, task='classification',
dev=mx.gp... | python | def SGLD(sym, X, Y, X_test, Y_test, total_iter_num,
data_inputs=None,
learning_rate=None,
lr_scheduler=None, prior_precision=1,
out_grad_f=None,
initializer=None,
minibatch_size=100, thin_interval=100, burn_in_iter_num=1000, task='classification',
dev=mx.gp... | [
"def",
"SGLD",
"(",
"sym",
",",
"X",
",",
"Y",
",",
"X_test",
",",
"Y_test",
",",
"total_iter_num",
",",
"data_inputs",
"=",
"None",
",",
"learning_rate",
"=",
"None",
",",
"lr_scheduler",
"=",
"None",
",",
"prior_precision",
"=",
"1",
",",
"out_grad_f",... | Generate the implementation of SGLD | [
"Generate",
"the",
"implementation",
"of",
"SGLD"
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/bayesian-methods/algos.py#L171-L228 | train |
apache/incubator-mxnet | example/bayesian-methods/algos.py | DistilledSGLD | def DistilledSGLD(teacher_sym, student_sym,
teacher_data_inputs, student_data_inputs,
X, Y, X_test, Y_test, total_iter_num,
teacher_learning_rate, student_learning_rate,
teacher_lr_scheduler=None, student_lr_scheduler=None,
studen... | python | def DistilledSGLD(teacher_sym, student_sym,
teacher_data_inputs, student_data_inputs,
X, Y, X_test, Y_test, total_iter_num,
teacher_learning_rate, student_learning_rate,
teacher_lr_scheduler=None, student_lr_scheduler=None,
studen... | [
"def",
"DistilledSGLD",
"(",
"teacher_sym",
",",
"student_sym",
",",
"teacher_data_inputs",
",",
"student_data_inputs",
",",
"X",
",",
"Y",
",",
"X_test",
",",
"Y_test",
",",
"total_iter_num",
",",
"teacher_learning_rate",
",",
"student_learning_rate",
",",
"teacher... | Generate the implementation of DistilledSGLD | [
"Generate",
"the",
"implementation",
"of",
"DistilledSGLD"
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/bayesian-methods/algos.py#L231-L343 | train |
apache/incubator-mxnet | ci/build.py | get_platforms | def get_platforms(path: str = get_dockerfiles_path()) -> List[str]:
"""Get a list of architectures given our dockerfiles"""
dockerfiles = glob.glob(os.path.join(path, "Dockerfile.*"))
dockerfiles = list(filter(lambda x: x[-1] != '~', dockerfiles))
files = list(map(lambda x: re.sub(r"Dockerfile.(.*)", r"... | python | def get_platforms(path: str = get_dockerfiles_path()) -> List[str]:
"""Get a list of architectures given our dockerfiles"""
dockerfiles = glob.glob(os.path.join(path, "Dockerfile.*"))
dockerfiles = list(filter(lambda x: x[-1] != '~', dockerfiles))
files = list(map(lambda x: re.sub(r"Dockerfile.(.*)", r"... | [
"def",
"get_platforms",
"(",
"path",
":",
"str",
"=",
"get_dockerfiles_path",
"(",
")",
")",
"->",
"List",
"[",
"str",
"]",
":",
"dockerfiles",
"=",
"glob",
".",
"glob",
"(",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"\"Dockerfile.*\"",
")",
... | Get a list of architectures given our dockerfiles | [
"Get",
"a",
"list",
"of",
"architectures",
"given",
"our",
"dockerfiles"
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/ci/build.py#L93-L99 | train |
apache/incubator-mxnet | ci/build.py | get_docker_tag | def get_docker_tag(platform: str, registry: str) -> str:
""":return: docker tag to be used for the container"""
platform = platform if any(x in platform for x in ['build.', 'publish.']) else 'build.{}'.format(platform)
if not registry:
registry = "mxnet_local"
return "{0}/{1}".format(registry, p... | python | def get_docker_tag(platform: str, registry: str) -> str:
""":return: docker tag to be used for the container"""
platform = platform if any(x in platform for x in ['build.', 'publish.']) else 'build.{}'.format(platform)
if not registry:
registry = "mxnet_local"
return "{0}/{1}".format(registry, p... | [
"def",
"get_docker_tag",
"(",
"platform",
":",
"str",
",",
"registry",
":",
"str",
")",
"->",
"str",
":",
"platform",
"=",
"platform",
"if",
"any",
"(",
"x",
"in",
"platform",
"for",
"x",
"in",
"[",
"'build.'",
",",
"'publish.'",
"]",
")",
"else",
"'... | :return: docker tag to be used for the container | [
":",
"return",
":",
"docker",
"tag",
"to",
"be",
"used",
"for",
"the",
"container"
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/ci/build.py#L102-L107 | train |
apache/incubator-mxnet | ci/build.py | build_docker | def build_docker(platform: str, docker_binary: str, registry: str, num_retries: int, no_cache: bool) -> str:
"""
Build a container for the given platform
:param platform: Platform
:param docker_binary: docker binary to use (docker/nvidia-docker)
:param registry: Dockerhub registry name
:param nu... | python | def build_docker(platform: str, docker_binary: str, registry: str, num_retries: int, no_cache: bool) -> str:
"""
Build a container for the given platform
:param platform: Platform
:param docker_binary: docker binary to use (docker/nvidia-docker)
:param registry: Dockerhub registry name
:param nu... | [
"def",
"build_docker",
"(",
"platform",
":",
"str",
",",
"docker_binary",
":",
"str",
",",
"registry",
":",
"str",
",",
"num_retries",
":",
"int",
",",
"no_cache",
":",
"bool",
")",
"->",
"str",
":",
"tag",
"=",
"get_docker_tag",
"(",
"platform",
"=",
... | Build a container for the given platform
:param platform: Platform
:param docker_binary: docker binary to use (docker/nvidia-docker)
:param registry: Dockerhub registry name
:param num_retries: Number of retries to build the docker image
:param no_cache: pass no-cache to docker to rebuild the images... | [
"Build",
"a",
"container",
"for",
"the",
"given",
"platform",
":",
"param",
"platform",
":",
"Platform",
":",
"param",
"docker_binary",
":",
"docker",
"binary",
"to",
"use",
"(",
"docker",
"/",
"nvidia",
"-",
"docker",
")",
":",
"param",
"registry",
":",
... | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/ci/build.py#L119-L168 | train |
apache/incubator-mxnet | ci/build.py | _get_local_image_id | def _get_local_image_id(docker_binary, docker_tag):
"""
Get the image id of the local docker layer with the passed tag
:param docker_tag: docker tag
:return: Image id as string or None if tag does not exist
"""
cmd = [docker_binary, "images", "-q", docker_tag]
image_id_b = check_output(cmd)
... | python | def _get_local_image_id(docker_binary, docker_tag):
"""
Get the image id of the local docker layer with the passed tag
:param docker_tag: docker tag
:return: Image id as string or None if tag does not exist
"""
cmd = [docker_binary, "images", "-q", docker_tag]
image_id_b = check_output(cmd)
... | [
"def",
"_get_local_image_id",
"(",
"docker_binary",
",",
"docker_tag",
")",
":",
"cmd",
"=",
"[",
"docker_binary",
",",
"\"images\"",
",",
"\"-q\"",
",",
"docker_tag",
"]",
"image_id_b",
"=",
"check_output",
"(",
"cmd",
")",
"image_id",
"=",
"image_id_b",
".",... | Get the image id of the local docker layer with the passed tag
:param docker_tag: docker tag
:return: Image id as string or None if tag does not exist | [
"Get",
"the",
"image",
"id",
"of",
"the",
"local",
"docker",
"layer",
"with",
"the",
"passed",
"tag",
":",
"param",
"docker_tag",
":",
"docker",
"tag",
":",
"return",
":",
"Image",
"id",
"as",
"string",
"or",
"None",
"if",
"tag",
"does",
"not",
"exist"... | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/ci/build.py#L171-L182 | train |
apache/incubator-mxnet | ci/build.py | default_ccache_dir | def default_ccache_dir() -> str:
""":return: ccache directory for the current platform"""
# Share ccache across containers
if 'CCACHE_DIR' in os.environ:
ccache_dir = os.path.realpath(os.environ['CCACHE_DIR'])
try:
os.makedirs(ccache_dir, exist_ok=True)
return ccache_... | python | def default_ccache_dir() -> str:
""":return: ccache directory for the current platform"""
# Share ccache across containers
if 'CCACHE_DIR' in os.environ:
ccache_dir = os.path.realpath(os.environ['CCACHE_DIR'])
try:
os.makedirs(ccache_dir, exist_ok=True)
return ccache_... | [
"def",
"default_ccache_dir",
"(",
")",
"->",
"str",
":",
"# Share ccache across containers",
"if",
"'CCACHE_DIR'",
"in",
"os",
".",
"environ",
":",
"ccache_dir",
"=",
"os",
".",
"path",
".",
"realpath",
"(",
"os",
".",
"environ",
"[",
"'CCACHE_DIR'",
"]",
")... | :return: ccache directory for the current platform | [
":",
"return",
":",
"ccache",
"directory",
"for",
"the",
"current",
"platform"
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/ci/build.py#L189-L205 | train |
apache/incubator-mxnet | ci/build.py | container_run | def container_run(platform: str,
nvidia_runtime: bool,
docker_registry: str,
shared_memory_size: str,
local_ccache_dir: str,
command: List[str],
cleanup: Cleanup,
environment: Dict[str, str],
... | python | def container_run(platform: str,
nvidia_runtime: bool,
docker_registry: str,
shared_memory_size: str,
local_ccache_dir: str,
command: List[str],
cleanup: Cleanup,
environment: Dict[str, str],
... | [
"def",
"container_run",
"(",
"platform",
":",
"str",
",",
"nvidia_runtime",
":",
"bool",
",",
"docker_registry",
":",
"str",
",",
"shared_memory_size",
":",
"str",
",",
"local_ccache_dir",
":",
"str",
",",
"command",
":",
"List",
"[",
"str",
"]",
",",
"cle... | Run command in a container | [
"Run",
"command",
"in",
"a",
"container"
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/ci/build.py#L213-L361 | train |
apache/incubator-mxnet | ci/build.py | load_docker_cache | def load_docker_cache(tag, docker_registry) -> None:
"""Imports tagged container from the given docker registry"""
if docker_registry:
# noinspection PyBroadException
try:
import docker_cache
logging.info('Docker cache download is enabled from registry %s', docker_registr... | python | def load_docker_cache(tag, docker_registry) -> None:
"""Imports tagged container from the given docker registry"""
if docker_registry:
# noinspection PyBroadException
try:
import docker_cache
logging.info('Docker cache download is enabled from registry %s', docker_registr... | [
"def",
"load_docker_cache",
"(",
"tag",
",",
"docker_registry",
")",
"->",
"None",
":",
"if",
"docker_registry",
":",
"# noinspection PyBroadException",
"try",
":",
"import",
"docker_cache",
"logging",
".",
"info",
"(",
"'Docker cache download is enabled from registry %s'... | Imports tagged container from the given docker registry | [
"Imports",
"tagged",
"container",
"from",
"the",
"given",
"docker",
"registry"
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/ci/build.py#L368-L379 | train |
apache/incubator-mxnet | python/mxnet/module/executor_group.py | _load_general | def _load_general(data, targets, major_axis):
"""Load a list of arrays into a list of arrays specified by slices."""
for d_src, d_targets, axis in zip(data, targets, major_axis): # pylint: disable=too-many-nested-blocks
if isinstance(d_targets, nd.NDArray):
d_src.copyto(d_targets)
el... | python | def _load_general(data, targets, major_axis):
"""Load a list of arrays into a list of arrays specified by slices."""
for d_src, d_targets, axis in zip(data, targets, major_axis): # pylint: disable=too-many-nested-blocks
if isinstance(d_targets, nd.NDArray):
d_src.copyto(d_targets)
el... | [
"def",
"_load_general",
"(",
"data",
",",
"targets",
",",
"major_axis",
")",
":",
"for",
"d_src",
",",
"d_targets",
",",
"axis",
"in",
"zip",
"(",
"data",
",",
"targets",
",",
"major_axis",
")",
":",
"# pylint: disable=too-many-nested-blocks",
"if",
"isinstanc... | Load a list of arrays into a list of arrays specified by slices. | [
"Load",
"a",
"list",
"of",
"arrays",
"into",
"a",
"list",
"of",
"arrays",
"specified",
"by",
"slices",
"."
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/module/executor_group.py#L31-L62 | train |
apache/incubator-mxnet | python/mxnet/module/executor_group.py | _load_data | def _load_data(batch, targets, major_axis):
"""Load data into sliced arrays."""
if isinstance(batch, list):
new_batch = []
for i in range(len(targets)):
new_batch.append([b.data[i] for b in batch])
new_targets = [[dst for _, dst in d_target] for d_target in targets]
_... | python | def _load_data(batch, targets, major_axis):
"""Load data into sliced arrays."""
if isinstance(batch, list):
new_batch = []
for i in range(len(targets)):
new_batch.append([b.data[i] for b in batch])
new_targets = [[dst for _, dst in d_target] for d_target in targets]
_... | [
"def",
"_load_data",
"(",
"batch",
",",
"targets",
",",
"major_axis",
")",
":",
"if",
"isinstance",
"(",
"batch",
",",
"list",
")",
":",
"new_batch",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"targets",
")",
")",
":",
"new_batch",
... | Load data into sliced arrays. | [
"Load",
"data",
"into",
"sliced",
"arrays",
"."
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/module/executor_group.py#L65-L74 | train |
apache/incubator-mxnet | python/mxnet/module/executor_group.py | _merge_multi_context | def _merge_multi_context(outputs, major_axis):
"""Merge outputs that lives on multiple context into one, so that they look
like living on one context.
"""
rets = []
for tensors, axis in zip(outputs, major_axis):
if axis >= 0:
# pylint: disable=no-member,protected-access
... | python | def _merge_multi_context(outputs, major_axis):
"""Merge outputs that lives on multiple context into one, so that they look
like living on one context.
"""
rets = []
for tensors, axis in zip(outputs, major_axis):
if axis >= 0:
# pylint: disable=no-member,protected-access
... | [
"def",
"_merge_multi_context",
"(",
"outputs",
",",
"major_axis",
")",
":",
"rets",
"=",
"[",
"]",
"for",
"tensors",
",",
"axis",
"in",
"zip",
"(",
"outputs",
",",
"major_axis",
")",
":",
"if",
"axis",
">=",
"0",
":",
"# pylint: disable=no-member,protected-a... | Merge outputs that lives on multiple context into one, so that they look
like living on one context. | [
"Merge",
"outputs",
"that",
"lives",
"on",
"multiple",
"context",
"into",
"one",
"so",
"that",
"they",
"look",
"like",
"living",
"on",
"one",
"context",
"."
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/module/executor_group.py#L89-L110 | train |
apache/incubator-mxnet | python/mxnet/module/executor_group.py | _prepare_group2ctxs | def _prepare_group2ctxs(group2ctxs, ctx_len):
"""Prepare the group2contexts, will duplicate the context
if some ctx_group map to only one context.
"""
if group2ctxs is None:
return [None] * ctx_len
elif isinstance(group2ctxs, list):
assert(len(group2ctxs) == ctx_len), "length of grou... | python | def _prepare_group2ctxs(group2ctxs, ctx_len):
"""Prepare the group2contexts, will duplicate the context
if some ctx_group map to only one context.
"""
if group2ctxs is None:
return [None] * ctx_len
elif isinstance(group2ctxs, list):
assert(len(group2ctxs) == ctx_len), "length of grou... | [
"def",
"_prepare_group2ctxs",
"(",
"group2ctxs",
",",
"ctx_len",
")",
":",
"if",
"group2ctxs",
"is",
"None",
":",
"return",
"[",
"None",
"]",
"*",
"ctx_len",
"elif",
"isinstance",
"(",
"group2ctxs",
",",
"list",
")",
":",
"assert",
"(",
"len",
"(",
"grou... | Prepare the group2contexts, will duplicate the context
if some ctx_group map to only one context. | [
"Prepare",
"the",
"group2contexts",
"will",
"duplicate",
"the",
"context",
"if",
"some",
"ctx_group",
"map",
"to",
"only",
"one",
"context",
"."
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/module/executor_group.py#L112-L141 | train |
apache/incubator-mxnet | python/mxnet/module/executor_group.py | DataParallelExecutorGroup.decide_slices | def decide_slices(self, data_shapes):
"""Decide the slices for each context according to the workload.
Parameters
----------
data_shapes : list
list of (name, shape) specifying the shapes for the input data or label.
"""
assert len(data_shapes) > 0
ma... | python | def decide_slices(self, data_shapes):
"""Decide the slices for each context according to the workload.
Parameters
----------
data_shapes : list
list of (name, shape) specifying the shapes for the input data or label.
"""
assert len(data_shapes) > 0
ma... | [
"def",
"decide_slices",
"(",
"self",
",",
"data_shapes",
")",
":",
"assert",
"len",
"(",
"data_shapes",
")",
">",
"0",
"major_axis",
"=",
"[",
"DataDesc",
".",
"get_batch_axis",
"(",
"x",
".",
"layout",
")",
"for",
"x",
"in",
"data_shapes",
"]",
"for",
... | Decide the slices for each context according to the workload.
Parameters
----------
data_shapes : list
list of (name, shape) specifying the shapes for the input data or label. | [
"Decide",
"the",
"slices",
"for",
"each",
"context",
"according",
"to",
"the",
"workload",
"."
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/module/executor_group.py#L281-L305 | train |
apache/incubator-mxnet | python/mxnet/module/executor_group.py | DataParallelExecutorGroup._collect_arrays | def _collect_arrays(self):
"""Collect internal arrays from executors."""
# convenient data structures
self.data_arrays = [[(self.slices[i], e.arg_dict[name]) for i, e in enumerate(self.execs)]
for name, _ in self.data_shapes]
self.state_arrays = [[e.arg_dict[... | python | def _collect_arrays(self):
"""Collect internal arrays from executors."""
# convenient data structures
self.data_arrays = [[(self.slices[i], e.arg_dict[name]) for i, e in enumerate(self.execs)]
for name, _ in self.data_shapes]
self.state_arrays = [[e.arg_dict[... | [
"def",
"_collect_arrays",
"(",
"self",
")",
":",
"# convenient data structures",
"self",
".",
"data_arrays",
"=",
"[",
"[",
"(",
"self",
".",
"slices",
"[",
"i",
"]",
",",
"e",
".",
"arg_dict",
"[",
"name",
"]",
")",
"for",
"i",
",",
"e",
"in",
"enum... | Collect internal arrays from executors. | [
"Collect",
"internal",
"arrays",
"from",
"executors",
"."
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/module/executor_group.py#L307-L342 | train |
apache/incubator-mxnet | python/mxnet/module/executor_group.py | DataParallelExecutorGroup.bind_exec | def bind_exec(self, data_shapes, label_shapes, shared_group=None, reshape=False):
"""Bind executors on their respective devices.
Parameters
----------
data_shapes : list
label_shapes : list
shared_group : DataParallelExecutorGroup
reshape : bool
"""
... | python | def bind_exec(self, data_shapes, label_shapes, shared_group=None, reshape=False):
"""Bind executors on their respective devices.
Parameters
----------
data_shapes : list
label_shapes : list
shared_group : DataParallelExecutorGroup
reshape : bool
"""
... | [
"def",
"bind_exec",
"(",
"self",
",",
"data_shapes",
",",
"label_shapes",
",",
"shared_group",
"=",
"None",
",",
"reshape",
"=",
"False",
")",
":",
"assert",
"reshape",
"or",
"not",
"self",
".",
"execs",
"self",
".",
"batch_size",
"=",
"None",
"# calculate... | Bind executors on their respective devices.
Parameters
----------
data_shapes : list
label_shapes : list
shared_group : DataParallelExecutorGroup
reshape : bool | [
"Bind",
"executors",
"on",
"their",
"respective",
"devices",
"."
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/module/executor_group.py#L344-L382 | train |
apache/incubator-mxnet | python/mxnet/module/executor_group.py | DataParallelExecutorGroup.reshape | def reshape(self, data_shapes, label_shapes):
"""Reshape executors.
Parameters
----------
data_shapes : list
label_shapes : list
"""
if data_shapes == self.data_shapes and label_shapes == self.label_shapes:
return
if self._default_execs is Non... | python | def reshape(self, data_shapes, label_shapes):
"""Reshape executors.
Parameters
----------
data_shapes : list
label_shapes : list
"""
if data_shapes == self.data_shapes and label_shapes == self.label_shapes:
return
if self._default_execs is Non... | [
"def",
"reshape",
"(",
"self",
",",
"data_shapes",
",",
"label_shapes",
")",
":",
"if",
"data_shapes",
"==",
"self",
".",
"data_shapes",
"and",
"label_shapes",
"==",
"self",
".",
"label_shapes",
":",
"return",
"if",
"self",
".",
"_default_execs",
"is",
"None... | Reshape executors.
Parameters
----------
data_shapes : list
label_shapes : list | [
"Reshape",
"executors",
"."
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/module/executor_group.py#L384-L396 | train |
apache/incubator-mxnet | python/mxnet/module/executor_group.py | DataParallelExecutorGroup.set_params | def set_params(self, arg_params, aux_params, allow_extra=False):
"""Assign, i.e. copy parameters to all the executors.
Parameters
----------
arg_params : dict
A dictionary of name to `NDArray` parameter mapping.
aux_params : dict
A dictionary of name to `... | python | def set_params(self, arg_params, aux_params, allow_extra=False):
"""Assign, i.e. copy parameters to all the executors.
Parameters
----------
arg_params : dict
A dictionary of name to `NDArray` parameter mapping.
aux_params : dict
A dictionary of name to `... | [
"def",
"set_params",
"(",
"self",
",",
"arg_params",
",",
"aux_params",
",",
"allow_extra",
"=",
"False",
")",
":",
"for",
"exec_",
"in",
"self",
".",
"execs",
":",
"exec_",
".",
"copy_params_from",
"(",
"arg_params",
",",
"aux_params",
",",
"allow_extra_par... | Assign, i.e. copy parameters to all the executors.
Parameters
----------
arg_params : dict
A dictionary of name to `NDArray` parameter mapping.
aux_params : dict
A dictionary of name to `NDArray` auxiliary variable mapping.
allow_extra : boolean, optional... | [
"Assign",
"i",
".",
"e",
".",
"copy",
"parameters",
"to",
"all",
"the",
"executors",
"."
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/module/executor_group.py#L398-L413 | train |
apache/incubator-mxnet | python/mxnet/module/executor_group.py | DataParallelExecutorGroup.get_params | def get_params(self, arg_params, aux_params):
""" Copy data from each executor to `arg_params` and `aux_params`.
Parameters
----------
arg_params : list of NDArray
Target parameter arrays.
aux_params : list of NDArray
Target aux arrays.
Notes
... | python | def get_params(self, arg_params, aux_params):
""" Copy data from each executor to `arg_params` and `aux_params`.
Parameters
----------
arg_params : list of NDArray
Target parameter arrays.
aux_params : list of NDArray
Target aux arrays.
Notes
... | [
"def",
"get_params",
"(",
"self",
",",
"arg_params",
",",
"aux_params",
")",
":",
"for",
"name",
",",
"block",
"in",
"zip",
"(",
"self",
".",
"param_names",
",",
"self",
".",
"param_arrays",
")",
":",
"weight",
"=",
"sum",
"(",
"w",
".",
"copyto",
"(... | Copy data from each executor to `arg_params` and `aux_params`.
Parameters
----------
arg_params : list of NDArray
Target parameter arrays.
aux_params : list of NDArray
Target aux arrays.
Notes
-----
- This function will inplace update the... | [
"Copy",
"data",
"from",
"each",
"executor",
"to",
"arg_params",
"and",
"aux_params",
"."
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/module/executor_group.py#L415-L434 | train |
apache/incubator-mxnet | python/mxnet/module/executor_group.py | DataParallelExecutorGroup.forward | def forward(self, data_batch, is_train=None):
"""Split `data_batch` according to workload and run forward on each devices.
Parameters
----------
data_batch : DataBatch
Or could be any object implementing similar interface.
is_train : bool
The hint for the... | python | def forward(self, data_batch, is_train=None):
"""Split `data_batch` according to workload and run forward on each devices.
Parameters
----------
data_batch : DataBatch
Or could be any object implementing similar interface.
is_train : bool
The hint for the... | [
"def",
"forward",
"(",
"self",
",",
"data_batch",
",",
"is_train",
"=",
"None",
")",
":",
"_load_data",
"(",
"data_batch",
",",
"self",
".",
"data_arrays",
",",
"self",
".",
"data_layouts",
")",
"if",
"is_train",
"is",
"None",
":",
"is_train",
"=",
"self... | Split `data_batch` according to workload and run forward on each devices.
Parameters
----------
data_batch : DataBatch
Or could be any object implementing similar interface.
is_train : bool
The hint for the backend, indicating whether we are during training phase... | [
"Split",
"data_batch",
"according",
"to",
"workload",
"and",
"run",
"forward",
"on",
"each",
"devices",
"."
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/module/executor_group.py#L436-L462 | train |
apache/incubator-mxnet | python/mxnet/module/executor_group.py | DataParallelExecutorGroup.get_output_shapes | def get_output_shapes(self):
"""Get the shapes of the outputs."""
outputs = self.execs[0].outputs
shapes = [out.shape for out in outputs]
concat_shapes = []
for key, the_shape, axis in zip(self.symbol.list_outputs(), shapes, self.output_layouts):
the_shape = list(the... | python | def get_output_shapes(self):
"""Get the shapes of the outputs."""
outputs = self.execs[0].outputs
shapes = [out.shape for out in outputs]
concat_shapes = []
for key, the_shape, axis in zip(self.symbol.list_outputs(), shapes, self.output_layouts):
the_shape = list(the... | [
"def",
"get_output_shapes",
"(",
"self",
")",
":",
"outputs",
"=",
"self",
".",
"execs",
"[",
"0",
"]",
".",
"outputs",
"shapes",
"=",
"[",
"out",
".",
"shape",
"for",
"out",
"in",
"outputs",
"]",
"concat_shapes",
"=",
"[",
"]",
"for",
"key",
",",
... | Get the shapes of the outputs. | [
"Get",
"the",
"shapes",
"of",
"the",
"outputs",
"."
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/module/executor_group.py#L464-L475 | train |
apache/incubator-mxnet | python/mxnet/module/executor_group.py | DataParallelExecutorGroup.get_outputs | def get_outputs(self, merge_multi_context=True, begin=0, end=None):
"""Get outputs of the previous forward computation.
If begin or end is specified, return [begin, end)-th outputs,
otherwise return all outputs.
Parameters
----------
merge_multi_context : bool
... | python | def get_outputs(self, merge_multi_context=True, begin=0, end=None):
"""Get outputs of the previous forward computation.
If begin or end is specified, return [begin, end)-th outputs,
otherwise return all outputs.
Parameters
----------
merge_multi_context : bool
... | [
"def",
"get_outputs",
"(",
"self",
",",
"merge_multi_context",
"=",
"True",
",",
"begin",
"=",
"0",
",",
"end",
"=",
"None",
")",
":",
"if",
"end",
"is",
"None",
":",
"end",
"=",
"self",
".",
"num_outputs",
"outputs",
"=",
"[",
"[",
"exec_",
".",
"... | Get outputs of the previous forward computation.
If begin or end is specified, return [begin, end)-th outputs,
otherwise return all outputs.
Parameters
----------
merge_multi_context : bool
Default is `True`. In the case when data-parallelism is used, the outputs
... | [
"Get",
"outputs",
"of",
"the",
"previous",
"forward",
"computation",
".",
"If",
"begin",
"or",
"end",
"is",
"specified",
"return",
"[",
"begin",
"end",
")",
"-",
"th",
"outputs",
"otherwise",
"return",
"all",
"outputs",
"."
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/module/executor_group.py#L477-L506 | train |
apache/incubator-mxnet | python/mxnet/module/executor_group.py | DataParallelExecutorGroup.set_states | def set_states(self, states=None, value=None):
"""Set value for states. Only one of states & value can be specified.
Parameters
----------
states : list of list of NDArrays
source states arrays formatted like [[state1_dev1, state1_dev2],
[state2_dev1, state2_dev2... | python | def set_states(self, states=None, value=None):
"""Set value for states. Only one of states & value can be specified.
Parameters
----------
states : list of list of NDArrays
source states arrays formatted like [[state1_dev1, state1_dev2],
[state2_dev1, state2_dev2... | [
"def",
"set_states",
"(",
"self",
",",
"states",
"=",
"None",
",",
"value",
"=",
"None",
")",
":",
"if",
"states",
"is",
"not",
"None",
":",
"assert",
"value",
"is",
"None",
",",
"\"Only one of states & value can be specified.\"",
"_load_general",
"(",
"states... | Set value for states. Only one of states & value can be specified.
Parameters
----------
states : list of list of NDArrays
source states arrays formatted like [[state1_dev1, state1_dev2],
[state2_dev1, state2_dev2]].
value : number
a single scalar val... | [
"Set",
"value",
"for",
"states",
".",
"Only",
"one",
"of",
"states",
"&",
"value",
"can",
"be",
"specified",
"."
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/module/executor_group.py#L529-L548 | train |
apache/incubator-mxnet | python/mxnet/module/executor_group.py | DataParallelExecutorGroup.get_input_grads | def get_input_grads(self, merge_multi_context=True):
"""Get the gradients with respect to the inputs of the module.
Parameters
----------
merge_multi_context : bool
Defaults to ``True``. In the case when data-parallelism is used, the outputs
will be collected fro... | python | def get_input_grads(self, merge_multi_context=True):
"""Get the gradients with respect to the inputs of the module.
Parameters
----------
merge_multi_context : bool
Defaults to ``True``. In the case when data-parallelism is used, the outputs
will be collected fro... | [
"def",
"get_input_grads",
"(",
"self",
",",
"merge_multi_context",
"=",
"True",
")",
":",
"assert",
"self",
".",
"inputs_need_grad",
"if",
"merge_multi_context",
":",
"return",
"_merge_multi_context",
"(",
"self",
".",
"input_grad_arrays",
",",
"self",
".",
"data_... | Get the gradients with respect to the inputs of the module.
Parameters
----------
merge_multi_context : bool
Defaults to ``True``. In the case when data-parallelism is used, the outputs
will be collected from multiple devices. A `True` value indicate that we
... | [
"Get",
"the",
"gradients",
"with",
"respect",
"to",
"the",
"inputs",
"of",
"the",
"module",
"."
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/module/executor_group.py#L550-L570 | train |
apache/incubator-mxnet | python/mxnet/module/executor_group.py | DataParallelExecutorGroup.backward | def backward(self, out_grads=None):
"""Run backward on all devices. A backward should be called after
a call to the forward function. Backward cannot be called unless
``self.for_training`` is ``True``.
Parameters
----------
out_grads : NDArray or list of NDArray, optiona... | python | def backward(self, out_grads=None):
"""Run backward on all devices. A backward should be called after
a call to the forward function. Backward cannot be called unless
``self.for_training`` is ``True``.
Parameters
----------
out_grads : NDArray or list of NDArray, optiona... | [
"def",
"backward",
"(",
"self",
",",
"out_grads",
"=",
"None",
")",
":",
"assert",
"self",
".",
"for_training",
",",
"'re-bind with for_training=True to run backward'",
"if",
"out_grads",
"is",
"None",
":",
"out_grads",
"=",
"[",
"]",
"for",
"i",
",",
"(",
"... | Run backward on all devices. A backward should be called after
a call to the forward function. Backward cannot be called unless
``self.for_training`` is ``True``.
Parameters
----------
out_grads : NDArray or list of NDArray, optional
Gradient on the outputs to be pro... | [
"Run",
"backward",
"on",
"all",
"devices",
".",
"A",
"backward",
"should",
"be",
"called",
"after",
"a",
"call",
"to",
"the",
"forward",
"function",
".",
"Backward",
"cannot",
"be",
"called",
"unless",
"self",
".",
"for_training",
"is",
"True",
"."
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/module/executor_group.py#L572-L599 | train |
apache/incubator-mxnet | python/mxnet/module/executor_group.py | DataParallelExecutorGroup.update_metric | def update_metric(self, eval_metric, labels, pre_sliced):
"""Accumulate the performance according to `eval_metric` on all devices
by comparing outputs from [begin, end) to labels. By default use all
outputs.
Parameters
----------
eval_metric : EvalMetric
The ... | python | def update_metric(self, eval_metric, labels, pre_sliced):
"""Accumulate the performance according to `eval_metric` on all devices
by comparing outputs from [begin, end) to labels. By default use all
outputs.
Parameters
----------
eval_metric : EvalMetric
The ... | [
"def",
"update_metric",
"(",
"self",
",",
"eval_metric",
",",
"labels",
",",
"pre_sliced",
")",
":",
"for",
"current_exec",
",",
"(",
"texec",
",",
"islice",
")",
"in",
"enumerate",
"(",
"zip",
"(",
"self",
".",
"execs",
",",
"self",
".",
"slices",
")"... | Accumulate the performance according to `eval_metric` on all devices
by comparing outputs from [begin, end) to labels. By default use all
outputs.
Parameters
----------
eval_metric : EvalMetric
The metric used for evaluation.
labels : list of NDArray
... | [
"Accumulate",
"the",
"performance",
"according",
"to",
"eval_metric",
"on",
"all",
"devices",
"by",
"comparing",
"outputs",
"from",
"[",
"begin",
"end",
")",
"to",
"labels",
".",
"By",
"default",
"use",
"all",
"outputs",
"."
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/module/executor_group.py#L601-L639 | train |
apache/incubator-mxnet | python/mxnet/module/executor_group.py | DataParallelExecutorGroup._bind_ith_exec | def _bind_ith_exec(self, i, data_shapes, label_shapes, shared_group):
"""Internal utility function to bind the i-th executor.
This function utilizes simple_bind python interface.
"""
shared_exec = None if shared_group is None else shared_group.execs[i]
context = self.contexts[i]
... | python | def _bind_ith_exec(self, i, data_shapes, label_shapes, shared_group):
"""Internal utility function to bind the i-th executor.
This function utilizes simple_bind python interface.
"""
shared_exec = None if shared_group is None else shared_group.execs[i]
context = self.contexts[i]
... | [
"def",
"_bind_ith_exec",
"(",
"self",
",",
"i",
",",
"data_shapes",
",",
"label_shapes",
",",
"shared_group",
")",
":",
"shared_exec",
"=",
"None",
"if",
"shared_group",
"is",
"None",
"else",
"shared_group",
".",
"execs",
"[",
"i",
"]",
"context",
"=",
"se... | Internal utility function to bind the i-th executor.
This function utilizes simple_bind python interface. | [
"Internal",
"utility",
"function",
"to",
"bind",
"the",
"i",
"-",
"th",
"executor",
".",
"This",
"function",
"utilizes",
"simple_bind",
"python",
"interface",
"."
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/module/executor_group.py#L641-L664 | train |
apache/incubator-mxnet | python/mxnet/module/executor_group.py | DataParallelExecutorGroup._sliced_shape | def _sliced_shape(self, shapes, i, major_axis):
"""Get the sliced shapes for the i-th executor.
Parameters
----------
shapes : list of (str, tuple)
The original (name, shape) pairs.
i : int
Which executor we are dealing with.
"""
sliced_sh... | python | def _sliced_shape(self, shapes, i, major_axis):
"""Get the sliced shapes for the i-th executor.
Parameters
----------
shapes : list of (str, tuple)
The original (name, shape) pairs.
i : int
Which executor we are dealing with.
"""
sliced_sh... | [
"def",
"_sliced_shape",
"(",
"self",
",",
"shapes",
",",
"i",
",",
"major_axis",
")",
":",
"sliced_shapes",
"=",
"[",
"]",
"for",
"desc",
",",
"axis",
"in",
"zip",
"(",
"shapes",
",",
"major_axis",
")",
":",
"shape",
"=",
"list",
"(",
"desc",
".",
... | Get the sliced shapes for the i-th executor.
Parameters
----------
shapes : list of (str, tuple)
The original (name, shape) pairs.
i : int
Which executor we are dealing with. | [
"Get",
"the",
"sliced",
"shapes",
"for",
"the",
"i",
"-",
"th",
"executor",
"."
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/module/executor_group.py#L666-L682 | train |
apache/incubator-mxnet | example/ssd/train.py | parse_class_names | def parse_class_names(args):
""" parse # classes and class_names if applicable """
num_class = args.num_class
if len(args.class_names) > 0:
if os.path.isfile(args.class_names):
# try to open it to read class names
with open(args.class_names, 'r') as f:
class_n... | python | def parse_class_names(args):
""" parse # classes and class_names if applicable """
num_class = args.num_class
if len(args.class_names) > 0:
if os.path.isfile(args.class_names):
# try to open it to read class names
with open(args.class_names, 'r') as f:
class_n... | [
"def",
"parse_class_names",
"(",
"args",
")",
":",
"num_class",
"=",
"args",
".",
"num_class",
"if",
"len",
"(",
"args",
".",
"class_names",
")",
">",
"0",
":",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"args",
".",
"class_names",
")",
":",
"# try... | parse # classes and class_names if applicable | [
"parse",
"#",
"classes",
"and",
"class_names",
"if",
"applicable"
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/ssd/train.py#L111-L126 | train |
apache/incubator-mxnet | python/mxnet/io/utils.py | _has_instance | def _has_instance(data, dtype):
"""Return True if ``data`` has instance of ``dtype``.
This function is called after _init_data.
``data`` is a list of (str, NDArray)"""
for item in data:
_, arr = item
if isinstance(arr, dtype):
return True
return False | python | def _has_instance(data, dtype):
"""Return True if ``data`` has instance of ``dtype``.
This function is called after _init_data.
``data`` is a list of (str, NDArray)"""
for item in data:
_, arr = item
if isinstance(arr, dtype):
return True
return False | [
"def",
"_has_instance",
"(",
"data",
",",
"dtype",
")",
":",
"for",
"item",
"in",
"data",
":",
"_",
",",
"arr",
"=",
"item",
"if",
"isinstance",
"(",
"arr",
",",
"dtype",
")",
":",
"return",
"True",
"return",
"False"
] | Return True if ``data`` has instance of ``dtype``.
This function is called after _init_data.
``data`` is a list of (str, NDArray) | [
"Return",
"True",
"if",
"data",
"has",
"instance",
"of",
"dtype",
".",
"This",
"function",
"is",
"called",
"after",
"_init_data",
".",
"data",
"is",
"a",
"list",
"of",
"(",
"str",
"NDArray",
")"
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/io/utils.py#L63-L71 | train |
apache/incubator-mxnet | python/mxnet/io/utils.py | _getdata_by_idx | def _getdata_by_idx(data, idx):
"""Shuffle the data."""
shuffle_data = []
for k, v in data:
if (isinstance(v, h5py.Dataset) if h5py else False):
shuffle_data.append((k, v))
elif isinstance(v, CSRNDArray):
shuffle_data.append((k, sparse_array(v.asscipy()[idx], v.conte... | python | def _getdata_by_idx(data, idx):
"""Shuffle the data."""
shuffle_data = []
for k, v in data:
if (isinstance(v, h5py.Dataset) if h5py else False):
shuffle_data.append((k, v))
elif isinstance(v, CSRNDArray):
shuffle_data.append((k, sparse_array(v.asscipy()[idx], v.conte... | [
"def",
"_getdata_by_idx",
"(",
"data",
",",
"idx",
")",
":",
"shuffle_data",
"=",
"[",
"]",
"for",
"k",
",",
"v",
"in",
"data",
":",
"if",
"(",
"isinstance",
"(",
"v",
",",
"h5py",
".",
"Dataset",
")",
"if",
"h5py",
"else",
"False",
")",
":",
"sh... | Shuffle the data. | [
"Shuffle",
"the",
"data",
"."
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/io/utils.py#L74-L86 | train |
apache/incubator-mxnet | python/mxnet/gluon/model_zoo/vision/mobilenet.py | get_mobilenet | def get_mobilenet(multiplier, pretrained=False, ctx=cpu(),
root=os.path.join(base.data_dir(), 'models'), **kwargs):
r"""MobileNet model from the
`"MobileNets: Efficient Convolutional Neural Networks for Mobile Vision Applications"
<https://arxiv.org/abs/1704.04861>`_ paper.
Parameters... | python | def get_mobilenet(multiplier, pretrained=False, ctx=cpu(),
root=os.path.join(base.data_dir(), 'models'), **kwargs):
r"""MobileNet model from the
`"MobileNets: Efficient Convolutional Neural Networks for Mobile Vision Applications"
<https://arxiv.org/abs/1704.04861>`_ paper.
Parameters... | [
"def",
"get_mobilenet",
"(",
"multiplier",
",",
"pretrained",
"=",
"False",
",",
"ctx",
"=",
"cpu",
"(",
")",
",",
"root",
"=",
"os",
".",
"path",
".",
"join",
"(",
"base",
".",
"data_dir",
"(",
")",
",",
"'models'",
")",
",",
"*",
"*",
"kwargs",
... | r"""MobileNet model from the
`"MobileNets: Efficient Convolutional Neural Networks for Mobile Vision Applications"
<https://arxiv.org/abs/1704.04861>`_ paper.
Parameters
----------
multiplier : float
The width multiplier for controling the model size. Only multipliers that are no
le... | [
"r",
"MobileNet",
"model",
"from",
"the",
"MobileNets",
":",
"Efficient",
"Convolutional",
"Neural",
"Networks",
"for",
"Mobile",
"Vision",
"Applications",
"<https",
":",
"//",
"arxiv",
".",
"org",
"/",
"abs",
"/",
"1704",
".",
"04861",
">",
"_",
"paper",
... | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/gluon/model_zoo/vision/mobilenet.py#L191-L219 | train |
apache/incubator-mxnet | python/mxnet/name.py | NameManager.get | def get(self, name, hint):
"""Get the canonical name for a symbol.
This is the default implementation.
If the user specifies a name,
the user-specified name will be used.
When user does not specify a name, we automatically generate a
name based on the hint string.
... | python | def get(self, name, hint):
"""Get the canonical name for a symbol.
This is the default implementation.
If the user specifies a name,
the user-specified name will be used.
When user does not specify a name, we automatically generate a
name based on the hint string.
... | [
"def",
"get",
"(",
"self",
",",
"name",
",",
"hint",
")",
":",
"if",
"name",
":",
"return",
"name",
"if",
"hint",
"not",
"in",
"self",
".",
"_counter",
":",
"self",
".",
"_counter",
"[",
"hint",
"]",
"=",
"0",
"name",
"=",
"'%s%d'",
"%",
"(",
"... | Get the canonical name for a symbol.
This is the default implementation.
If the user specifies a name,
the user-specified name will be used.
When user does not specify a name, we automatically generate a
name based on the hint string.
Parameters
----------
... | [
"Get",
"the",
"canonical",
"name",
"for",
"a",
"symbol",
"."
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/name.py#L36-L65 | train |
apache/incubator-mxnet | example/rnn/large_word_lm/sampler.py | LogUniformSampler.draw | def draw(self, true_classes):
"""Draw samples from log uniform distribution and returns sampled candidates,
expected count for true classes and sampled classes."""
range_max = self.range_max
num_sampled = self.num_sampled
ctx = true_classes.context
log_range = math.log(ra... | python | def draw(self, true_classes):
"""Draw samples from log uniform distribution and returns sampled candidates,
expected count for true classes and sampled classes."""
range_max = self.range_max
num_sampled = self.num_sampled
ctx = true_classes.context
log_range = math.log(ra... | [
"def",
"draw",
"(",
"self",
",",
"true_classes",
")",
":",
"range_max",
"=",
"self",
".",
"range_max",
"num_sampled",
"=",
"self",
".",
"num_sampled",
"ctx",
"=",
"true_classes",
".",
"context",
"log_range",
"=",
"math",
".",
"log",
"(",
"range_max",
"+",
... | Draw samples from log uniform distribution and returns sampled candidates,
expected count for true classes and sampled classes. | [
"Draw",
"samples",
"from",
"log",
"uniform",
"distribution",
"and",
"returns",
"sampled",
"candidates",
"expected",
"count",
"for",
"true",
"classes",
"and",
"sampled",
"classes",
"."
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/rnn/large_word_lm/sampler.py#L36-L55 | train |
apache/incubator-mxnet | example/gluon/dc_gan/inception_score.py | get_inception_score | def get_inception_score(images, splits=10):
"""
Inception_score function.
The images will be divided into 'splits' parts, and calculate each inception_score separately,
then return the mean and std of inception_scores of these parts.
:param images: Images(num x c x w x h) that needs to calcu... | python | def get_inception_score(images, splits=10):
"""
Inception_score function.
The images will be divided into 'splits' parts, and calculate each inception_score separately,
then return the mean and std of inception_scores of these parts.
:param images: Images(num x c x w x h) that needs to calcu... | [
"def",
"get_inception_score",
"(",
"images",
",",
"splits",
"=",
"10",
")",
":",
"assert",
"(",
"images",
".",
"shape",
"[",
"1",
"]",
"==",
"3",
")",
"# load inception model",
"if",
"inception_model",
"is",
"None",
":",
"_init_inception",
"(",
")",
"# res... | Inception_score function.
The images will be divided into 'splits' parts, and calculate each inception_score separately,
then return the mean and std of inception_scores of these parts.
:param images: Images(num x c x w x h) that needs to calculate inception_score.
:param splits:
:return: me... | [
"Inception_score",
"function",
".",
"The",
"images",
"will",
"be",
"divided",
"into",
"splits",
"parts",
"and",
"calculate",
"each",
"inception_score",
"separately",
"then",
"return",
"the",
"mean",
"and",
"std",
"of",
"inception_scores",
"of",
"these",
"parts",
... | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/gluon/dc_gan/inception_score.py#L31-L76 | train |
apache/incubator-mxnet | example/rcnn/symnet/model.py | load_param | def load_param(params, ctx=None):
"""same as mx.model.load_checkpoint, but do not load symnet and will convert context"""
if ctx is None:
ctx = mx.cpu()
save_dict = mx.nd.load(params)
arg_params = {}
aux_params = {}
for k, v in save_dict.items():
tp, name = k.split(':', 1)
... | python | def load_param(params, ctx=None):
"""same as mx.model.load_checkpoint, but do not load symnet and will convert context"""
if ctx is None:
ctx = mx.cpu()
save_dict = mx.nd.load(params)
arg_params = {}
aux_params = {}
for k, v in save_dict.items():
tp, name = k.split(':', 1)
... | [
"def",
"load_param",
"(",
"params",
",",
"ctx",
"=",
"None",
")",
":",
"if",
"ctx",
"is",
"None",
":",
"ctx",
"=",
"mx",
".",
"cpu",
"(",
")",
"save_dict",
"=",
"mx",
".",
"nd",
".",
"load",
"(",
"params",
")",
"arg_params",
"=",
"{",
"}",
"aux... | same as mx.model.load_checkpoint, but do not load symnet and will convert context | [
"same",
"as",
"mx",
".",
"model",
".",
"load_checkpoint",
"but",
"do",
"not",
"load",
"symnet",
"and",
"will",
"convert",
"context"
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/rcnn/symnet/model.py#L21-L34 | train |
apache/incubator-mxnet | python/mxnet/rnn/rnn.py | rnn_unroll | def rnn_unroll(cell, length, inputs=None, begin_state=None, input_prefix='', layout='NTC'):
"""Deprecated. Please use cell.unroll instead"""
warnings.warn('rnn_unroll is deprecated. Please call cell.unroll directly.')
return cell.unroll(length=length, inputs=inputs, begin_state=begin_state,
... | python | def rnn_unroll(cell, length, inputs=None, begin_state=None, input_prefix='', layout='NTC'):
"""Deprecated. Please use cell.unroll instead"""
warnings.warn('rnn_unroll is deprecated. Please call cell.unroll directly.')
return cell.unroll(length=length, inputs=inputs, begin_state=begin_state,
... | [
"def",
"rnn_unroll",
"(",
"cell",
",",
"length",
",",
"inputs",
"=",
"None",
",",
"begin_state",
"=",
"None",
",",
"input_prefix",
"=",
"''",
",",
"layout",
"=",
"'NTC'",
")",
":",
"warnings",
".",
"warn",
"(",
"'rnn_unroll is deprecated. Please call cell.unro... | Deprecated. Please use cell.unroll instead | [
"Deprecated",
".",
"Please",
"use",
"cell",
".",
"unroll",
"instead"
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/rnn/rnn.py#L26-L30 | train |
apache/incubator-mxnet | python/mxnet/rnn/rnn.py | save_rnn_checkpoint | def save_rnn_checkpoint(cells, prefix, epoch, symbol, arg_params, aux_params):
"""Save checkpoint for model using RNN cells.
Unpacks weight before saving.
Parameters
----------
cells : mxnet.rnn.RNNCell or list of RNNCells
The RNN cells used by this symbol.
prefix : str
Prefix o... | python | def save_rnn_checkpoint(cells, prefix, epoch, symbol, arg_params, aux_params):
"""Save checkpoint for model using RNN cells.
Unpacks weight before saving.
Parameters
----------
cells : mxnet.rnn.RNNCell or list of RNNCells
The RNN cells used by this symbol.
prefix : str
Prefix o... | [
"def",
"save_rnn_checkpoint",
"(",
"cells",
",",
"prefix",
",",
"epoch",
",",
"symbol",
",",
"arg_params",
",",
"aux_params",
")",
":",
"if",
"isinstance",
"(",
"cells",
",",
"BaseRNNCell",
")",
":",
"cells",
"=",
"[",
"cells",
"]",
"for",
"cell",
"in",
... | Save checkpoint for model using RNN cells.
Unpacks weight before saving.
Parameters
----------
cells : mxnet.rnn.RNNCell or list of RNNCells
The RNN cells used by this symbol.
prefix : str
Prefix of model name.
epoch : int
The epoch number of the model.
symbol : Symb... | [
"Save",
"checkpoint",
"for",
"model",
"using",
"RNN",
"cells",
".",
"Unpacks",
"weight",
"before",
"saving",
"."
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/rnn/rnn.py#L32-L60 | train |
apache/incubator-mxnet | python/mxnet/rnn/rnn.py | load_rnn_checkpoint | def load_rnn_checkpoint(cells, prefix, epoch):
"""Load model checkpoint from file.
Pack weights after loading.
Parameters
----------
cells : mxnet.rnn.RNNCell or list of RNNCells
The RNN cells used by this symbol.
prefix : str
Prefix of model name.
epoch : int
Epoch ... | python | def load_rnn_checkpoint(cells, prefix, epoch):
"""Load model checkpoint from file.
Pack weights after loading.
Parameters
----------
cells : mxnet.rnn.RNNCell or list of RNNCells
The RNN cells used by this symbol.
prefix : str
Prefix of model name.
epoch : int
Epoch ... | [
"def",
"load_rnn_checkpoint",
"(",
"cells",
",",
"prefix",
",",
"epoch",
")",
":",
"sym",
",",
"arg",
",",
"aux",
"=",
"load_checkpoint",
"(",
"prefix",
",",
"epoch",
")",
"if",
"isinstance",
"(",
"cells",
",",
"BaseRNNCell",
")",
":",
"cells",
"=",
"[... | Load model checkpoint from file.
Pack weights after loading.
Parameters
----------
cells : mxnet.rnn.RNNCell or list of RNNCells
The RNN cells used by this symbol.
prefix : str
Prefix of model name.
epoch : int
Epoch number of model we would like to load.
Returns
... | [
"Load",
"model",
"checkpoint",
"from",
"file",
".",
"Pack",
"weights",
"after",
"loading",
"."
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/rnn/rnn.py#L62-L95 | train |
apache/incubator-mxnet | python/mxnet/rnn/rnn.py | do_rnn_checkpoint | def do_rnn_checkpoint(cells, prefix, period=1):
"""Make a callback to checkpoint Module to prefix every epoch.
unpacks weights used by cells before saving.
Parameters
----------
cells : mxnet.rnn.RNNCell or list of RNNCells
The RNN cells used by this symbol.
prefix : str
The fil... | python | def do_rnn_checkpoint(cells, prefix, period=1):
"""Make a callback to checkpoint Module to prefix every epoch.
unpacks weights used by cells before saving.
Parameters
----------
cells : mxnet.rnn.RNNCell or list of RNNCells
The RNN cells used by this symbol.
prefix : str
The fil... | [
"def",
"do_rnn_checkpoint",
"(",
"cells",
",",
"prefix",
",",
"period",
"=",
"1",
")",
":",
"period",
"=",
"int",
"(",
"max",
"(",
"1",
",",
"period",
")",
")",
"# pylint: disable=unused-argument",
"def",
"_callback",
"(",
"iter_no",
",",
"sym",
"=",
"No... | Make a callback to checkpoint Module to prefix every epoch.
unpacks weights used by cells before saving.
Parameters
----------
cells : mxnet.rnn.RNNCell or list of RNNCells
The RNN cells used by this symbol.
prefix : str
The file prefix to checkpoint to
period : int
How ... | [
"Make",
"a",
"callback",
"to",
"checkpoint",
"Module",
"to",
"prefix",
"every",
"epoch",
".",
"unpacks",
"weights",
"used",
"by",
"cells",
"before",
"saving",
"."
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/rnn/rnn.py#L97-L121 | train |
apache/incubator-mxnet | python/mxnet/gluon/nn/basic_layers.py | Sequential.hybridize | def hybridize(self, active=True, **kwargs):
"""Activates or deactivates `HybridBlock` s recursively. Has no effect on
non-hybrid children.
Parameters
----------
active : bool, default True
Whether to turn hybrid on or off.
**kwargs : string
Additi... | python | def hybridize(self, active=True, **kwargs):
"""Activates or deactivates `HybridBlock` s recursively. Has no effect on
non-hybrid children.
Parameters
----------
active : bool, default True
Whether to turn hybrid on or off.
**kwargs : string
Additi... | [
"def",
"hybridize",
"(",
"self",
",",
"active",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"_children",
"and",
"all",
"(",
"isinstance",
"(",
"c",
",",
"HybridBlock",
")",
"for",
"c",
"in",
"self",
".",
"_children",
".",
"va... | Activates or deactivates `HybridBlock` s recursively. Has no effect on
non-hybrid children.
Parameters
----------
active : bool, default True
Whether to turn hybrid on or off.
**kwargs : string
Additional flags for hybridized operator. | [
"Activates",
"or",
"deactivates",
"HybridBlock",
"s",
"recursively",
".",
"Has",
"no",
"effect",
"on",
"non",
"-",
"hybrid",
"children",
"."
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/gluon/nn/basic_layers.py#L77-L92 | train |
apache/incubator-mxnet | example/ctc/lstm_ocr_infer.py | read_img | def read_img(path):
""" Reads image specified by path into numpy.ndarray"""
img = cv2.resize(cv2.imread(path, 0), (80, 30)).astype(np.float32) / 255
img = np.expand_dims(img.transpose(1, 0), 0)
return img | python | def read_img(path):
""" Reads image specified by path into numpy.ndarray"""
img = cv2.resize(cv2.imread(path, 0), (80, 30)).astype(np.float32) / 255
img = np.expand_dims(img.transpose(1, 0), 0)
return img | [
"def",
"read_img",
"(",
"path",
")",
":",
"img",
"=",
"cv2",
".",
"resize",
"(",
"cv2",
".",
"imread",
"(",
"path",
",",
"0",
")",
",",
"(",
"80",
",",
"30",
")",
")",
".",
"astype",
"(",
"np",
".",
"float32",
")",
"/",
"255",
"img",
"=",
"... | Reads image specified by path into numpy.ndarray | [
"Reads",
"image",
"specified",
"by",
"path",
"into",
"numpy",
".",
"ndarray"
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/ctc/lstm_ocr_infer.py#L32-L36 | train |
apache/incubator-mxnet | example/ctc/lstm_ocr_infer.py | lstm_init_states | def lstm_init_states(batch_size):
""" Returns a tuple of names and zero arrays for LSTM init states"""
hp = Hyperparams()
init_shapes = lstm.init_states(batch_size=batch_size, num_lstm_layer=hp.num_lstm_layer, num_hidden=hp.num_hidden)
init_names = [s[0] for s in init_shapes]
init_arrays = [mx.nd.ze... | python | def lstm_init_states(batch_size):
""" Returns a tuple of names and zero arrays for LSTM init states"""
hp = Hyperparams()
init_shapes = lstm.init_states(batch_size=batch_size, num_lstm_layer=hp.num_lstm_layer, num_hidden=hp.num_hidden)
init_names = [s[0] for s in init_shapes]
init_arrays = [mx.nd.ze... | [
"def",
"lstm_init_states",
"(",
"batch_size",
")",
":",
"hp",
"=",
"Hyperparams",
"(",
")",
"init_shapes",
"=",
"lstm",
".",
"init_states",
"(",
"batch_size",
"=",
"batch_size",
",",
"num_lstm_layer",
"=",
"hp",
".",
"num_lstm_layer",
",",
"num_hidden",
"=",
... | Returns a tuple of names and zero arrays for LSTM init states | [
"Returns",
"a",
"tuple",
"of",
"names",
"and",
"zero",
"arrays",
"for",
"LSTM",
"init",
"states"
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/ctc/lstm_ocr_infer.py#L39-L45 | train |
apache/incubator-mxnet | example/ctc/lstm_ocr_infer.py | load_module | def load_module(prefix, epoch, data_names, data_shapes):
"""Loads the model from checkpoint specified by prefix and epoch, binds it
to an executor, and sets its parameters and returns a mx.mod.Module
"""
sym, arg_params, aux_params = mx.model.load_checkpoint(prefix, epoch)
# We don't need CTC loss ... | python | def load_module(prefix, epoch, data_names, data_shapes):
"""Loads the model from checkpoint specified by prefix and epoch, binds it
to an executor, and sets its parameters and returns a mx.mod.Module
"""
sym, arg_params, aux_params = mx.model.load_checkpoint(prefix, epoch)
# We don't need CTC loss ... | [
"def",
"load_module",
"(",
"prefix",
",",
"epoch",
",",
"data_names",
",",
"data_shapes",
")",
":",
"sym",
",",
"arg_params",
",",
"aux_params",
"=",
"mx",
".",
"model",
".",
"load_checkpoint",
"(",
"prefix",
",",
"epoch",
")",
"# We don't need CTC loss for pr... | Loads the model from checkpoint specified by prefix and epoch, binds it
to an executor, and sets its parameters and returns a mx.mod.Module | [
"Loads",
"the",
"model",
"from",
"checkpoint",
"specified",
"by",
"prefix",
"and",
"epoch",
"binds",
"it",
"to",
"an",
"executor",
"and",
"sets",
"its",
"parameters",
"and",
"returns",
"a",
"mx",
".",
"mod",
".",
"Module"
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/ctc/lstm_ocr_infer.py#L48-L62 | train |
apache/incubator-mxnet | example/ctc/lstm_ocr_infer.py | main | def main():
"""Program entry point"""
parser = argparse.ArgumentParser()
parser.add_argument("path", help="Path to the CAPTCHA image file")
parser.add_argument("--prefix", help="Checkpoint prefix [Default 'ocr']", default='ocr')
parser.add_argument("--epoch", help="Checkpoint epoch [Default 100]", t... | python | def main():
"""Program entry point"""
parser = argparse.ArgumentParser()
parser.add_argument("path", help="Path to the CAPTCHA image file")
parser.add_argument("--prefix", help="Checkpoint prefix [Default 'ocr']", default='ocr')
parser.add_argument("--epoch", help="Checkpoint epoch [Default 100]", t... | [
"def",
"main",
"(",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
")",
"parser",
".",
"add_argument",
"(",
"\"path\"",
",",
"help",
"=",
"\"Path to the CAPTCHA image file\"",
")",
"parser",
".",
"add_argument",
"(",
"\"--prefix\"",
",",
"hel... | Program entry point | [
"Program",
"entry",
"point"
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/ctc/lstm_ocr_infer.py#L65-L88 | train |
apache/incubator-mxnet | example/rcnn/symdata/bbox.py | bbox_flip | def bbox_flip(bbox, width, flip_x=False):
"""
invalid value in bbox_transform if this wrong (no overlap), note index 0 and 2
also note need to save before assignment
:param bbox: [n][x1, y1, x2, y2]
:param width: cv2 (height, width, channel)
:param flip_x: will flip x1 and x2
:return: flippe... | python | def bbox_flip(bbox, width, flip_x=False):
"""
invalid value in bbox_transform if this wrong (no overlap), note index 0 and 2
also note need to save before assignment
:param bbox: [n][x1, y1, x2, y2]
:param width: cv2 (height, width, channel)
:param flip_x: will flip x1 and x2
:return: flippe... | [
"def",
"bbox_flip",
"(",
"bbox",
",",
"width",
",",
"flip_x",
"=",
"False",
")",
":",
"if",
"flip_x",
":",
"xmax",
"=",
"width",
"-",
"bbox",
"[",
":",
",",
"0",
"]",
"xmin",
"=",
"width",
"-",
"bbox",
"[",
":",
",",
"2",
"]",
"bbox",
"[",
":... | invalid value in bbox_transform if this wrong (no overlap), note index 0 and 2
also note need to save before assignment
:param bbox: [n][x1, y1, x2, y2]
:param width: cv2 (height, width, channel)
:param flip_x: will flip x1 and x2
:return: flipped box | [
"invalid",
"value",
"in",
"bbox_transform",
"if",
"this",
"wrong",
"(",
"no",
"overlap",
")",
"note",
"index",
"0",
"and",
"2",
"also",
"note",
"need",
"to",
"save",
"before",
"assignment",
":",
"param",
"bbox",
":",
"[",
"n",
"]",
"[",
"x1",
"y1",
"... | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/rcnn/symdata/bbox.py#L21-L35 | train |
apache/incubator-mxnet | example/rcnn/symdata/bbox.py | bbox_overlaps | def bbox_overlaps(boxes, query_boxes):
"""
determine overlaps between boxes and query_boxes
:param boxes: n * 4 bounding boxes
:param query_boxes: k * 4 bounding boxes
:return: overlaps: n * k overlaps
"""
n_ = boxes.shape[0]
k_ = query_boxes.shape[0]
overlaps = np.zeros((n_, k_), dt... | python | def bbox_overlaps(boxes, query_boxes):
"""
determine overlaps between boxes and query_boxes
:param boxes: n * 4 bounding boxes
:param query_boxes: k * 4 bounding boxes
:return: overlaps: n * k overlaps
"""
n_ = boxes.shape[0]
k_ = query_boxes.shape[0]
overlaps = np.zeros((n_, k_), dt... | [
"def",
"bbox_overlaps",
"(",
"boxes",
",",
"query_boxes",
")",
":",
"n_",
"=",
"boxes",
".",
"shape",
"[",
"0",
"]",
"k_",
"=",
"query_boxes",
".",
"shape",
"[",
"0",
"]",
"overlaps",
"=",
"np",
".",
"zeros",
"(",
"(",
"n_",
",",
"k_",
")",
",",
... | determine overlaps between boxes and query_boxes
:param boxes: n * 4 bounding boxes
:param query_boxes: k * 4 bounding boxes
:return: overlaps: n * k overlaps | [
"determine",
"overlaps",
"between",
"boxes",
"and",
"query_boxes",
":",
"param",
"boxes",
":",
"n",
"*",
"4",
"bounding",
"boxes",
":",
"param",
"query_boxes",
":",
"k",
"*",
"4",
"bounding",
"boxes",
":",
"return",
":",
"overlaps",
":",
"n",
"*",
"k",
... | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/rcnn/symdata/bbox.py#L38-L58 | train |
apache/incubator-mxnet | example/rcnn/symdata/bbox.py | clip_boxes | def clip_boxes(boxes, im_shape):
"""
Clip boxes to image boundaries.
:param boxes: [N, 4* num_classes]
:param im_shape: tuple of 2
:return: [N, 4* num_classes]
"""
# x1 >= 0
boxes[:, 0::4] = np.maximum(np.minimum(boxes[:, 0::4], im_shape[1] - 1), 0)
# y1 >= 0
boxes[:, 1::4] = np.... | python | def clip_boxes(boxes, im_shape):
"""
Clip boxes to image boundaries.
:param boxes: [N, 4* num_classes]
:param im_shape: tuple of 2
:return: [N, 4* num_classes]
"""
# x1 >= 0
boxes[:, 0::4] = np.maximum(np.minimum(boxes[:, 0::4], im_shape[1] - 1), 0)
# y1 >= 0
boxes[:, 1::4] = np.... | [
"def",
"clip_boxes",
"(",
"boxes",
",",
"im_shape",
")",
":",
"# x1 >= 0",
"boxes",
"[",
":",
",",
"0",
":",
":",
"4",
"]",
"=",
"np",
".",
"maximum",
"(",
"np",
".",
"minimum",
"(",
"boxes",
"[",
":",
",",
"0",
":",
":",
"4",
"]",
",",
"im_s... | Clip boxes to image boundaries.
:param boxes: [N, 4* num_classes]
:param im_shape: tuple of 2
:return: [N, 4* num_classes] | [
"Clip",
"boxes",
"to",
"image",
"boundaries",
".",
":",
"param",
"boxes",
":",
"[",
"N",
"4",
"*",
"num_classes",
"]",
":",
"param",
"im_shape",
":",
"tuple",
"of",
"2",
":",
"return",
":",
"[",
"N",
"4",
"*",
"num_classes",
"]"
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/rcnn/symdata/bbox.py#L61-L76 | train |
apache/incubator-mxnet | example/rcnn/symdata/bbox.py | bbox_transform | def bbox_transform(ex_rois, gt_rois, box_stds):
"""
compute bounding box regression targets from ex_rois to gt_rois
:param ex_rois: [N, 4]
:param gt_rois: [N, 4]
:return: [N, 4]
"""
assert ex_rois.shape[0] == gt_rois.shape[0], 'inconsistent rois number'
ex_widths = ex_rois[:, 2] - ex_ro... | python | def bbox_transform(ex_rois, gt_rois, box_stds):
"""
compute bounding box regression targets from ex_rois to gt_rois
:param ex_rois: [N, 4]
:param gt_rois: [N, 4]
:return: [N, 4]
"""
assert ex_rois.shape[0] == gt_rois.shape[0], 'inconsistent rois number'
ex_widths = ex_rois[:, 2] - ex_ro... | [
"def",
"bbox_transform",
"(",
"ex_rois",
",",
"gt_rois",
",",
"box_stds",
")",
":",
"assert",
"ex_rois",
".",
"shape",
"[",
"0",
"]",
"==",
"gt_rois",
".",
"shape",
"[",
"0",
"]",
",",
"'inconsistent rois number'",
"ex_widths",
"=",
"ex_rois",
"[",
":",
... | compute bounding box regression targets from ex_rois to gt_rois
:param ex_rois: [N, 4]
:param gt_rois: [N, 4]
:return: [N, 4] | [
"compute",
"bounding",
"box",
"regression",
"targets",
"from",
"ex_rois",
"to",
"gt_rois",
":",
"param",
"ex_rois",
":",
"[",
"N",
"4",
"]",
":",
"param",
"gt_rois",
":",
"[",
"N",
"4",
"]",
":",
"return",
":",
"[",
"N",
"4",
"]"
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/rcnn/symdata/bbox.py#L79-L104 | train |
apache/incubator-mxnet | example/rcnn/symdata/bbox.py | bbox_pred | def bbox_pred(boxes, box_deltas, box_stds):
"""
Transform the set of class-agnostic boxes into class-specific boxes
by applying the predicted offsets (box_deltas)
:param boxes: !important [N 4]
:param box_deltas: [N, 4 * num_classes]
:return: [N 4 * num_classes]
"""
if boxes.shape[0] == ... | python | def bbox_pred(boxes, box_deltas, box_stds):
"""
Transform the set of class-agnostic boxes into class-specific boxes
by applying the predicted offsets (box_deltas)
:param boxes: !important [N 4]
:param box_deltas: [N, 4 * num_classes]
:return: [N 4 * num_classes]
"""
if boxes.shape[0] == ... | [
"def",
"bbox_pred",
"(",
"boxes",
",",
"box_deltas",
",",
"box_stds",
")",
":",
"if",
"boxes",
".",
"shape",
"[",
"0",
"]",
"==",
"0",
":",
"return",
"np",
".",
"zeros",
"(",
"(",
"0",
",",
"box_deltas",
".",
"shape",
"[",
"1",
"]",
")",
")",
"... | Transform the set of class-agnostic boxes into class-specific boxes
by applying the predicted offsets (box_deltas)
:param boxes: !important [N 4]
:param box_deltas: [N, 4 * num_classes]
:return: [N 4 * num_classes] | [
"Transform",
"the",
"set",
"of",
"class",
"-",
"agnostic",
"boxes",
"into",
"class",
"-",
"specific",
"boxes",
"by",
"applying",
"the",
"predicted",
"offsets",
"(",
"box_deltas",
")",
":",
"param",
"boxes",
":",
"!important",
"[",
"N",
"4",
"]",
":",
"pa... | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/rcnn/symdata/bbox.py#L107-L143 | train |
apache/incubator-mxnet | example/rcnn/symdata/bbox.py | nms | def nms(dets, thresh):
"""
greedily select boxes with high confidence and overlap with current maximum <= thresh
rule out overlap >= thresh
:param dets: [[x1, y1, x2, y2 score]]
:param thresh: retain overlap < thresh
:return: indexes to keep
"""
x1 = dets[:, 0]
y1 = dets[:, 1]
x2... | python | def nms(dets, thresh):
"""
greedily select boxes with high confidence and overlap with current maximum <= thresh
rule out overlap >= thresh
:param dets: [[x1, y1, x2, y2 score]]
:param thresh: retain overlap < thresh
:return: indexes to keep
"""
x1 = dets[:, 0]
y1 = dets[:, 1]
x2... | [
"def",
"nms",
"(",
"dets",
",",
"thresh",
")",
":",
"x1",
"=",
"dets",
"[",
":",
",",
"0",
"]",
"y1",
"=",
"dets",
"[",
":",
",",
"1",
"]",
"x2",
"=",
"dets",
"[",
":",
",",
"2",
"]",
"y2",
"=",
"dets",
"[",
":",
",",
"3",
"]",
"scores"... | greedily select boxes with high confidence and overlap with current maximum <= thresh
rule out overlap >= thresh
:param dets: [[x1, y1, x2, y2 score]]
:param thresh: retain overlap < thresh
:return: indexes to keep | [
"greedily",
"select",
"boxes",
"with",
"high",
"confidence",
"and",
"overlap",
"with",
"current",
"maximum",
"<",
"=",
"thresh",
"rule",
"out",
"overlap",
">",
"=",
"thresh",
":",
"param",
"dets",
":",
"[[",
"x1",
"y1",
"x2",
"y2",
"score",
"]]",
":",
... | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/rcnn/symdata/bbox.py#L146-L180 | train |
apache/incubator-mxnet | example/rcnn/symdata/bbox.py | im_detect | def im_detect(rois, scores, bbox_deltas, im_info,
bbox_stds, nms_thresh, conf_thresh):
"""rois (nroi, 4), scores (nrois, nclasses), bbox_deltas (nrois, 4 * nclasses), im_info (3)"""
rois = rois.asnumpy()
scores = scores.asnumpy()
bbox_deltas = bbox_deltas.asnumpy()
im_info = im_info.a... | python | def im_detect(rois, scores, bbox_deltas, im_info,
bbox_stds, nms_thresh, conf_thresh):
"""rois (nroi, 4), scores (nrois, nclasses), bbox_deltas (nrois, 4 * nclasses), im_info (3)"""
rois = rois.asnumpy()
scores = scores.asnumpy()
bbox_deltas = bbox_deltas.asnumpy()
im_info = im_info.a... | [
"def",
"im_detect",
"(",
"rois",
",",
"scores",
",",
"bbox_deltas",
",",
"im_info",
",",
"bbox_stds",
",",
"nms_thresh",
",",
"conf_thresh",
")",
":",
"rois",
"=",
"rois",
".",
"asnumpy",
"(",
")",
"scores",
"=",
"scores",
".",
"asnumpy",
"(",
")",
"bb... | rois (nroi, 4), scores (nrois, nclasses), bbox_deltas (nrois, 4 * nclasses), im_info (3) | [
"rois",
"(",
"nroi",
"4",
")",
"scores",
"(",
"nrois",
"nclasses",
")",
"bbox_deltas",
"(",
"nrois",
"4",
"*",
"nclasses",
")",
"im_info",
"(",
"3",
")"
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/rcnn/symdata/bbox.py#L183-L214 | train |
apache/incubator-mxnet | amalgamation/python/mxnet_predict.py | c_str | def c_str(string):
""""Convert a python string to C string."""
if not isinstance(string, str):
string = string.decode('ascii')
return ctypes.c_char_p(string.encode('utf-8')) | python | def c_str(string):
""""Convert a python string to C string."""
if not isinstance(string, str):
string = string.decode('ascii')
return ctypes.c_char_p(string.encode('utf-8')) | [
"def",
"c_str",
"(",
"string",
")",
":",
"if",
"not",
"isinstance",
"(",
"string",
",",
"str",
")",
":",
"string",
"=",
"string",
".",
"decode",
"(",
"'ascii'",
")",
"return",
"ctypes",
".",
"c_char_p",
"(",
"string",
".",
"encode",
"(",
"'utf-8'",
"... | Convert a python string to C string. | [
"Convert",
"a",
"python",
"string",
"to",
"C",
"string",
"."
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/amalgamation/python/mxnet_predict.py#L40-L44 | train |
apache/incubator-mxnet | amalgamation/python/mxnet_predict.py | _find_lib_path | def _find_lib_path():
"""Find mxnet library."""
curr_path = os.path.dirname(os.path.abspath(os.path.expanduser(__file__)))
amalgamation_lib_path = os.path.join(curr_path, '../../lib/libmxnet_predict.so')
if os.path.exists(amalgamation_lib_path) and os.path.isfile(amalgamation_lib_path):
lib_path... | python | def _find_lib_path():
"""Find mxnet library."""
curr_path = os.path.dirname(os.path.abspath(os.path.expanduser(__file__)))
amalgamation_lib_path = os.path.join(curr_path, '../../lib/libmxnet_predict.so')
if os.path.exists(amalgamation_lib_path) and os.path.isfile(amalgamation_lib_path):
lib_path... | [
"def",
"_find_lib_path",
"(",
")",
":",
"curr_path",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"os",
".",
"path",
".",
"abspath",
"(",
"os",
".",
"path",
".",
"expanduser",
"(",
"__file__",
")",
")",
")",
"amalgamation_lib_path",
"=",
"os",
".",
"... | Find mxnet library. | [
"Find",
"mxnet",
"library",
"."
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/amalgamation/python/mxnet_predict.py#L52-L73 | train |
apache/incubator-mxnet | amalgamation/python/mxnet_predict.py | _load_lib | def _load_lib():
"""Load libary by searching possible path."""
lib_path = _find_lib_path()
lib = ctypes.cdll.LoadLibrary(lib_path[0])
# DMatrix functions
lib.MXGetLastError.restype = ctypes.c_char_p
return lib | python | def _load_lib():
"""Load libary by searching possible path."""
lib_path = _find_lib_path()
lib = ctypes.cdll.LoadLibrary(lib_path[0])
# DMatrix functions
lib.MXGetLastError.restype = ctypes.c_char_p
return lib | [
"def",
"_load_lib",
"(",
")",
":",
"lib_path",
"=",
"_find_lib_path",
"(",
")",
"lib",
"=",
"ctypes",
".",
"cdll",
".",
"LoadLibrary",
"(",
"lib_path",
"[",
"0",
"]",
")",
"# DMatrix functions",
"lib",
".",
"MXGetLastError",
".",
"restype",
"=",
"ctypes",
... | Load libary by searching possible path. | [
"Load",
"libary",
"by",
"searching",
"possible",
"path",
"."
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/amalgamation/python/mxnet_predict.py#L76-L82 | train |
apache/incubator-mxnet | amalgamation/python/mxnet_predict.py | load_ndarray_file | def load_ndarray_file(nd_bytes):
"""Load ndarray file and return as list of numpy array.
Parameters
----------
nd_bytes : str or bytes
The internal ndarray bytes
Returns
-------
out : dict of str to numpy array or list of numpy array
The output list or dict, depending on wh... | python | def load_ndarray_file(nd_bytes):
"""Load ndarray file and return as list of numpy array.
Parameters
----------
nd_bytes : str or bytes
The internal ndarray bytes
Returns
-------
out : dict of str to numpy array or list of numpy array
The output list or dict, depending on wh... | [
"def",
"load_ndarray_file",
"(",
"nd_bytes",
")",
":",
"handle",
"=",
"NDListHandle",
"(",
")",
"olen",
"=",
"mx_uint",
"(",
")",
"nd_bytes",
"=",
"bytearray",
"(",
"nd_bytes",
")",
"ptr",
"=",
"(",
"ctypes",
".",
"c_char",
"*",
"len",
"(",
"nd_bytes",
... | Load ndarray file and return as list of numpy array.
Parameters
----------
nd_bytes : str or bytes
The internal ndarray bytes
Returns
-------
out : dict of str to numpy array or list of numpy array
The output list or dict, depending on whether the saved type is list or dict. | [
"Load",
"ndarray",
"file",
"and",
"return",
"as",
"list",
"of",
"numpy",
"array",
"."
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/amalgamation/python/mxnet_predict.py#L234-L276 | train |
apache/incubator-mxnet | amalgamation/python/mxnet_predict.py | Predictor.forward | def forward(self, **kwargs):
"""Perform forward to get the output.
Parameters
----------
**kwargs
Keyword arguments of input variable name to data.
Examples
--------
>>> predictor.forward(data=mydata)
>>> out = predictor.get_output(0)
... | python | def forward(self, **kwargs):
"""Perform forward to get the output.
Parameters
----------
**kwargs
Keyword arguments of input variable name to data.
Examples
--------
>>> predictor.forward(data=mydata)
>>> out = predictor.get_output(0)
... | [
"def",
"forward",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"k",
",",
"v",
"in",
"kwargs",
".",
"items",
"(",
")",
":",
"if",
"not",
"isinstance",
"(",
"v",
",",
"np",
".",
"ndarray",
")",
":",
"raise",
"ValueError",
"(",
"\"Expect n... | Perform forward to get the output.
Parameters
----------
**kwargs
Keyword arguments of input variable name to data.
Examples
--------
>>> predictor.forward(data=mydata)
>>> out = predictor.get_output(0) | [
"Perform",
"forward",
"to",
"get",
"the",
"output",
"."
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/amalgamation/python/mxnet_predict.py#L150-L171 | train |
apache/incubator-mxnet | amalgamation/python/mxnet_predict.py | Predictor.reshape | def reshape(self, input_shapes):
"""Change the input shape of the predictor.
Parameters
----------
input_shapes : dict of str to tuple
The new shape of input data.
Examples
--------
>>> predictor.reshape({'data':data_shape_tuple})
"""
... | python | def reshape(self, input_shapes):
"""Change the input shape of the predictor.
Parameters
----------
input_shapes : dict of str to tuple
The new shape of input data.
Examples
--------
>>> predictor.reshape({'data':data_shape_tuple})
"""
... | [
"def",
"reshape",
"(",
"self",
",",
"input_shapes",
")",
":",
"indptr",
"=",
"[",
"0",
"]",
"sdata",
"=",
"[",
"]",
"keys",
"=",
"[",
"]",
"for",
"k",
",",
"v",
"in",
"input_shapes",
".",
"items",
"(",
")",
":",
"if",
"not",
"isinstance",
"(",
... | Change the input shape of the predictor.
Parameters
----------
input_shapes : dict of str to tuple
The new shape of input data.
Examples
--------
>>> predictor.reshape({'data':data_shape_tuple}) | [
"Change",
"the",
"input",
"shape",
"of",
"the",
"predictor",
"."
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/amalgamation/python/mxnet_predict.py#L173-L204 | train |
apache/incubator-mxnet | amalgamation/python/mxnet_predict.py | Predictor.get_output | def get_output(self, index):
"""Get the index-th output.
Parameters
----------
index : int
The index of output.
Returns
-------
out : numpy array.
The output array.
"""
pdata = ctypes.POINTER(mx_uint)()
ndim = mx_u... | python | def get_output(self, index):
"""Get the index-th output.
Parameters
----------
index : int
The index of output.
Returns
-------
out : numpy array.
The output array.
"""
pdata = ctypes.POINTER(mx_uint)()
ndim = mx_u... | [
"def",
"get_output",
"(",
"self",
",",
"index",
")",
":",
"pdata",
"=",
"ctypes",
".",
"POINTER",
"(",
"mx_uint",
")",
"(",
")",
"ndim",
"=",
"mx_uint",
"(",
")",
"_check_call",
"(",
"_LIB",
".",
"MXPredGetOutputShape",
"(",
"self",
".",
"handle",
",",... | Get the index-th output.
Parameters
----------
index : int
The index of output.
Returns
-------
out : numpy array.
The output array. | [
"Get",
"the",
"index",
"-",
"th",
"output",
"."
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/amalgamation/python/mxnet_predict.py#L206-L231 | train |
apache/incubator-mxnet | example/reinforcement-learning/dqn/atari_game.py | AtariGame.begin_episode | def begin_episode(self, max_episode_step=DEFAULT_MAX_EPISODE_STEP):
"""
Begin an episode of a game instance. We can play the game for a maximum of
`max_episode_step` and after that, we are forced to restart
"""
if self.episode_step > self.max_episode_step or self.ale.game... | python | def begin_episode(self, max_episode_step=DEFAULT_MAX_EPISODE_STEP):
"""
Begin an episode of a game instance. We can play the game for a maximum of
`max_episode_step` and after that, we are forced to restart
"""
if self.episode_step > self.max_episode_step or self.ale.game... | [
"def",
"begin_episode",
"(",
"self",
",",
"max_episode_step",
"=",
"DEFAULT_MAX_EPISODE_STEP",
")",
":",
"if",
"self",
".",
"episode_step",
">",
"self",
".",
"max_episode_step",
"or",
"self",
".",
"ale",
".",
"game_over",
"(",
")",
":",
"self",
".",
"start",... | Begin an episode of a game instance. We can play the game for a maximum of
`max_episode_step` and after that, we are forced to restart | [
"Begin",
"an",
"episode",
"of",
"a",
"game",
"instance",
".",
"We",
"can",
"play",
"the",
"game",
"for",
"a",
"maximum",
"of",
"max_episode_step",
"and",
"after",
"that",
"we",
"are",
"forced",
"to",
"restart"
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/reinforcement-learning/dqn/atari_game.py#L112-L126 | train |
apache/incubator-mxnet | python/mxnet/gluon/rnn/rnn_cell.py | RecurrentCell.reset | def reset(self):
"""Reset before re-using the cell for another graph."""
self._init_counter = -1
self._counter = -1
for cell in self._children.values():
cell.reset() | python | def reset(self):
"""Reset before re-using the cell for another graph."""
self._init_counter = -1
self._counter = -1
for cell in self._children.values():
cell.reset() | [
"def",
"reset",
"(",
"self",
")",
":",
"self",
".",
"_init_counter",
"=",
"-",
"1",
"self",
".",
"_counter",
"=",
"-",
"1",
"for",
"cell",
"in",
"self",
".",
"_children",
".",
"values",
"(",
")",
":",
"cell",
".",
"reset",
"(",
")"
] | Reset before re-using the cell for another graph. | [
"Reset",
"before",
"re",
"-",
"using",
"the",
"cell",
"for",
"another",
"graph",
"."
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/gluon/rnn/rnn_cell.py#L140-L145 | train |
apache/incubator-mxnet | python/mxnet/gluon/rnn/rnn_cell.py | RecurrentCell.begin_state | def begin_state(self, batch_size=0, func=ndarray.zeros, **kwargs):
"""Initial state for this cell.
Parameters
----------
func : callable, default symbol.zeros
Function for creating initial state.
For Symbol API, func can be `symbol.zeros`, `symbol.uniform`,
... | python | def begin_state(self, batch_size=0, func=ndarray.zeros, **kwargs):
"""Initial state for this cell.
Parameters
----------
func : callable, default symbol.zeros
Function for creating initial state.
For Symbol API, func can be `symbol.zeros`, `symbol.uniform`,
... | [
"def",
"begin_state",
"(",
"self",
",",
"batch_size",
"=",
"0",
",",
"func",
"=",
"ndarray",
".",
"zeros",
",",
"*",
"*",
"kwargs",
")",
":",
"assert",
"not",
"self",
".",
"_modified",
",",
"\"After applying modifier cells (e.g. ZoneoutCell) the base \"",
"\"cel... | Initial state for this cell.
Parameters
----------
func : callable, default symbol.zeros
Function for creating initial state.
For Symbol API, func can be `symbol.zeros`, `symbol.uniform`,
`symbol.var etc`. Use `symbol.var` if you want to directly
... | [
"Initial",
"state",
"for",
"this",
"cell",
"."
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/gluon/rnn/rnn_cell.py#L151-L190 | train |
apache/incubator-mxnet | python/mxnet/gluon/rnn/rnn_cell.py | RecurrentCell.unroll | def unroll(self, length, inputs, begin_state=None, layout='NTC', merge_outputs=None,
valid_length=None):
"""Unrolls an RNN cell across time steps.
Parameters
----------
length : int
Number of steps to unroll.
inputs : Symbol, list of Symbol, or None
... | python | def unroll(self, length, inputs, begin_state=None, layout='NTC', merge_outputs=None,
valid_length=None):
"""Unrolls an RNN cell across time steps.
Parameters
----------
length : int
Number of steps to unroll.
inputs : Symbol, list of Symbol, or None
... | [
"def",
"unroll",
"(",
"self",
",",
"length",
",",
"inputs",
",",
"begin_state",
"=",
"None",
",",
"layout",
"=",
"'NTC'",
",",
"merge_outputs",
"=",
"None",
",",
"valid_length",
"=",
"None",
")",
":",
"# pylint: disable=too-many-locals",
"self",
".",
"reset"... | Unrolls an RNN cell across time steps.
Parameters
----------
length : int
Number of steps to unroll.
inputs : Symbol, list of Symbol, or None
If `inputs` is a single Symbol (usually the output
of Embedding symbol), it should have shape
(ba... | [
"Unrolls",
"an",
"RNN",
"cell",
"across",
"time",
"steps",
"."
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/gluon/rnn/rnn_cell.py#L192-L267 | train |
apache/incubator-mxnet | python/mxnet/gluon/rnn/rnn_cell.py | RecurrentCell._get_activation | def _get_activation(self, F, inputs, activation, **kwargs):
"""Get activation function. Convert if is string"""
func = {'tanh': F.tanh,
'relu': F.relu,
'sigmoid': F.sigmoid,
'softsign': F.softsign}.get(activation)
if func:
return func(i... | python | def _get_activation(self, F, inputs, activation, **kwargs):
"""Get activation function. Convert if is string"""
func = {'tanh': F.tanh,
'relu': F.relu,
'sigmoid': F.sigmoid,
'softsign': F.softsign}.get(activation)
if func:
return func(i... | [
"def",
"_get_activation",
"(",
"self",
",",
"F",
",",
"inputs",
",",
"activation",
",",
"*",
"*",
"kwargs",
")",
":",
"func",
"=",
"{",
"'tanh'",
":",
"F",
".",
"tanh",
",",
"'relu'",
":",
"F",
".",
"relu",
",",
"'sigmoid'",
":",
"F",
".",
"sigmo... | Get activation function. Convert if is string | [
"Get",
"activation",
"function",
".",
"Convert",
"if",
"is",
"string"
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/gluon/rnn/rnn_cell.py#L270-L282 | train |
apache/incubator-mxnet | python/mxnet/gluon/rnn/rnn_cell.py | RecurrentCell.forward | def forward(self, inputs, states):
"""Unrolls the recurrent cell for one time step.
Parameters
----------
inputs : sym.Variable
Input symbol, 2D, of shape (batch_size * num_units).
states : list of sym.Variable
RNN state from previous step or the output o... | python | def forward(self, inputs, states):
"""Unrolls the recurrent cell for one time step.
Parameters
----------
inputs : sym.Variable
Input symbol, 2D, of shape (batch_size * num_units).
states : list of sym.Variable
RNN state from previous step or the output o... | [
"def",
"forward",
"(",
"self",
",",
"inputs",
",",
"states",
")",
":",
"# pylint: disable= arguments-differ",
"self",
".",
"_counter",
"+=",
"1",
"return",
"super",
"(",
"RecurrentCell",
",",
"self",
")",
".",
"forward",
"(",
"inputs",
",",
"states",
")"
] | Unrolls the recurrent cell for one time step.
Parameters
----------
inputs : sym.Variable
Input symbol, 2D, of shape (batch_size * num_units).
states : list of sym.Variable
RNN state from previous step or the output of begin_state().
Returns
----... | [
"Unrolls",
"the",
"recurrent",
"cell",
"for",
"one",
"time",
"step",
"."
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/gluon/rnn/rnn_cell.py#L284-L312 | train |
apache/incubator-mxnet | python/mxnet/module/base_module.py | _check_input_names | def _check_input_names(symbol, names, typename, throw):
"""Check that all input names are in symbol's arguments."""
args = symbol.list_arguments()
for name in names:
if name in args:
continue
candidates = [arg for arg in args if
not arg.endswith('_weight') a... | python | def _check_input_names(symbol, names, typename, throw):
"""Check that all input names are in symbol's arguments."""
args = symbol.list_arguments()
for name in names:
if name in args:
continue
candidates = [arg for arg in args if
not arg.endswith('_weight') a... | [
"def",
"_check_input_names",
"(",
"symbol",
",",
"names",
",",
"typename",
",",
"throw",
")",
":",
"args",
"=",
"symbol",
".",
"list_arguments",
"(",
")",
"for",
"name",
"in",
"names",
":",
"if",
"name",
"in",
"args",
":",
"continue",
"candidates",
"=",
... | Check that all input names are in symbol's arguments. | [
"Check",
"that",
"all",
"input",
"names",
"are",
"in",
"symbol",
"s",
"arguments",
"."
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/module/base_module.py#L37-L55 | train |
apache/incubator-mxnet | python/mxnet/module/base_module.py | _check_names_match | def _check_names_match(data_names, data_shapes, name, throw):
"""Check that input names matches input data descriptors."""
actual = [x[0] for x in data_shapes]
if sorted(data_names) != sorted(actual):
msg = "Data provided by %s_shapes don't match names specified by %s_names (%s vs. %s)"%(
... | python | def _check_names_match(data_names, data_shapes, name, throw):
"""Check that input names matches input data descriptors."""
actual = [x[0] for x in data_shapes]
if sorted(data_names) != sorted(actual):
msg = "Data provided by %s_shapes don't match names specified by %s_names (%s vs. %s)"%(
... | [
"def",
"_check_names_match",
"(",
"data_names",
",",
"data_shapes",
",",
"name",
",",
"throw",
")",
":",
"actual",
"=",
"[",
"x",
"[",
"0",
"]",
"for",
"x",
"in",
"data_shapes",
"]",
"if",
"sorted",
"(",
"data_names",
")",
"!=",
"sorted",
"(",
"actual"... | Check that input names matches input data descriptors. | [
"Check",
"that",
"input",
"names",
"matches",
"input",
"data",
"descriptors",
"."
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/module/base_module.py#L58-L67 | train |
apache/incubator-mxnet | python/mxnet/module/base_module.py | _parse_data_desc | def _parse_data_desc(data_names, label_names, data_shapes, label_shapes):
"""parse data_attrs into DataDesc format and check that names match"""
data_shapes = [x if isinstance(x, DataDesc) else DataDesc(*x) for x in data_shapes]
_check_names_match(data_names, data_shapes, 'data', True)
if label_shapes i... | python | def _parse_data_desc(data_names, label_names, data_shapes, label_shapes):
"""parse data_attrs into DataDesc format and check that names match"""
data_shapes = [x if isinstance(x, DataDesc) else DataDesc(*x) for x in data_shapes]
_check_names_match(data_names, data_shapes, 'data', True)
if label_shapes i... | [
"def",
"_parse_data_desc",
"(",
"data_names",
",",
"label_names",
",",
"data_shapes",
",",
"label_shapes",
")",
":",
"data_shapes",
"=",
"[",
"x",
"if",
"isinstance",
"(",
"x",
",",
"DataDesc",
")",
"else",
"DataDesc",
"(",
"*",
"x",
")",
"for",
"x",
"in... | parse data_attrs into DataDesc format and check that names match | [
"parse",
"data_attrs",
"into",
"DataDesc",
"format",
"and",
"check",
"that",
"names",
"match"
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/module/base_module.py#L70-L79 | train |
apache/incubator-mxnet | python/mxnet/module/base_module.py | BaseModule.forward_backward | def forward_backward(self, data_batch):
"""A convenient function that calls both ``forward`` and ``backward``."""
self.forward(data_batch, is_train=True)
self.backward() | python | def forward_backward(self, data_batch):
"""A convenient function that calls both ``forward`` and ``backward``."""
self.forward(data_batch, is_train=True)
self.backward() | [
"def",
"forward_backward",
"(",
"self",
",",
"data_batch",
")",
":",
"self",
".",
"forward",
"(",
"data_batch",
",",
"is_train",
"=",
"True",
")",
"self",
".",
"backward",
"(",
")"
] | A convenient function that calls both ``forward`` and ``backward``. | [
"A",
"convenient",
"function",
"that",
"calls",
"both",
"forward",
"and",
"backward",
"."
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/module/base_module.py#L193-L196 | train |
apache/incubator-mxnet | python/mxnet/module/base_module.py | BaseModule.score | def score(self, eval_data, eval_metric, num_batch=None, batch_end_callback=None,
score_end_callback=None,
reset=True, epoch=0, sparse_row_id_fn=None):
"""Runs prediction on ``eval_data`` and evaluates the performance according to
the given ``eval_metric``.
Checkout `... | python | def score(self, eval_data, eval_metric, num_batch=None, batch_end_callback=None,
score_end_callback=None,
reset=True, epoch=0, sparse_row_id_fn=None):
"""Runs prediction on ``eval_data`` and evaluates the performance according to
the given ``eval_metric``.
Checkout `... | [
"def",
"score",
"(",
"self",
",",
"eval_data",
",",
"eval_metric",
",",
"num_batch",
"=",
"None",
",",
"batch_end_callback",
"=",
"None",
",",
"score_end_callback",
"=",
"None",
",",
"reset",
"=",
"True",
",",
"epoch",
"=",
"0",
",",
"sparse_row_id_fn",
"=... | Runs prediction on ``eval_data`` and evaluates the performance according to
the given ``eval_metric``.
Checkout `Module Tutorial <http://mxnet.io/tutorials/basic/module.html>`_ to see
a end-to-end use-case.
Parameters
----------
eval_data : DataIter
Evaluati... | [
"Runs",
"prediction",
"on",
"eval_data",
"and",
"evaluates",
"the",
"performance",
"according",
"to",
"the",
"given",
"eval_metric",
"."
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/module/base_module.py#L198-L276 | train |
apache/incubator-mxnet | python/mxnet/module/base_module.py | BaseModule.iter_predict | def iter_predict(self, eval_data, num_batch=None, reset=True, sparse_row_id_fn=None):
"""Iterates over predictions.
Examples
--------
>>> for pred, i_batch, batch in module.iter_predict(eval_data):
... # pred is a list of outputs from the module
... # i_batch is ... | python | def iter_predict(self, eval_data, num_batch=None, reset=True, sparse_row_id_fn=None):
"""Iterates over predictions.
Examples
--------
>>> for pred, i_batch, batch in module.iter_predict(eval_data):
... # pred is a list of outputs from the module
... # i_batch is ... | [
"def",
"iter_predict",
"(",
"self",
",",
"eval_data",
",",
"num_batch",
"=",
"None",
",",
"reset",
"=",
"True",
",",
"sparse_row_id_fn",
"=",
"None",
")",
":",
"assert",
"self",
".",
"binded",
"and",
"self",
".",
"params_initialized",
"if",
"reset",
":",
... | Iterates over predictions.
Examples
--------
>>> for pred, i_batch, batch in module.iter_predict(eval_data):
... # pred is a list of outputs from the module
... # i_batch is a integer
... # batch is the data batch from the data iterator
Parameters
... | [
"Iterates",
"over",
"predictions",
"."
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/module/base_module.py#L278-L316 | train |
apache/incubator-mxnet | python/mxnet/module/base_module.py | BaseModule.predict | def predict(self, eval_data, num_batch=None, merge_batches=True, reset=True,
always_output_list=False, sparse_row_id_fn=None):
"""Runs prediction and collects the outputs.
When `merge_batches` is ``True`` (by default), the return value will be a list
``[out1, out2, out3]``, wher... | python | def predict(self, eval_data, num_batch=None, merge_batches=True, reset=True,
always_output_list=False, sparse_row_id_fn=None):
"""Runs prediction and collects the outputs.
When `merge_batches` is ``True`` (by default), the return value will be a list
``[out1, out2, out3]``, wher... | [
"def",
"predict",
"(",
"self",
",",
"eval_data",
",",
"num_batch",
"=",
"None",
",",
"merge_batches",
"=",
"True",
",",
"reset",
"=",
"True",
",",
"always_output_list",
"=",
"False",
",",
"sparse_row_id_fn",
"=",
"None",
")",
":",
"assert",
"self",
".",
... | Runs prediction and collects the outputs.
When `merge_batches` is ``True`` (by default), the return value will be a list
``[out1, out2, out3]``, where each element is formed by concatenating the outputs for
all the mini-batches. When `always_output_list` is ``False`` (as by default),
th... | [
"Runs",
"prediction",
"and",
"collects",
"the",
"outputs",
"."
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/module/base_module.py#L318-L407 | train |
apache/incubator-mxnet | python/mxnet/module/base_module.py | BaseModule.set_params | def set_params(self, arg_params, aux_params, allow_missing=False, force_init=True,
allow_extra=False):
"""Assigns parameter and aux state values.
Parameters
----------
arg_params : dict
Dictionary of name to value (`NDArray`) mapping.
aux_params : ... | python | def set_params(self, arg_params, aux_params, allow_missing=False, force_init=True,
allow_extra=False):
"""Assigns parameter and aux state values.
Parameters
----------
arg_params : dict
Dictionary of name to value (`NDArray`) mapping.
aux_params : ... | [
"def",
"set_params",
"(",
"self",
",",
"arg_params",
",",
"aux_params",
",",
"allow_missing",
"=",
"False",
",",
"force_init",
"=",
"True",
",",
"allow_extra",
"=",
"False",
")",
":",
"self",
".",
"init_params",
"(",
"initializer",
"=",
"None",
",",
"arg_p... | Assigns parameter and aux state values.
Parameters
----------
arg_params : dict
Dictionary of name to value (`NDArray`) mapping.
aux_params : dict
Dictionary of name to value (`NDArray`) mapping.
allow_missing : bool
If ``True``, params could ... | [
"Assigns",
"parameter",
"and",
"aux",
"state",
"values",
"."
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/module/base_module.py#L671-L699 | train |
apache/incubator-mxnet | python/mxnet/module/base_module.py | BaseModule.save_params | def save_params(self, fname):
"""Saves model parameters to file.
Parameters
----------
fname : str
Path to output param file.
Examples
--------
>>> # An example of saving module parameters.
>>> mod.save_params('myfile')
"""
ar... | python | def save_params(self, fname):
"""Saves model parameters to file.
Parameters
----------
fname : str
Path to output param file.
Examples
--------
>>> # An example of saving module parameters.
>>> mod.save_params('myfile')
"""
ar... | [
"def",
"save_params",
"(",
"self",
",",
"fname",
")",
":",
"arg_params",
",",
"aux_params",
"=",
"self",
".",
"get_params",
"(",
")",
"save_dict",
"=",
"{",
"(",
"'arg:%s'",
"%",
"k",
")",
":",
"v",
".",
"as_in_context",
"(",
"cpu",
"(",
")",
")",
... | Saves model parameters to file.
Parameters
----------
fname : str
Path to output param file.
Examples
--------
>>> # An example of saving module parameters.
>>> mod.save_params('myfile') | [
"Saves",
"model",
"parameters",
"to",
"file",
"."
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/module/base_module.py#L701-L717 | train |
apache/incubator-mxnet | python/mxnet/module/base_module.py | BaseModule.load_params | def load_params(self, fname):
"""Loads model parameters from file.
Parameters
----------
fname : str
Path to input param file.
Examples
--------
>>> # An example of loading module parameters.
>>> mod.load_params('myfile')
"""
... | python | def load_params(self, fname):
"""Loads model parameters from file.
Parameters
----------
fname : str
Path to input param file.
Examples
--------
>>> # An example of loading module parameters.
>>> mod.load_params('myfile')
"""
... | [
"def",
"load_params",
"(",
"self",
",",
"fname",
")",
":",
"save_dict",
"=",
"ndarray",
".",
"load",
"(",
"fname",
")",
"arg_params",
"=",
"{",
"}",
"aux_params",
"=",
"{",
"}",
"for",
"k",
",",
"value",
"in",
"save_dict",
".",
"items",
"(",
")",
"... | Loads model parameters from file.
Parameters
----------
fname : str
Path to input param file.
Examples
--------
>>> # An example of loading module parameters.
>>> mod.load_params('myfile') | [
"Loads",
"model",
"parameters",
"from",
"file",
"."
] | 1af29e9c060a4c7d60eeaacba32afdb9a7775ba7 | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/module/base_module.py#L719-L743 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.