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
python/mxnet/kvstore.py
_ctype_dict
def _ctype_dict(param_dict): """ Returns ctype arrays for keys and values(converted to strings) in a dictionary """ assert(isinstance(param_dict, dict)), \ "unexpected type for param_dict: " + str(type(param_dict)) c_keys = c_array(ctypes.c_char_p, [c_str(k) for k in param_dict.keys()]) ...
python
def _ctype_dict(param_dict): """ Returns ctype arrays for keys and values(converted to strings) in a dictionary """ assert(isinstance(param_dict, dict)), \ "unexpected type for param_dict: " + str(type(param_dict)) c_keys = c_array(ctypes.c_char_p, [c_str(k) for k in param_dict.keys()]) ...
[ "def", "_ctype_dict", "(", "param_dict", ")", ":", "assert", "(", "isinstance", "(", "param_dict", ",", "dict", ")", ")", ",", "\"unexpected type for param_dict: \"", "+", "str", "(", "type", "(", "param_dict", ")", ")", "c_keys", "=", "c_array", "(", "ctype...
Returns ctype arrays for keys and values(converted to strings) in a dictionary
[ "Returns", "ctype", "arrays", "for", "keys", "and", "values", "(", "converted", "to", "strings", ")", "in", "a", "dictionary" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/kvstore.py#L68-L76
train
apache/incubator-mxnet
python/mxnet/kvstore.py
_updater_wrapper
def _updater_wrapper(updater): """A wrapper for the user-defined handle.""" def updater_handle(key, lhs_handle, rhs_handle, _): """ ctypes function """ lhs = _ndarray_cls(NDArrayHandle(lhs_handle)) rhs = _ndarray_cls(NDArrayHandle(rhs_handle)) updater(key, lhs, rhs) return up...
python
def _updater_wrapper(updater): """A wrapper for the user-defined handle.""" def updater_handle(key, lhs_handle, rhs_handle, _): """ ctypes function """ lhs = _ndarray_cls(NDArrayHandle(lhs_handle)) rhs = _ndarray_cls(NDArrayHandle(rhs_handle)) updater(key, lhs, rhs) return up...
[ "def", "_updater_wrapper", "(", "updater", ")", ":", "def", "updater_handle", "(", "key", ",", "lhs_handle", ",", "rhs_handle", ",", "_", ")", ":", "\"\"\" ctypes function \"\"\"", "lhs", "=", "_ndarray_cls", "(", "NDArrayHandle", "(", "lhs_handle", ")", ")", ...
A wrapper for the user-defined handle.
[ "A", "wrapper", "for", "the", "user", "-", "defined", "handle", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/kvstore.py#L78-L85
train
apache/incubator-mxnet
python/mxnet/kvstore.py
create
def create(name='local'): """Creates a new KVStore. For single machine training, there are two commonly used types: ``local``: Copies all gradients to CPU memory and updates weights there. ``device``: Aggregates gradients and updates weights on GPUs. With this setting, the KVStore also attempts t...
python
def create(name='local'): """Creates a new KVStore. For single machine training, there are two commonly used types: ``local``: Copies all gradients to CPU memory and updates weights there. ``device``: Aggregates gradients and updates weights on GPUs. With this setting, the KVStore also attempts t...
[ "def", "create", "(", "name", "=", "'local'", ")", ":", "if", "not", "isinstance", "(", "name", ",", "string_types", ")", ":", "raise", "TypeError", "(", "'name must be a string'", ")", "handle", "=", "KVStoreHandle", "(", ")", "check_call", "(", "_LIB", "...
Creates a new KVStore. For single machine training, there are two commonly used types: ``local``: Copies all gradients to CPU memory and updates weights there. ``device``: Aggregates gradients and updates weights on GPUs. With this setting, the KVStore also attempts to use GPU peer-to-peer communicat...
[ "Creates", "a", "new", "KVStore", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/kvstore.py#L635-L677
train
apache/incubator-mxnet
python/mxnet/kvstore.py
KVStore.init
def init(self, key, value): """ Initializes a single or a sequence of key-value pairs into the store. For each key, one must `init` it before calling `push` or `pull`. When multiple workers invoke `init` for the same key, only the value supplied by worker with rank `0` is used. This fun...
python
def init(self, key, value): """ Initializes a single or a sequence of key-value pairs into the store. For each key, one must `init` it before calling `push` or `pull`. When multiple workers invoke `init` for the same key, only the value supplied by worker with rank `0` is used. This fun...
[ "def", "init", "(", "self", ",", "key", ",", "value", ")", ":", "ckeys", ",", "cvals", ",", "use_str_keys", "=", "_ctype_key_value", "(", "key", ",", "value", ")", "if", "use_str_keys", ":", "check_call", "(", "_LIB", ".", "MXKVStoreInitEx", "(", "self",...
Initializes a single or a sequence of key-value pairs into the store. For each key, one must `init` it before calling `push` or `pull`. When multiple workers invoke `init` for the same key, only the value supplied by worker with rank `0` is used. This function returns after data has bee...
[ "Initializes", "a", "single", "or", "a", "sequence", "of", "key", "-", "value", "pairs", "into", "the", "store", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/kvstore.py#L116-L158
train
apache/incubator-mxnet
python/mxnet/kvstore.py
KVStore.push
def push(self, key, value, priority=0): """ Pushes a single or a sequence of key-value pairs into the store. This function returns immediately after adding an operator to the engine. The actual operation is executed asynchronously. If there are consecutive pushes to the same key, there ...
python
def push(self, key, value, priority=0): """ Pushes a single or a sequence of key-value pairs into the store. This function returns immediately after adding an operator to the engine. The actual operation is executed asynchronously. If there are consecutive pushes to the same key, there ...
[ "def", "push", "(", "self", ",", "key", ",", "value", ",", "priority", "=", "0", ")", ":", "ckeys", ",", "cvals", ",", "use_str_keys", "=", "_ctype_key_value", "(", "key", ",", "value", ")", "if", "use_str_keys", ":", "check_call", "(", "_LIB", ".", ...
Pushes a single or a sequence of key-value pairs into the store. This function returns immediately after adding an operator to the engine. The actual operation is executed asynchronously. If there are consecutive pushes to the same key, there is no guarantee on the serialization of pushes. ...
[ "Pushes", "a", "single", "or", "a", "sequence", "of", "key", "-", "value", "pairs", "into", "the", "store", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/kvstore.py#L160-L237
train
apache/incubator-mxnet
python/mxnet/kvstore.py
KVStore.pull
def pull(self, key, out=None, priority=0, ignore_sparse=True): """ Pulls a single value or a sequence of values from the store. This function returns immediately after adding an operator to the engine. Subsequent attempts to read from the `out` variable will be blocked until the pull op...
python
def pull(self, key, out=None, priority=0, ignore_sparse=True): """ Pulls a single value or a sequence of values from the store. This function returns immediately after adding an operator to the engine. Subsequent attempts to read from the `out` variable will be blocked until the pull op...
[ "def", "pull", "(", "self", ",", "key", ",", "out", "=", "None", ",", "priority", "=", "0", ",", "ignore_sparse", "=", "True", ")", ":", "assert", "(", "out", "is", "not", "None", ")", "ckeys", ",", "cvals", ",", "use_str_keys", "=", "_ctype_key_valu...
Pulls a single value or a sequence of values from the store. This function returns immediately after adding an operator to the engine. Subsequent attempts to read from the `out` variable will be blocked until the pull operation completes. `pull` is executed asynchronously after all pre...
[ "Pulls", "a", "single", "value", "or", "a", "sequence", "of", "values", "from", "the", "store", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/kvstore.py#L240-L312
train
apache/incubator-mxnet
python/mxnet/kvstore.py
KVStore.row_sparse_pull
def row_sparse_pull(self, key, out=None, priority=0, row_ids=None): """ Pulls a single RowSparseNDArray value or a sequence of RowSparseNDArray values \ from the store with specified row_ids. When there is only one row_id, KVStoreRowSparsePull \ is invoked just once and the result is broadcast t...
python
def row_sparse_pull(self, key, out=None, priority=0, row_ids=None): """ Pulls a single RowSparseNDArray value or a sequence of RowSparseNDArray values \ from the store with specified row_ids. When there is only one row_id, KVStoreRowSparsePull \ is invoked just once and the result is broadcast t...
[ "def", "row_sparse_pull", "(", "self", ",", "key", ",", "out", "=", "None", ",", "priority", "=", "0", ",", "row_ids", "=", "None", ")", ":", "assert", "(", "out", "is", "not", "None", ")", "assert", "(", "row_ids", "is", "not", "None", ")", "if", ...
Pulls a single RowSparseNDArray value or a sequence of RowSparseNDArray values \ from the store with specified row_ids. When there is only one row_id, KVStoreRowSparsePull \ is invoked just once and the result is broadcast to all the rest of outputs. `row_sparse_pull` is executed asynchronously...
[ "Pulls", "a", "single", "RowSparseNDArray", "value", "or", "a", "sequence", "of", "RowSparseNDArray", "values", "\\", "from", "the", "store", "with", "specified", "row_ids", ".", "When", "there", "is", "only", "one", "row_id", "KVStoreRowSparsePull", "\\", "is",...
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/kvstore.py#L314-L392
train
apache/incubator-mxnet
python/mxnet/kvstore.py
KVStore.set_gradient_compression
def set_gradient_compression(self, compression_params): """ Specifies type of low-bit quantization for gradient compression \ and additional arguments depending on the type of compression being used. 2bit Gradient Compression takes a positive float `threshold`. The technique works by t...
python
def set_gradient_compression(self, compression_params): """ Specifies type of low-bit quantization for gradient compression \ and additional arguments depending on the type of compression being used. 2bit Gradient Compression takes a positive float `threshold`. The technique works by t...
[ "def", "set_gradient_compression", "(", "self", ",", "compression_params", ")", ":", "if", "(", "'device'", "in", "self", ".", "type", ")", "or", "(", "'dist'", "in", "self", ".", "type", ")", ":", "# pylint: disable=unsupported-membership-test", "ckeys", ",", ...
Specifies type of low-bit quantization for gradient compression \ and additional arguments depending on the type of compression being used. 2bit Gradient Compression takes a positive float `threshold`. The technique works by thresholding values such that positive values in the gradient...
[ "Specifies", "type", "of", "low", "-", "bit", "quantization", "for", "gradient", "compression", "\\", "and", "additional", "arguments", "depending", "on", "the", "type", "of", "compression", "being", "used", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/kvstore.py#L394-L448
train
apache/incubator-mxnet
python/mxnet/kvstore.py
KVStore.set_optimizer
def set_optimizer(self, optimizer): """ Registers an optimizer with the kvstore. When using a single machine, this function updates the local optimizer. If using multiple machines and this operation is invoked from a worker node, it will serialized the optimizer with pickle and send it ...
python
def set_optimizer(self, optimizer): """ Registers an optimizer with the kvstore. When using a single machine, this function updates the local optimizer. If using multiple machines and this operation is invoked from a worker node, it will serialized the optimizer with pickle and send it ...
[ "def", "set_optimizer", "(", "self", ",", "optimizer", ")", ":", "is_worker", "=", "ctypes", ".", "c_int", "(", ")", "check_call", "(", "_LIB", ".", "MXKVStoreIsWorkerNode", "(", "ctypes", ".", "byref", "(", "is_worker", ")", ")", ")", "# pylint: disable=inv...
Registers an optimizer with the kvstore. When using a single machine, this function updates the local optimizer. If using multiple machines and this operation is invoked from a worker node, it will serialized the optimizer with pickle and send it to all servers. The function returns aft...
[ "Registers", "an", "optimizer", "with", "the", "kvstore", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/kvstore.py#L450-L497
train
apache/incubator-mxnet
python/mxnet/kvstore.py
KVStore.type
def type(self): """ Returns the type of this kvstore. Returns ------- type : str the string type """ kv_type = ctypes.c_char_p() check_call(_LIB.MXKVStoreGetType(self.handle, ctypes.byref(kv_type))) return py_str(kv_type.value)
python
def type(self): """ Returns the type of this kvstore. Returns ------- type : str the string type """ kv_type = ctypes.c_char_p() check_call(_LIB.MXKVStoreGetType(self.handle, ctypes.byref(kv_type))) return py_str(kv_type.value)
[ "def", "type", "(", "self", ")", ":", "kv_type", "=", "ctypes", ".", "c_char_p", "(", ")", "check_call", "(", "_LIB", ".", "MXKVStoreGetType", "(", "self", ".", "handle", ",", "ctypes", ".", "byref", "(", "kv_type", ")", ")", ")", "return", "py_str", ...
Returns the type of this kvstore. Returns ------- type : str the string type
[ "Returns", "the", "type", "of", "this", "kvstore", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/kvstore.py#L500-L510
train
apache/incubator-mxnet
python/mxnet/kvstore.py
KVStore.rank
def rank(self): """ Returns the rank of this worker node. Returns ------- rank : int The rank of this node, which is in range [0, num_workers()) """ rank = ctypes.c_int() check_call(_LIB.MXKVStoreGetRank(self.handle, ctypes.byref(rank))) retur...
python
def rank(self): """ Returns the rank of this worker node. Returns ------- rank : int The rank of this node, which is in range [0, num_workers()) """ rank = ctypes.c_int() check_call(_LIB.MXKVStoreGetRank(self.handle, ctypes.byref(rank))) retur...
[ "def", "rank", "(", "self", ")", ":", "rank", "=", "ctypes", ".", "c_int", "(", ")", "check_call", "(", "_LIB", ".", "MXKVStoreGetRank", "(", "self", ".", "handle", ",", "ctypes", ".", "byref", "(", "rank", ")", ")", ")", "return", "rank", ".", "va...
Returns the rank of this worker node. Returns ------- rank : int The rank of this node, which is in range [0, num_workers())
[ "Returns", "the", "rank", "of", "this", "worker", "node", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/kvstore.py#L513-L523
train
apache/incubator-mxnet
python/mxnet/kvstore.py
KVStore.num_workers
def num_workers(self): """Returns the number of worker nodes. Returns ------- size :int The number of worker nodes. """ size = ctypes.c_int() check_call(_LIB.MXKVStoreGetGroupSize(self.handle, ctypes.byref(size))) return size.value
python
def num_workers(self): """Returns the number of worker nodes. Returns ------- size :int The number of worker nodes. """ size = ctypes.c_int() check_call(_LIB.MXKVStoreGetGroupSize(self.handle, ctypes.byref(size))) return size.value
[ "def", "num_workers", "(", "self", ")", ":", "size", "=", "ctypes", ".", "c_int", "(", ")", "check_call", "(", "_LIB", ".", "MXKVStoreGetGroupSize", "(", "self", ".", "handle", ",", "ctypes", ".", "byref", "(", "size", ")", ")", ")", "return", "size", ...
Returns the number of worker nodes. Returns ------- size :int The number of worker nodes.
[ "Returns", "the", "number", "of", "worker", "nodes", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/kvstore.py#L526-L536
train
apache/incubator-mxnet
python/mxnet/kvstore.py
KVStore.save_optimizer_states
def save_optimizer_states(self, fname, dump_optimizer=False): """Saves the optimizer (updater) state to a file. This is often used when checkpointing the model during training. Parameters ---------- fname : str Path to the output states file. dump_optimizer :...
python
def save_optimizer_states(self, fname, dump_optimizer=False): """Saves the optimizer (updater) state to a file. This is often used when checkpointing the model during training. Parameters ---------- fname : str Path to the output states file. dump_optimizer :...
[ "def", "save_optimizer_states", "(", "self", ",", "fname", ",", "dump_optimizer", "=", "False", ")", ":", "assert", "self", ".", "_updater", "is", "not", "None", ",", "\"Cannot save states for distributed training\"", "with", "open", "(", "fname", ",", "'wb'", "...
Saves the optimizer (updater) state to a file. This is often used when checkpointing the model during training. Parameters ---------- fname : str Path to the output states file. dump_optimizer : bool, default False Whether to also save the optimizer itsel...
[ "Saves", "the", "optimizer", "(", "updater", ")", "state", "to", "a", "file", ".", "This", "is", "often", "used", "when", "checkpointing", "the", "model", "during", "training", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/kvstore.py#L538-L552
train
apache/incubator-mxnet
python/mxnet/kvstore.py
KVStore.load_optimizer_states
def load_optimizer_states(self, fname): """Loads the optimizer (updater) state from the file. Parameters ---------- fname : str Path to input states file. """ assert self._updater is not None, "Cannot load states for distributed training" self._update...
python
def load_optimizer_states(self, fname): """Loads the optimizer (updater) state from the file. Parameters ---------- fname : str Path to input states file. """ assert self._updater is not None, "Cannot load states for distributed training" self._update...
[ "def", "load_optimizer_states", "(", "self", ",", "fname", ")", ":", "assert", "self", ".", "_updater", "is", "not", "None", ",", "\"Cannot load states for distributed training\"", "self", ".", "_updater", ".", "set_states", "(", "open", "(", "fname", ",", "'rb'...
Loads the optimizer (updater) state from the file. Parameters ---------- fname : str Path to input states file.
[ "Loads", "the", "optimizer", "(", "updater", ")", "state", "from", "the", "file", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/kvstore.py#L554-L563
train
apache/incubator-mxnet
python/mxnet/kvstore.py
KVStore._set_updater
def _set_updater(self, updater): """Sets a push updater into the store. This function only changes the local store. When running on multiple machines one must use `set_optimizer`. Parameters ---------- updater : function The updater function. Exampl...
python
def _set_updater(self, updater): """Sets a push updater into the store. This function only changes the local store. When running on multiple machines one must use `set_optimizer`. Parameters ---------- updater : function The updater function. Exampl...
[ "def", "_set_updater", "(", "self", ",", "updater", ")", ":", "self", ".", "_updater", "=", "updater", "# set updater with int keys", "_updater_proto", "=", "ctypes", ".", "CFUNCTYPE", "(", "None", ",", "ctypes", ".", "c_int", ",", "NDArrayHandle", ",", "NDArr...
Sets a push updater into the store. This function only changes the local store. When running on multiple machines one must use `set_optimizer`. Parameters ---------- updater : function The updater function. Examples -------- >>> def update(k...
[ "Sets", "a", "push", "updater", "into", "the", "store", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/kvstore.py#L565-L603
train
apache/incubator-mxnet
python/mxnet/kvstore.py
KVStore._send_command_to_servers
def _send_command_to_servers(self, head, body): """Sends a command to all server nodes. Sending command to a server node will cause that server node to invoke ``KVStoreServer.controller`` to execute the command. This function returns after the command has been executed on all server ...
python
def _send_command_to_servers(self, head, body): """Sends a command to all server nodes. Sending command to a server node will cause that server node to invoke ``KVStoreServer.controller`` to execute the command. This function returns after the command has been executed on all server ...
[ "def", "_send_command_to_servers", "(", "self", ",", "head", ",", "body", ")", ":", "check_call", "(", "_LIB", ".", "MXKVStoreSendCommmandToServers", "(", "self", ".", "handle", ",", "mx_uint", "(", "head", ")", ",", "c_str", "(", "body", ")", ")", ")" ]
Sends a command to all server nodes. Sending command to a server node will cause that server node to invoke ``KVStoreServer.controller`` to execute the command. This function returns after the command has been executed on all server nodes. Parameters ---------- ...
[ "Sends", "a", "command", "to", "all", "server", "nodes", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/kvstore.py#L616-L633
train
apache/incubator-mxnet
python/mxnet/module/sequential_module.py
SequentialModule.add
def add(self, module, **kwargs): """Add a module to the chain. Parameters ---------- module : BaseModule The new module to add. kwargs : ``**keywords`` All the keyword arguments are saved as meta information for the added module. The currently...
python
def add(self, module, **kwargs): """Add a module to the chain. Parameters ---------- module : BaseModule The new module to add. kwargs : ``**keywords`` All the keyword arguments are saved as meta information for the added module. The currently...
[ "def", "add", "(", "self", ",", "module", ",", "*", "*", "kwargs", ")", ":", "self", ".", "_modules", ".", "append", "(", "module", ")", "# a sanity check to avoid typo", "for", "key", "in", "kwargs", ":", "assert", "key", "in", "self", ".", "_meta_keys"...
Add a module to the chain. Parameters ---------- module : BaseModule The new module to add. kwargs : ``**keywords`` All the keyword arguments are saved as meta information for the added module. The currently known meta includes - `take_la...
[ "Add", "a", "module", "to", "the", "chain", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/module/sequential_module.py#L52-L97
train
apache/incubator-mxnet
python/mxnet/module/sequential_module.py
SequentialModule.get_params
def get_params(self): """Gets current parameters. Returns ------- (arg_params, aux_params) A pair of dictionaries each mapping parameter names to NDArray values. This is a merged dictionary of all the parameters in the modules. """ assert self.bin...
python
def get_params(self): """Gets current parameters. Returns ------- (arg_params, aux_params) A pair of dictionaries each mapping parameter names to NDArray values. This is a merged dictionary of all the parameters in the modules. """ assert self.bin...
[ "def", "get_params", "(", "self", ")", ":", "assert", "self", ".", "binded", "and", "self", ".", "params_initialized", "arg_params", "=", "dict", "(", ")", "aux_params", "=", "dict", "(", ")", "for", "module", "in", "self", ".", "_modules", ":", "arg", ...
Gets current parameters. Returns ------- (arg_params, aux_params) A pair of dictionaries each mapping parameter names to NDArray values. This is a merged dictionary of all the parameters in the modules.
[ "Gets", "current", "parameters", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/module/sequential_module.py#L153-L172
train
apache/incubator-mxnet
python/mxnet/module/sequential_module.py
SequentialModule.init_params
def init_params(self, initializer=Uniform(0.01), arg_params=None, aux_params=None, allow_missing=False, force_init=False, allow_extra=False): """Initializes parameters. Parameters ---------- initializer : Initializer arg_params : dict Default ``No...
python
def init_params(self, initializer=Uniform(0.01), arg_params=None, aux_params=None, allow_missing=False, force_init=False, allow_extra=False): """Initializes parameters. Parameters ---------- initializer : Initializer arg_params : dict Default ``No...
[ "def", "init_params", "(", "self", ",", "initializer", "=", "Uniform", "(", "0.01", ")", ",", "arg_params", "=", "None", ",", "aux_params", "=", "None", ",", "allow_missing", "=", "False", ",", "force_init", "=", "False", ",", "allow_extra", "=", "False", ...
Initializes parameters. Parameters ---------- initializer : Initializer arg_params : dict Default ``None``. Existing parameters. This has higher priority than `initializer`. aux_params : dict Default ``None``. Existing auxiliary states. This h...
[ "Initializes", "parameters", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/module/sequential_module.py#L174-L223
train
apache/incubator-mxnet
python/mxnet/module/sequential_module.py
SequentialModule.bind
def bind(self, data_shapes, label_shapes=None, for_training=True, inputs_need_grad=False, force_rebind=False, shared_module=None, grad_req='write'): """Binds the symbols to construct executors. This is necessary before one can perform computation with the module. Param...
python
def bind(self, data_shapes, label_shapes=None, for_training=True, inputs_need_grad=False, force_rebind=False, shared_module=None, grad_req='write'): """Binds the symbols to construct executors. This is necessary before one can perform computation with the module. Param...
[ "def", "bind", "(", "self", ",", "data_shapes", ",", "label_shapes", "=", "None", ",", "for_training", "=", "True", ",", "inputs_need_grad", "=", "False", ",", "force_rebind", "=", "False", ",", "shared_module", "=", "None", ",", "grad_req", "=", "'write'", ...
Binds the symbols to construct executors. This is necessary before one can perform computation with the module. Parameters ---------- data_shapes : list of (str, tuple) Typically is `data_iter.provide_data`. label_shapes : list of (str, tuple) Typically i...
[ "Binds", "the", "symbols", "to", "construct", "executors", ".", "This", "is", "necessary", "before", "one", "can", "perform", "computation", "with", "the", "module", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/module/sequential_module.py#L225-L296
train
apache/incubator-mxnet
python/mxnet/module/sequential_module.py
SequentialModule.init_optimizer
def init_optimizer(self, kvstore='local', optimizer='sgd', optimizer_params=(('learning_rate', 0.01),), force_init=False): """Installs and initializes optimizers. Parameters ---------- kvstore : str or KVStore Default `'local'`. ...
python
def init_optimizer(self, kvstore='local', optimizer='sgd', optimizer_params=(('learning_rate', 0.01),), force_init=False): """Installs and initializes optimizers. Parameters ---------- kvstore : str or KVStore Default `'local'`. ...
[ "def", "init_optimizer", "(", "self", ",", "kvstore", "=", "'local'", ",", "optimizer", "=", "'sgd'", ",", "optimizer_params", "=", "(", "(", "'learning_rate'", ",", "0.01", ")", ",", ")", ",", "force_init", "=", "False", ")", ":", "assert", "self", ".",...
Installs and initializes optimizers. Parameters ---------- kvstore : str or KVStore Default `'local'`. optimizer : str or Optimizer Default `'sgd'` optimizer_params : dict Default ``(('learning_rate', 0.01),)``. The default value is not a dict...
[ "Installs", "and", "initializes", "optimizers", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/module/sequential_module.py#L298-L325
train
apache/incubator-mxnet
python/mxnet/module/sequential_module.py
SequentialModule.forward
def forward(self, data_batch, is_train=None): """Forward computation. Parameters ---------- data_batch : DataBatch is_train : bool Default is ``None``, in which case `is_train` is take as ``self.for_training``. """ assert self.binded and self.params_i...
python
def forward(self, data_batch, is_train=None): """Forward computation. Parameters ---------- data_batch : DataBatch is_train : bool Default is ``None``, in which case `is_train` is take as ``self.for_training``. """ assert self.binded and self.params_i...
[ "def", "forward", "(", "self", ",", "data_batch", ",", "is_train", "=", "None", ")", ":", "assert", "self", ".", "binded", "and", "self", ".", "params_initialized", "# make a shallow copy, just to maintain necessary properties (if any) like", "# bucket_key, pad, etc.", "d...
Forward computation. Parameters ---------- data_batch : DataBatch is_train : bool Default is ``None``, in which case `is_train` is take as ``self.for_training``.
[ "Forward", "computation", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/module/sequential_module.py#L327-L356
train
apache/incubator-mxnet
python/mxnet/module/sequential_module.py
SequentialModule.backward
def backward(self, out_grads=None): """Backward computation.""" assert self.binded and self.params_initialized for i_layer, module in reversed(list(zip(range(len(self._modules)), self._modules))): module.backward(out_grads=out_grads) if i_layer == 0: brea...
python
def backward(self, out_grads=None): """Backward computation.""" assert self.binded and self.params_initialized for i_layer, module in reversed(list(zip(range(len(self._modules)), self._modules))): module.backward(out_grads=out_grads) if i_layer == 0: brea...
[ "def", "backward", "(", "self", ",", "out_grads", "=", "None", ")", ":", "assert", "self", ".", "binded", "and", "self", ".", "params_initialized", "for", "i_layer", ",", "module", "in", "reversed", "(", "list", "(", "zip", "(", "range", "(", "len", "(...
Backward computation.
[ "Backward", "computation", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/module/sequential_module.py#L358-L367
train
apache/incubator-mxnet
python/mxnet/module/sequential_module.py
SequentialModule.update
def update(self): """Updates parameters according to installed optimizer and the gradient computed in the previous forward-backward cycle. """ assert self.binded and self.params_initialized and self.optimizer_initialized for module in self._modules: module.update()
python
def update(self): """Updates parameters according to installed optimizer and the gradient computed in the previous forward-backward cycle. """ assert self.binded and self.params_initialized and self.optimizer_initialized for module in self._modules: module.update()
[ "def", "update", "(", "self", ")", ":", "assert", "self", ".", "binded", "and", "self", ".", "params_initialized", "and", "self", ".", "optimizer_initialized", "for", "module", "in", "self", ".", "_modules", ":", "module", ".", "update", "(", ")" ]
Updates parameters according to installed optimizer and the gradient computed in the previous forward-backward cycle.
[ "Updates", "parameters", "according", "to", "installed", "optimizer", "and", "the", "gradient", "computed", "in", "the", "previous", "forward", "-", "backward", "cycle", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/module/sequential_module.py#L369-L376
train
apache/incubator-mxnet
python/mxnet/module/sequential_module.py
SequentialModule.get_outputs
def get_outputs(self, merge_multi_context=True): """Gets outputs from a previous forward computation. Parameters ---------- merge_multi_context : bool Default is ``True``. In the case when data-parallelism is used, the outputs will be collected from multiple devi...
python
def get_outputs(self, merge_multi_context=True): """Gets outputs from a previous forward computation. Parameters ---------- merge_multi_context : bool Default is ``True``. In the case when data-parallelism is used, the outputs will be collected from multiple devi...
[ "def", "get_outputs", "(", "self", ",", "merge_multi_context", "=", "True", ")", ":", "assert", "self", ".", "binded", "and", "self", ".", "params_initialized", "return", "self", ".", "_modules", "[", "-", "1", "]", ".", "get_outputs", "(", "merge_multi_cont...
Gets outputs from a previous forward computation. Parameters ---------- merge_multi_context : bool Default is ``True``. In the case when data-parallelism is used, the outputs will be collected from multiple devices. A ``True`` value indicate that we should me...
[ "Gets", "outputs", "from", "a", "previous", "forward", "computation", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/module/sequential_module.py#L378-L397
train
apache/incubator-mxnet
python/mxnet/module/sequential_module.py
SequentialModule.get_input_grads
def get_input_grads(self, merge_multi_context=True): """Gets the gradients with respect to the inputs of the module. Parameters ---------- merge_multi_context : bool Default is ``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): """Gets the gradients with respect to the inputs of the module. Parameters ---------- merge_multi_context : bool Default is ``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", ".", "binded", "and", "self", ".", "params_initialized", "and", "self", ".", "inputs_need_grad", "return", "self", ".", "_modules", "[", "0", "]", "."...
Gets the gradients with respect to the inputs of the module. Parameters ---------- merge_multi_context : bool Default is ``True``. In the case when data-parallelism is used, the outputs will be collected from multiple devices. A ``True`` value indicate that we ...
[ "Gets", "the", "gradients", "with", "respect", "to", "the", "inputs", "of", "the", "module", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/module/sequential_module.py#L399-L418
train
apache/incubator-mxnet
python/mxnet/module/sequential_module.py
SequentialModule.update_metric
def update_metric(self, eval_metric, labels, pre_sliced=False): """Evaluates and accumulates evaluation metric on outputs of the last forward computation. Parameters ---------- eval_metric : EvalMetric labels : list of NDArray Typically ``data_batch.label``. ...
python
def update_metric(self, eval_metric, labels, pre_sliced=False): """Evaluates and accumulates evaluation metric on outputs of the last forward computation. Parameters ---------- eval_metric : EvalMetric labels : list of NDArray Typically ``data_batch.label``. ...
[ "def", "update_metric", "(", "self", ",", "eval_metric", ",", "labels", ",", "pre_sliced", "=", "False", ")", ":", "assert", "self", ".", "binded", "and", "self", ".", "params_initialized", "for", "meta", ",", "module", "in", "zip", "(", "self", ".", "_m...
Evaluates and accumulates evaluation metric on outputs of the last forward computation. Parameters ---------- eval_metric : EvalMetric labels : list of NDArray Typically ``data_batch.label``.
[ "Evaluates", "and", "accumulates", "evaluation", "metric", "on", "outputs", "of", "the", "last", "forward", "computation", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/module/sequential_module.py#L420-L434
train
apache/incubator-mxnet
python/mxnet/module/sequential_module.py
SequentialModule.install_monitor
def install_monitor(self, mon): """Installs monitor on all executors.""" assert self.binded for module in self._modules: module.install_monitor(mon)
python
def install_monitor(self, mon): """Installs monitor on all executors.""" assert self.binded for module in self._modules: module.install_monitor(mon)
[ "def", "install_monitor", "(", "self", ",", "mon", ")", ":", "assert", "self", ".", "binded", "for", "module", "in", "self", ".", "_modules", ":", "module", ".", "install_monitor", "(", "mon", ")" ]
Installs monitor on all executors.
[ "Installs", "monitor", "on", "all", "executors", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/module/sequential_module.py#L436-L440
train
apache/incubator-mxnet
example/caffe/data.py
get_iterator
def get_iterator(data_shape, use_caffe_data): """Generate the iterator of mnist dataset""" def get_iterator_impl_mnist(args, kv): """return train and val iterators for mnist""" # download data get_mnist_ubyte() flat = False if len(data_shape) != 1 else True train = mx.io...
python
def get_iterator(data_shape, use_caffe_data): """Generate the iterator of mnist dataset""" def get_iterator_impl_mnist(args, kv): """return train and val iterators for mnist""" # download data get_mnist_ubyte() flat = False if len(data_shape) != 1 else True train = mx.io...
[ "def", "get_iterator", "(", "data_shape", ",", "use_caffe_data", ")", ":", "def", "get_iterator_impl_mnist", "(", "args", ",", "kv", ")", ":", "\"\"\"return train and val iterators for mnist\"\"\"", "# download data", "get_mnist_ubyte", "(", ")", "flat", "=", "False", ...
Generate the iterator of mnist dataset
[ "Generate", "the", "iterator", "of", "mnist", "dataset" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/caffe/data.py#L22-L106
train
apache/incubator-mxnet
example/gluon/audio/urban_sounds/predict.py
predict
def predict(prediction_dir='./Test'): """The function is used to run predictions on the audio files in the directory `pred_directory`. Parameters ---------- net: The model that has been trained. prediction_dir: string, default ./Test The directory that contains the audio files on wh...
python
def predict(prediction_dir='./Test'): """The function is used to run predictions on the audio files in the directory `pred_directory`. Parameters ---------- net: The model that has been trained. prediction_dir: string, default ./Test The directory that contains the audio files on wh...
[ "def", "predict", "(", "prediction_dir", "=", "'./Test'", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "prediction_dir", ")", ":", "warnings", ".", "warn", "(", "\"The directory on which predictions are to be made is not found!\"", ")", "return", ...
The function is used to run predictions on the audio files in the directory `pred_directory`. Parameters ---------- net: The model that has been trained. prediction_dir: string, default ./Test The directory that contains the audio files on which predictions are to be made
[ "The", "function", "is", "used", "to", "run", "predictions", "on", "the", "audio", "files", "in", "the", "directory", "pred_directory", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/gluon/audio/urban_sounds/predict.py#L32-L77
train
apache/incubator-mxnet
example/ctc/multiproc_data.py
MPData._proc_loop
def _proc_loop(proc_id, alive, queue, fn): """Thread loop for generating data Parameters ---------- proc_id: int Process id alive: multiprocessing.Value variable for signaling whether process should continue or not queue: multiprocessing.Queue ...
python
def _proc_loop(proc_id, alive, queue, fn): """Thread loop for generating data Parameters ---------- proc_id: int Process id alive: multiprocessing.Value variable for signaling whether process should continue or not queue: multiprocessing.Queue ...
[ "def", "_proc_loop", "(", "proc_id", ",", "alive", ",", "queue", ",", "fn", ")", ":", "print", "(", "\"proc {} started\"", ".", "format", "(", "proc_id", ")", ")", "try", ":", "while", "alive", ".", "value", ":", "data", "=", "fn", "(", ")", "put_suc...
Thread loop for generating data Parameters ---------- proc_id: int Process id alive: multiprocessing.Value variable for signaling whether process should continue or not queue: multiprocessing.Queue queue for passing data back fn: funct...
[ "Thread", "loop", "for", "generating", "data" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/ctc/multiproc_data.py#L59-L88
train
apache/incubator-mxnet
example/ctc/multiproc_data.py
MPData._init_proc
def _init_proc(self): """Start processes if not already started""" if not self.proc: self.proc = [ mp.Process(target=self._proc_loop, args=(i, self.alive, self.queue, self.fn)) for i in range(self.num_proc) ] self.alive.value = True ...
python
def _init_proc(self): """Start processes if not already started""" if not self.proc: self.proc = [ mp.Process(target=self._proc_loop, args=(i, self.alive, self.queue, self.fn)) for i in range(self.num_proc) ] self.alive.value = True ...
[ "def", "_init_proc", "(", "self", ")", ":", "if", "not", "self", ".", "proc", ":", "self", ".", "proc", "=", "[", "mp", ".", "Process", "(", "target", "=", "self", ".", "_proc_loop", ",", "args", "=", "(", "i", ",", "self", ".", "alive", ",", "...
Start processes if not already started
[ "Start", "processes", "if", "not", "already", "started" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/ctc/multiproc_data.py#L90-L99
train
apache/incubator-mxnet
example/ctc/multiproc_data.py
MPData.reset
def reset(self): """Resets the generator by stopping all processes""" self.alive.value = False qsize = 0 try: while True: self.queue.get(timeout=0.1) qsize += 1 except QEmptyExcept: pass print("Queue size on reset: {...
python
def reset(self): """Resets the generator by stopping all processes""" self.alive.value = False qsize = 0 try: while True: self.queue.get(timeout=0.1) qsize += 1 except QEmptyExcept: pass print("Queue size on reset: {...
[ "def", "reset", "(", "self", ")", ":", "self", ".", "alive", ".", "value", "=", "False", "qsize", "=", "0", "try", ":", "while", "True", ":", "self", ".", "queue", ".", "get", "(", "timeout", "=", "0.1", ")", "qsize", "+=", "1", "except", "QEmpty...
Resets the generator by stopping all processes
[ "Resets", "the", "generator", "by", "stopping", "all", "processes" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/ctc/multiproc_data.py#L112-L125
train
apache/incubator-mxnet
python/mxnet/base.py
with_metaclass
def with_metaclass(meta, *bases): """Create a base class with a metaclass.""" # This requires a bit of explanation: the basic idea is to make a dummy # metaclass for one level of class instantiation that replaces itself with # the actual metaclass. class metaclass(type): def __new__(cls, na...
python
def with_metaclass(meta, *bases): """Create a base class with a metaclass.""" # This requires a bit of explanation: the basic idea is to make a dummy # metaclass for one level of class instantiation that replaces itself with # the actual metaclass. class metaclass(type): def __new__(cls, na...
[ "def", "with_metaclass", "(", "meta", ",", "*", "bases", ")", ":", "# This requires a bit of explanation: the basic idea is to make a dummy", "# metaclass for one level of class instantiation that replaces itself with", "# the actual metaclass.", "class", "metaclass", "(", "type", ")...
Create a base class with a metaclass.
[ "Create", "a", "base", "class", "with", "a", "metaclass", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/base.py#L178-L191
train
apache/incubator-mxnet
python/mxnet/base.py
_load_lib
def _load_lib(): """Load library by searching possible path.""" lib_path = libinfo.find_lib_path() lib = ctypes.CDLL(lib_path[0], ctypes.RTLD_LOCAL) # DMatrix functions lib.MXGetLastError.restype = ctypes.c_char_p return lib
python
def _load_lib(): """Load library by searching possible path.""" lib_path = libinfo.find_lib_path() lib = ctypes.CDLL(lib_path[0], ctypes.RTLD_LOCAL) # DMatrix functions lib.MXGetLastError.restype = ctypes.c_char_p return lib
[ "def", "_load_lib", "(", ")", ":", "lib_path", "=", "libinfo", ".", "find_lib_path", "(", ")", "lib", "=", "ctypes", ".", "CDLL", "(", "lib_path", "[", "0", "]", ",", "ctypes", ".", "RTLD_LOCAL", ")", "# DMatrix functions", "lib", ".", "MXGetLastError", ...
Load library by searching possible path.
[ "Load", "library", "by", "searching", "possible", "path", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/base.py#L202-L208
train
apache/incubator-mxnet
python/mxnet/base.py
c_array
def c_array(ctype, values): """Create ctypes array from a Python array. Parameters ---------- ctype : ctypes data type Data type of the array we want to convert to, such as mx_float. values : tuple or list Data content. Returns ------- out : ctypes array Create...
python
def c_array(ctype, values): """Create ctypes array from a Python array. Parameters ---------- ctype : ctypes data type Data type of the array we want to convert to, such as mx_float. values : tuple or list Data content. Returns ------- out : ctypes array Create...
[ "def", "c_array", "(", "ctype", ",", "values", ")", ":", "out", "=", "(", "ctype", "*", "len", "(", "values", ")", ")", "(", ")", "out", "[", ":", "]", "=", "values", "return", "out" ]
Create ctypes array from a Python array. Parameters ---------- ctype : ctypes data type Data type of the array we want to convert to, such as mx_float. values : tuple or list Data content. Returns ------- out : ctypes array Created ctypes array. Examples -...
[ "Create", "ctypes", "array", "from", "a", "Python", "array", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/base.py#L336-L362
train
apache/incubator-mxnet
python/mxnet/base.py
c_handle_array
def c_handle_array(objs): """Create ctypes const void ** from a list of MXNet objects with handles. Parameters ---------- objs : list of NDArray/Symbol. MXNet objects. Returns ------- (ctypes.c_void_p * len(objs)) A void ** pointer that can be passed to C API. """ a...
python
def c_handle_array(objs): """Create ctypes const void ** from a list of MXNet objects with handles. Parameters ---------- objs : list of NDArray/Symbol. MXNet objects. Returns ------- (ctypes.c_void_p * len(objs)) A void ** pointer that can be passed to C API. """ a...
[ "def", "c_handle_array", "(", "objs", ")", ":", "arr", "=", "(", "ctypes", ".", "c_void_p", "*", "len", "(", "objs", ")", ")", "(", ")", "arr", "[", ":", "]", "=", "[", "o", ".", "handle", "for", "o", "in", "objs", "]", "return", "arr" ]
Create ctypes const void ** from a list of MXNet objects with handles. Parameters ---------- objs : list of NDArray/Symbol. MXNet objects. Returns ------- (ctypes.c_void_p * len(objs)) A void ** pointer that can be passed to C API.
[ "Create", "ctypes", "const", "void", "**", "from", "a", "list", "of", "MXNet", "objects", "with", "handles", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/base.py#L394-L409
train
apache/incubator-mxnet
python/mxnet/base.py
ctypes2numpy_shared
def ctypes2numpy_shared(cptr, shape): """Convert a ctypes pointer to a numpy array. The resulting NumPy array shares the memory with the pointer. Parameters ---------- cptr : ctypes.POINTER(mx_float) pointer to the memory region shape : tuple Shape of target `NDArray`. Re...
python
def ctypes2numpy_shared(cptr, shape): """Convert a ctypes pointer to a numpy array. The resulting NumPy array shares the memory with the pointer. Parameters ---------- cptr : ctypes.POINTER(mx_float) pointer to the memory region shape : tuple Shape of target `NDArray`. Re...
[ "def", "ctypes2numpy_shared", "(", "cptr", ",", "shape", ")", ":", "if", "not", "isinstance", "(", "cptr", ",", "ctypes", ".", "POINTER", "(", "mx_float", ")", ")", ":", "raise", "RuntimeError", "(", "'expected float pointer'", ")", "size", "=", "1", "for"...
Convert a ctypes pointer to a numpy array. The resulting NumPy array shares the memory with the pointer. Parameters ---------- cptr : ctypes.POINTER(mx_float) pointer to the memory region shape : tuple Shape of target `NDArray`. Returns ------- out : numpy_array ...
[ "Convert", "a", "ctypes", "pointer", "to", "a", "numpy", "array", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/base.py#L436-L460
train
apache/incubator-mxnet
python/mxnet/base.py
build_param_doc
def build_param_doc(arg_names, arg_types, arg_descs, remove_dup=True): """Build argument docs in python style. arg_names : list of str Argument names. arg_types : list of str Argument type information. arg_descs : list of str Argument description information. remove_dup :...
python
def build_param_doc(arg_names, arg_types, arg_descs, remove_dup=True): """Build argument docs in python style. arg_names : list of str Argument names. arg_types : list of str Argument type information. arg_descs : list of str Argument description information. remove_dup :...
[ "def", "build_param_doc", "(", "arg_names", ",", "arg_types", ",", "arg_descs", ",", "remove_dup", "=", "True", ")", ":", "param_keys", "=", "set", "(", ")", "param_str", "=", "[", "]", "for", "key", ",", "type_info", ",", "desc", "in", "zip", "(", "ar...
Build argument docs in python style. arg_names : list of str Argument names. arg_types : list of str Argument type information. arg_descs : list of str Argument description information. remove_dup : boolean, optional Whether remove duplication or not. Returns ...
[ "Build", "argument", "docs", "in", "python", "style", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/base.py#L463-L499
train
apache/incubator-mxnet
python/mxnet/base.py
add_fileline_to_docstring
def add_fileline_to_docstring(module, incursive=True): """Append the definition position to each function contained in module. Examples -------- # Put the following codes at the end of a file add_fileline_to_docstring(__name__) """ def _add_fileline(obj): """Add fileinto to a objec...
python
def add_fileline_to_docstring(module, incursive=True): """Append the definition position to each function contained in module. Examples -------- # Put the following codes at the end of a file add_fileline_to_docstring(__name__) """ def _add_fileline(obj): """Add fileinto to a objec...
[ "def", "add_fileline_to_docstring", "(", "module", ",", "incursive", "=", "True", ")", ":", "def", "_add_fileline", "(", "obj", ")", ":", "\"\"\"Add fileinto to a object.\n \"\"\"", "if", "obj", ".", "__doc__", "is", "None", "or", "'From:'", "in", "obj", ...
Append the definition position to each function contained in module. Examples -------- # Put the following codes at the end of a file add_fileline_to_docstring(__name__)
[ "Append", "the", "definition", "position", "to", "each", "function", "contained", "in", "module", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/base.py#L510-L543
train
apache/incubator-mxnet
python/mxnet/base.py
_init_op_module
def _init_op_module(root_namespace, module_name, make_op_func): """ Registers op functions created by `make_op_func` under `root_namespace.module_name.[submodule_name]`, where `submodule_name` is one of `_OP_SUBMODULE_NAME_LIST`. Parameters ---------- root_namespace : str Top level ...
python
def _init_op_module(root_namespace, module_name, make_op_func): """ Registers op functions created by `make_op_func` under `root_namespace.module_name.[submodule_name]`, where `submodule_name` is one of `_OP_SUBMODULE_NAME_LIST`. Parameters ---------- root_namespace : str Top level ...
[ "def", "_init_op_module", "(", "root_namespace", ",", "module_name", ",", "make_op_func", ")", ":", "plist", "=", "ctypes", ".", "POINTER", "(", "ctypes", ".", "c_char_p", ")", "(", ")", "size", "=", "ctypes", ".", "c_uint", "(", ")", "check_call", "(", ...
Registers op functions created by `make_op_func` under `root_namespace.module_name.[submodule_name]`, where `submodule_name` is one of `_OP_SUBMODULE_NAME_LIST`. Parameters ---------- root_namespace : str Top level module name, `mxnet` in the current cases. module_name : str Sec...
[ "Registers", "op", "functions", "created", "by", "make_op_func", "under", "root_namespace", ".", "module_name", ".", "[", "submodule_name", "]", "where", "submodule_name", "is", "one", "of", "_OP_SUBMODULE_NAME_LIST", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/base.py#L580-L648
train
apache/incubator-mxnet
python/mxnet/base.py
_generate_op_module_signature
def _generate_op_module_signature(root_namespace, module_name, op_code_gen_func): """ Generate op functions created by `op_code_gen_func` and write to the source file of `root_namespace.module_name.[submodule_name]`, where `submodule_name` is one of `_OP_SUBMODULE_NAME_LIST`. Parameters -------...
python
def _generate_op_module_signature(root_namespace, module_name, op_code_gen_func): """ Generate op functions created by `op_code_gen_func` and write to the source file of `root_namespace.module_name.[submodule_name]`, where `submodule_name` is one of `_OP_SUBMODULE_NAME_LIST`. Parameters -------...
[ "def", "_generate_op_module_signature", "(", "root_namespace", ",", "module_name", ",", "op_code_gen_func", ")", ":", "def", "get_module_file", "(", "module_name", ")", ":", "\"\"\"Return the generated module file based on module name.\"\"\"", "path", "=", "os", ".", "path"...
Generate op functions created by `op_code_gen_func` and write to the source file of `root_namespace.module_name.[submodule_name]`, where `submodule_name` is one of `_OP_SUBMODULE_NAME_LIST`. Parameters ---------- root_namespace : str Top level module name, `mxnet` in the current cases. ...
[ "Generate", "op", "functions", "created", "by", "op_code_gen_func", "and", "write", "to", "the", "source", "file", "of", "root_namespace", ".", "module_name", ".", "[", "submodule_name", "]", "where", "submodule_name", "is", "one", "of", "_OP_SUBMODULE_NAME_LIST", ...
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/base.py#L651-L734
train
apache/incubator-mxnet
python/mxnet/base.py
set_np_compat
def set_np_compat(active): """ Turns on/off NumPy compatibility. NumPy-compatibility is turned off by default in backend. Parameters ---------- active : bool Indicates whether to turn on/off NumPy compatibility. Returns ------- A bool value indicating the previous state of ...
python
def set_np_compat(active): """ Turns on/off NumPy compatibility. NumPy-compatibility is turned off by default in backend. Parameters ---------- active : bool Indicates whether to turn on/off NumPy compatibility. Returns ------- A bool value indicating the previous state of ...
[ "def", "set_np_compat", "(", "active", ")", ":", "prev", "=", "ctypes", ".", "c_int", "(", ")", "check_call", "(", "_LIB", ".", "MXSetIsNumpyCompatible", "(", "ctypes", ".", "c_int", "(", "active", ")", ",", "ctypes", ".", "byref", "(", "prev", ")", ")...
Turns on/off NumPy compatibility. NumPy-compatibility is turned off by default in backend. Parameters ---------- active : bool Indicates whether to turn on/off NumPy compatibility. Returns ------- A bool value indicating the previous state of NumPy compatibility.
[ "Turns", "on", "/", "off", "NumPy", "compatibility", ".", "NumPy", "-", "compatibility", "is", "turned", "off", "by", "default", "in", "backend", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/base.py#L740-L755
train
apache/incubator-mxnet
python/mxnet/base.py
is_np_compat
def is_np_compat(): """ Checks whether the NumPy compatibility is currently turned on. NumPy-compatibility is turned off by default in backend. Returns ------- A bool value indicating whether the NumPy compatibility is currently on. """ curr = ctypes.c_bool() check_call(_LIB.MXI...
python
def is_np_compat(): """ Checks whether the NumPy compatibility is currently turned on. NumPy-compatibility is turned off by default in backend. Returns ------- A bool value indicating whether the NumPy compatibility is currently on. """ curr = ctypes.c_bool() check_call(_LIB.MXI...
[ "def", "is_np_compat", "(", ")", ":", "curr", "=", "ctypes", ".", "c_bool", "(", ")", "check_call", "(", "_LIB", ".", "MXIsNumpyCompatible", "(", "ctypes", ".", "byref", "(", "curr", ")", ")", ")", "return", "curr", ".", "value" ]
Checks whether the NumPy compatibility is currently turned on. NumPy-compatibility is turned off by default in backend. Returns ------- A bool value indicating whether the NumPy compatibility is currently on.
[ "Checks", "whether", "the", "NumPy", "compatibility", "is", "currently", "turned", "on", ".", "NumPy", "-", "compatibility", "is", "turned", "off", "by", "default", "in", "backend", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/base.py#L758-L769
train
apache/incubator-mxnet
python/mxnet/base.py
use_np_compat
def use_np_compat(func): """Wraps a function with an activated NumPy-compatibility scope. This ensures that the execution of the function is guaranteed with NumPy compatible semantics, such as zero-dim and zero size tensors. Example:: import mxnet as mx @mx.use_np_compat def sca...
python
def use_np_compat(func): """Wraps a function with an activated NumPy-compatibility scope. This ensures that the execution of the function is guaranteed with NumPy compatible semantics, such as zero-dim and zero size tensors. Example:: import mxnet as mx @mx.use_np_compat def sca...
[ "def", "use_np_compat", "(", "func", ")", ":", "@", "wraps", "(", "func", ")", "def", "_with_np_compat", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "with", "np_compat", "(", "active", "=", "True", ")", ":", "return", "func", "(", "*", "ar...
Wraps a function with an activated NumPy-compatibility scope. This ensures that the execution of the function is guaranteed with NumPy compatible semantics, such as zero-dim and zero size tensors. Example:: import mxnet as mx @mx.use_np_compat def scalar_one(): return mx...
[ "Wraps", "a", "function", "with", "an", "activated", "NumPy", "-", "compatibility", "scope", ".", "This", "ensures", "that", "the", "execution", "of", "the", "function", "is", "guaranteed", "with", "NumPy", "compatible", "semantics", "such", "as", "zero", "-",...
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/base.py#L848-L874
train
apache/incubator-mxnet
example/multivariate_time_series/src/metrics.py
rse
def rse(label, pred): """computes the root relative squared error (condensed using standard deviation formula)""" numerator = np.sqrt(np.mean(np.square(label - pred), axis = None)) denominator = np.std(label, axis = None) return numerator / denominator
python
def rse(label, pred): """computes the root relative squared error (condensed using standard deviation formula)""" numerator = np.sqrt(np.mean(np.square(label - pred), axis = None)) denominator = np.std(label, axis = None) return numerator / denominator
[ "def", "rse", "(", "label", ",", "pred", ")", ":", "numerator", "=", "np", ".", "sqrt", "(", "np", ".", "mean", "(", "np", ".", "square", "(", "label", "-", "pred", ")", ",", "axis", "=", "None", ")", ")", "denominator", "=", "np", ".", "std", ...
computes the root relative squared error (condensed using standard deviation formula)
[ "computes", "the", "root", "relative", "squared", "error", "(", "condensed", "using", "standard", "deviation", "formula", ")" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/multivariate_time_series/src/metrics.py#L25-L29
train
apache/incubator-mxnet
example/multivariate_time_series/src/metrics.py
rae
def rae(label, pred): """computes the relative absolute error (condensed using standard deviation formula)""" numerator = np.mean(np.abs(label - pred), axis=None) denominator = np.mean(np.abs(label - np.mean(label, axis=None)), axis=None) return numerator / denominator
python
def rae(label, pred): """computes the relative absolute error (condensed using standard deviation formula)""" numerator = np.mean(np.abs(label - pred), axis=None) denominator = np.mean(np.abs(label - np.mean(label, axis=None)), axis=None) return numerator / denominator
[ "def", "rae", "(", "label", ",", "pred", ")", ":", "numerator", "=", "np", ".", "mean", "(", "np", ".", "abs", "(", "label", "-", "pred", ")", ",", "axis", "=", "None", ")", "denominator", "=", "np", ".", "mean", "(", "np", ".", "abs", "(", "...
computes the relative absolute error (condensed using standard deviation formula)
[ "computes", "the", "relative", "absolute", "error", "(", "condensed", "using", "standard", "deviation", "formula", ")" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/multivariate_time_series/src/metrics.py#L31-L35
train
apache/incubator-mxnet
example/multivariate_time_series/src/metrics.py
corr
def corr(label, pred): """computes the empirical correlation coefficient""" numerator1 = label - np.mean(label, axis=0) numerator2 = pred - np.mean(pred, axis = 0) numerator = np.mean(numerator1 * numerator2, axis=0) denominator = np.std(label, axis=0) * np.std(pred, axis=0) return np.mean(numer...
python
def corr(label, pred): """computes the empirical correlation coefficient""" numerator1 = label - np.mean(label, axis=0) numerator2 = pred - np.mean(pred, axis = 0) numerator = np.mean(numerator1 * numerator2, axis=0) denominator = np.std(label, axis=0) * np.std(pred, axis=0) return np.mean(numer...
[ "def", "corr", "(", "label", ",", "pred", ")", ":", "numerator1", "=", "label", "-", "np", ".", "mean", "(", "label", ",", "axis", "=", "0", ")", "numerator2", "=", "pred", "-", "np", ".", "mean", "(", "pred", ",", "axis", "=", "0", ")", "numer...
computes the empirical correlation coefficient
[ "computes", "the", "empirical", "correlation", "coefficient" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/multivariate_time_series/src/metrics.py#L37-L43
train
apache/incubator-mxnet
example/multivariate_time_series/src/metrics.py
get_custom_metrics
def get_custom_metrics(): """ :return: mxnet metric object """ _rse = mx.metric.create(rse) _rae = mx.metric.create(rae) _corr = mx.metric.create(corr) return mx.metric.create([_rae, _rse, _corr])
python
def get_custom_metrics(): """ :return: mxnet metric object """ _rse = mx.metric.create(rse) _rae = mx.metric.create(rae) _corr = mx.metric.create(corr) return mx.metric.create([_rae, _rse, _corr])
[ "def", "get_custom_metrics", "(", ")", ":", "_rse", "=", "mx", ".", "metric", ".", "create", "(", "rse", ")", "_rae", "=", "mx", ".", "metric", ".", "create", "(", "rae", ")", "_corr", "=", "mx", ".", "metric", ".", "create", "(", "corr", ")", "r...
:return: mxnet metric object
[ ":", "return", ":", "mxnet", "metric", "object" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/multivariate_time_series/src/metrics.py#L45-L52
train
apache/incubator-mxnet
example/ssd/tools/caffe_converter/convert_symbol.py
_get_input
def _get_input(proto): """Get input size """ layer = caffe_parser.get_layers(proto) if len(proto.input_dim) > 0: input_dim = proto.input_dim elif len(proto.input_shape) > 0: input_dim = proto.input_shape[0].dim elif layer[0].type == "Input": input_dim = layer[0].input_par...
python
def _get_input(proto): """Get input size """ layer = caffe_parser.get_layers(proto) if len(proto.input_dim) > 0: input_dim = proto.input_dim elif len(proto.input_shape) > 0: input_dim = proto.input_shape[0].dim elif layer[0].type == "Input": input_dim = layer[0].input_par...
[ "def", "_get_input", "(", "proto", ")", ":", "layer", "=", "caffe_parser", ".", "get_layers", "(", "proto", ")", "if", "len", "(", "proto", ".", "input_dim", ")", ">", "0", ":", "input_dim", "=", "proto", ".", "input_dim", "elif", "len", "(", "proto", ...
Get input size
[ "Get", "input", "size" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/ssd/tools/caffe_converter/convert_symbol.py#L23-L40
train
apache/incubator-mxnet
example/ssd/tools/caffe_converter/convert_symbol.py
_convert_conv_param
def _convert_conv_param(param): """ Convert convolution layer parameter from Caffe to MXNet """ param_string = "num_filter=%d" % param.num_output pad_w = 0 pad_h = 0 if isinstance(param.pad, int): pad = param.pad param_string += ", pad=(%d, %d)" % (pad, pad) else: ...
python
def _convert_conv_param(param): """ Convert convolution layer parameter from Caffe to MXNet """ param_string = "num_filter=%d" % param.num_output pad_w = 0 pad_h = 0 if isinstance(param.pad, int): pad = param.pad param_string += ", pad=(%d, %d)" % (pad, pad) else: ...
[ "def", "_convert_conv_param", "(", "param", ")", ":", "param_string", "=", "\"num_filter=%d\"", "%", "param", ".", "num_output", "pad_w", "=", "0", "pad_h", "=", "0", "if", "isinstance", "(", "param", ".", "pad", ",", "int", ")", ":", "pad", "=", "param"...
Convert convolution layer parameter from Caffe to MXNet
[ "Convert", "convolution", "layer", "parameter", "from", "Caffe", "to", "MXNet" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/ssd/tools/caffe_converter/convert_symbol.py#L42-L103
train
apache/incubator-mxnet
example/ssd/tools/caffe_converter/convert_symbol.py
_convert_pooling_param
def _convert_pooling_param(param): """Convert the pooling layer parameter """ param_string = "pooling_convention='full', " if param.global_pooling: param_string += "global_pool=True, kernel=(1,1)" else: param_string += "pad=(%d,%d), kernel=(%d,%d), stride=(%d,%d)" % ( par...
python
def _convert_pooling_param(param): """Convert the pooling layer parameter """ param_string = "pooling_convention='full', " if param.global_pooling: param_string += "global_pool=True, kernel=(1,1)" else: param_string += "pad=(%d,%d), kernel=(%d,%d), stride=(%d,%d)" % ( par...
[ "def", "_convert_pooling_param", "(", "param", ")", ":", "param_string", "=", "\"pooling_convention='full', \"", "if", "param", ".", "global_pooling", ":", "param_string", "+=", "\"global_pool=True, kernel=(1,1)\"", "else", ":", "param_string", "+=", "\"pad=(%d,%d), kernel=...
Convert the pooling layer parameter
[ "Convert", "the", "pooling", "layer", "parameter" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/ssd/tools/caffe_converter/convert_symbol.py#L105-L121
train
apache/incubator-mxnet
example/ssd/tools/caffe_converter/convert_symbol.py
_parse_proto
def _parse_proto(prototxt_fname): """Parse Caffe prototxt into symbol string """ proto = caffe_parser.read_prototxt(prototxt_fname) # process data layer input_name, input_dim, layers = _get_input(proto) # only support single input, so always use `data` as the input data mapping = {input_nam...
python
def _parse_proto(prototxt_fname): """Parse Caffe prototxt into symbol string """ proto = caffe_parser.read_prototxt(prototxt_fname) # process data layer input_name, input_dim, layers = _get_input(proto) # only support single input, so always use `data` as the input data mapping = {input_nam...
[ "def", "_parse_proto", "(", "prototxt_fname", ")", ":", "proto", "=", "caffe_parser", ".", "read_prototxt", "(", "prototxt_fname", ")", "# process data layer", "input_name", ",", "input_dim", ",", "layers", "=", "_get_input", "(", "proto", ")", "# only support singl...
Parse Caffe prototxt into symbol string
[ "Parse", "Caffe", "prototxt", "into", "symbol", "string" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/ssd/tools/caffe_converter/convert_symbol.py#L129-L359
train
apache/incubator-mxnet
example/ssd/tools/caffe_converter/convert_symbol.py
convert_symbol
def convert_symbol(prototxt_fname): """Convert caffe model definition into Symbol Parameters ---------- prototxt_fname : str Filename of the prototxt file Returns ------- Symbol Converted Symbol tuple Input shape """ sym, output_name, input_dim = _parse_...
python
def convert_symbol(prototxt_fname): """Convert caffe model definition into Symbol Parameters ---------- prototxt_fname : str Filename of the prototxt file Returns ------- Symbol Converted Symbol tuple Input shape """ sym, output_name, input_dim = _parse_...
[ "def", "convert_symbol", "(", "prototxt_fname", ")", ":", "sym", ",", "output_name", ",", "input_dim", "=", "_parse_proto", "(", "prototxt_fname", ")", "exec", "(", "sym", ")", "# pylint: disable=exec-used", "_locals", "=", "locals", "(", ")", "exec", "(", "\"...
Convert caffe model definition into Symbol Parameters ---------- prototxt_fname : str Filename of the prototxt file Returns ------- Symbol Converted Symbol tuple Input shape
[ "Convert", "caffe", "model", "definition", "into", "Symbol" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/ssd/tools/caffe_converter/convert_symbol.py#L361-L381
train
apache/incubator-mxnet
example/reinforcement-learning/parallel_actor_critic/train.py
train_episode
def train_episode(agent, envs, preprocessors, t_max, render): """Complete an episode's worth of training for each environment.""" num_envs = len(envs) # Buffers to hold trajectories, e.g. `env_xs[i]` will hold the observations # for environment `i`. env_xs, env_as = _2d_list(num_envs), _2d_list(num...
python
def train_episode(agent, envs, preprocessors, t_max, render): """Complete an episode's worth of training for each environment.""" num_envs = len(envs) # Buffers to hold trajectories, e.g. `env_xs[i]` will hold the observations # for environment `i`. env_xs, env_as = _2d_list(num_envs), _2d_list(num...
[ "def", "train_episode", "(", "agent", ",", "envs", ",", "preprocessors", ",", "t_max", ",", "render", ")", ":", "num_envs", "=", "len", "(", "envs", ")", "# Buffers to hold trajectories, e.g. `env_xs[i]` will hold the observations", "# for environment `i`.", "env_xs", "...
Complete an episode's worth of training for each environment.
[ "Complete", "an", "episode", "s", "worth", "of", "training", "for", "each", "environment", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/reinforcement-learning/parallel_actor_critic/train.py#L31-L113
train
apache/incubator-mxnet
example/ssd/tools/caffe_converter/caffe_parse/parse_from_protobuf.py
parse_caffemodel
def parse_caffemodel(file_path): """ parses the trained .caffemodel file filepath: /path/to/trained-model.caffemodel returns: layers """ f = open(file_path, 'rb') contents = f.read() net_param = caffe_pb2.NetParameter() net_param.ParseFromString(contents) layers = find_layers...
python
def parse_caffemodel(file_path): """ parses the trained .caffemodel file filepath: /path/to/trained-model.caffemodel returns: layers """ f = open(file_path, 'rb') contents = f.read() net_param = caffe_pb2.NetParameter() net_param.ParseFromString(contents) layers = find_layers...
[ "def", "parse_caffemodel", "(", "file_path", ")", ":", "f", "=", "open", "(", "file_path", ",", "'rb'", ")", "contents", "=", "f", ".", "read", "(", ")", "net_param", "=", "caffe_pb2", ".", "NetParameter", "(", ")", "net_param", ".", "ParseFromString", "...
parses the trained .caffemodel file filepath: /path/to/trained-model.caffemodel returns: layers
[ "parses", "the", "trained", ".", "caffemodel", "file" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/ssd/tools/caffe_converter/caffe_parse/parse_from_protobuf.py#L23-L38
train
apache/incubator-mxnet
example/speech_recognition/stt_datagenerator.py
DataGenerator.featurize
def featurize(self, audio_clip, overwrite=False, save_feature_as_csvfile=False): """ For a given audio clip, calculate the log of its Fourier Transform Params: audio_clip(str): Path to the audio clip """ return spectrogram_from_file( audio_clip, step=self.step, wi...
python
def featurize(self, audio_clip, overwrite=False, save_feature_as_csvfile=False): """ For a given audio clip, calculate the log of its Fourier Transform Params: audio_clip(str): Path to the audio clip """ return spectrogram_from_file( audio_clip, step=self.step, wi...
[ "def", "featurize", "(", "self", ",", "audio_clip", ",", "overwrite", "=", "False", ",", "save_feature_as_csvfile", "=", "False", ")", ":", "return", "spectrogram_from_file", "(", "audio_clip", ",", "step", "=", "self", ".", "step", ",", "window", "=", "self...
For a given audio clip, calculate the log of its Fourier Transform Params: audio_clip(str): Path to the audio clip
[ "For", "a", "given", "audio", "clip", "calculate", "the", "log", "of", "its", "Fourier", "Transform", "Params", ":", "audio_clip", "(", "str", ")", ":", "Path", "to", "the", "audio", "clip" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/speech_recognition/stt_datagenerator.py#L70-L78
train
apache/incubator-mxnet
example/speech_recognition/stt_datagenerator.py
DataGenerator.load_metadata_from_desc_file
def load_metadata_from_desc_file(self, desc_file, partition='train', max_duration=16.0,): """ Read metadata from the description file (possibly takes long, depending on the filesize) Params: desc_file (str): Path to a JSON-line file that cont...
python
def load_metadata_from_desc_file(self, desc_file, partition='train', max_duration=16.0,): """ Read metadata from the description file (possibly takes long, depending on the filesize) Params: desc_file (str): Path to a JSON-line file that cont...
[ "def", "load_metadata_from_desc_file", "(", "self", ",", "desc_file", ",", "partition", "=", "'train'", ",", "max_duration", "=", "16.0", ",", ")", ":", "logger", "=", "logUtil", ".", "getlogger", "(", ")", "logger", ".", "info", "(", "'Reading description fil...
Read metadata from the description file (possibly takes long, depending on the filesize) Params: desc_file (str): Path to a JSON-line file that contains labels and paths to the audio files partition (str): One of 'train', 'validation' or 'test' ma...
[ "Read", "metadata", "from", "the", "description", "file", "(", "possibly", "takes", "long", "depending", "on", "the", "filesize", ")", "Params", ":", "desc_file", "(", "str", ")", ":", "Path", "to", "a", "JSON", "-", "line", "file", "that", "contains", "...
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/speech_recognition/stt_datagenerator.py#L80-L128
train
apache/incubator-mxnet
example/speech_recognition/stt_datagenerator.py
DataGenerator.prepare_minibatch
def prepare_minibatch(self, audio_paths, texts, overwrite=False, is_bi_graphemes=False, seq_length=-1, save_feature_as_csvfile=False): """ Featurize a minibatch of audio, zero pad them and return a dictionary Params: audio_paths (list(str)): List of paths to audio f...
python
def prepare_minibatch(self, audio_paths, texts, overwrite=False, is_bi_graphemes=False, seq_length=-1, save_feature_as_csvfile=False): """ Featurize a minibatch of audio, zero pad them and return a dictionary Params: audio_paths (list(str)): List of paths to audio f...
[ "def", "prepare_minibatch", "(", "self", ",", "audio_paths", ",", "texts", ",", "overwrite", "=", "False", ",", "is_bi_graphemes", "=", "False", ",", "seq_length", "=", "-", "1", ",", "save_feature_as_csvfile", "=", "False", ")", ":", "assert", "len", "(", ...
Featurize a minibatch of audio, zero pad them and return a dictionary Params: audio_paths (list(str)): List of paths to audio files texts (list(str)): List of texts corresponding to the audio files Returns: dict: See below for contents
[ "Featurize", "a", "minibatch", "of", "audio", "zero", "pad", "them", "and", "return", "a", "dictionary", "Params", ":", "audio_paths", "(", "list", "(", "str", "))", ":", "List", "of", "paths", "to", "audio", "files", "texts", "(", "list", "(", "str", ...
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/speech_recognition/stt_datagenerator.py#L172-L216
train
apache/incubator-mxnet
example/speech_recognition/stt_datagenerator.py
DataGenerator.sample_normalize
def sample_normalize(self, k_samples=1000, overwrite=False): """ Estimate the mean and std of the features from the training set Params: k_samples (int): Use this number of samples for estimation """ log = logUtil.getlogger() log.info("Calculating mean and std from sa...
python
def sample_normalize(self, k_samples=1000, overwrite=False): """ Estimate the mean and std of the features from the training set Params: k_samples (int): Use this number of samples for estimation """ log = logUtil.getlogger() log.info("Calculating mean and std from sa...
[ "def", "sample_normalize", "(", "self", ",", "k_samples", "=", "1000", ",", "overwrite", "=", "False", ")", ":", "log", "=", "logUtil", ".", "getlogger", "(", ")", "log", ".", "info", "(", "\"Calculating mean and std from samples\"", ")", "# if k_samples is nega...
Estimate the mean and std of the features from the training set Params: k_samples (int): Use this number of samples for estimation
[ "Estimate", "the", "mean", "and", "std", "of", "the", "features", "from", "the", "training", "set", "Params", ":", "k_samples", "(", "int", ")", ":", "Use", "this", "number", "of", "samples", "for", "estimation" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/speech_recognition/stt_datagenerator.py#L245-L281
train
apache/incubator-mxnet
example/speech_recognition/stt_layer_gru.py
gru
def gru(num_hidden, indata, prev_state, param, seqidx, layeridx, dropout=0., is_batchnorm=False, gamma=None, beta=None, name=None): """ GRU Cell symbol Reference: * Chung, Junyoung, et al. "Empirical evaluation of gated recurrent neural networks on sequence modeling." arXiv preprint arXiv:1412.3...
python
def gru(num_hidden, indata, prev_state, param, seqidx, layeridx, dropout=0., is_batchnorm=False, gamma=None, beta=None, name=None): """ GRU Cell symbol Reference: * Chung, Junyoung, et al. "Empirical evaluation of gated recurrent neural networks on sequence modeling." arXiv preprint arXiv:1412.3...
[ "def", "gru", "(", "num_hidden", ",", "indata", ",", "prev_state", ",", "param", ",", "seqidx", ",", "layeridx", ",", "dropout", "=", "0.", ",", "is_batchnorm", "=", "False", ",", "gamma", "=", "None", ",", "beta", "=", "None", ",", "name", "=", "Non...
GRU Cell symbol Reference: * Chung, Junyoung, et al. "Empirical evaluation of gated recurrent neural networks on sequence modeling." arXiv preprint arXiv:1412.3555 (2014).
[ "GRU", "Cell", "symbol", "Reference", ":", "*", "Chung", "Junyoung", "et", "al", ".", "Empirical", "evaluation", "of", "gated", "recurrent", "neural", "networks", "on", "sequence", "modeling", ".", "arXiv", "preprint", "arXiv", ":", "1412", ".", "3555", "(",...
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/speech_recognition/stt_layer_gru.py#L35-L80
train
apache/incubator-mxnet
example/gluon/sn_gan/utils.py
save_image
def save_image(data, epoch, image_size, batch_size, output_dir, padding=2): """ save image """ data = data.asnumpy().transpose((0, 2, 3, 1)) datanp = np.clip( (data - np.min(data))*(255.0/(np.max(data) - np.min(data))), 0, 255).astype(np.uint8) x_dim = min(8, batch_size) y_dim = int(math.cei...
python
def save_image(data, epoch, image_size, batch_size, output_dir, padding=2): """ save image """ data = data.asnumpy().transpose((0, 2, 3, 1)) datanp = np.clip( (data - np.min(data))*(255.0/(np.max(data) - np.min(data))), 0, 255).astype(np.uint8) x_dim = min(8, batch_size) y_dim = int(math.cei...
[ "def", "save_image", "(", "data", ",", "epoch", ",", "image_size", ",", "batch_size", ",", "output_dir", ",", "padding", "=", "2", ")", ":", "data", "=", "data", ".", "asnumpy", "(", ")", ".", "transpose", "(", "(", "0", ",", "2", ",", "3", ",", ...
save image
[ "save", "image" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/gluon/sn_gan/utils.py#L27-L49
train
apache/incubator-mxnet
tools/im2rec.py
list_image
def list_image(root, recursive, exts): """Traverses the root of directory that contains images and generates image list iterator. Parameters ---------- root: string recursive: bool exts: string Returns ------- image iterator that contains all the image under the specified path ...
python
def list_image(root, recursive, exts): """Traverses the root of directory that contains images and generates image list iterator. Parameters ---------- root: string recursive: bool exts: string Returns ------- image iterator that contains all the image under the specified path ...
[ "def", "list_image", "(", "root", ",", "recursive", ",", "exts", ")", ":", "i", "=", "0", "if", "recursive", ":", "cat", "=", "{", "}", "for", "path", ",", "dirs", ",", "files", "in", "os", ".", "walk", "(", "root", ",", "followlinks", "=", "True...
Traverses the root of directory that contains images and generates image list iterator. Parameters ---------- root: string recursive: bool exts: string Returns ------- image iterator that contains all the image under the specified path
[ "Traverses", "the", "root", "of", "directory", "that", "contains", "images", "and", "generates", "image", "list", "iterator", ".", "Parameters", "----------", "root", ":", "string", "recursive", ":", "bool", "exts", ":", "string", "Returns", "-------", "image", ...
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/tools/im2rec.py#L38-L73
train
apache/incubator-mxnet
tools/im2rec.py
write_list
def write_list(path_out, image_list): """Hepler function to write image list into the file. The format is as below, integer_image_index \t float_label_index \t path_to_image Note that the blank between number and tab is only used for readability. Parameters ---------- path_out: string im...
python
def write_list(path_out, image_list): """Hepler function to write image list into the file. The format is as below, integer_image_index \t float_label_index \t path_to_image Note that the blank between number and tab is only used for readability. Parameters ---------- path_out: string im...
[ "def", "write_list", "(", "path_out", ",", "image_list", ")", ":", "with", "open", "(", "path_out", ",", "'w'", ")", "as", "fout", ":", "for", "i", ",", "item", "in", "enumerate", "(", "image_list", ")", ":", "line", "=", "'%d\\t'", "%", "item", "[",...
Hepler function to write image list into the file. The format is as below, integer_image_index \t float_label_index \t path_to_image Note that the blank between number and tab is only used for readability. Parameters ---------- path_out: string image_list: list
[ "Hepler", "function", "to", "write", "image", "list", "into", "the", "file", ".", "The", "format", "is", "as", "below", "integer_image_index", "\\", "t", "float_label_index", "\\", "t", "path_to_image", "Note", "that", "the", "blank", "between", "number", "and...
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/tools/im2rec.py#L75-L91
train
apache/incubator-mxnet
tools/im2rec.py
make_list
def make_list(args): """Generates .lst file. Parameters ---------- args: object that contains all the arguments """ image_list = list_image(args.root, args.recursive, args.exts) image_list = list(image_list) if args.shuffle is True: random.seed(100) random.shuffle(image_l...
python
def make_list(args): """Generates .lst file. Parameters ---------- args: object that contains all the arguments """ image_list = list_image(args.root, args.recursive, args.exts) image_list = list(image_list) if args.shuffle is True: random.seed(100) random.shuffle(image_l...
[ "def", "make_list", "(", "args", ")", ":", "image_list", "=", "list_image", "(", "args", ".", "root", ",", "args", ".", "recursive", ",", "args", ".", "exts", ")", "image_list", "=", "list", "(", "image_list", ")", "if", "args", ".", "shuffle", "is", ...
Generates .lst file. Parameters ---------- args: object that contains all the arguments
[ "Generates", ".", "lst", "file", ".", "Parameters", "----------", "args", ":", "object", "that", "contains", "all", "the", "arguments" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/tools/im2rec.py#L93-L121
train
apache/incubator-mxnet
tools/im2rec.py
read_list
def read_list(path_in): """Reads the .lst file and generates corresponding iterator. Parameters ---------- path_in: string Returns ------- item iterator that contains information in .lst file """ with open(path_in) as fin: while True: line = fin.readline() ...
python
def read_list(path_in): """Reads the .lst file and generates corresponding iterator. Parameters ---------- path_in: string Returns ------- item iterator that contains information in .lst file """ with open(path_in) as fin: while True: line = fin.readline() ...
[ "def", "read_list", "(", "path_in", ")", ":", "with", "open", "(", "path_in", ")", "as", "fin", ":", "while", "True", ":", "line", "=", "fin", ".", "readline", "(", ")", "if", "not", "line", ":", "break", "line", "=", "[", "i", ".", "strip", "(",...
Reads the .lst file and generates corresponding iterator. Parameters ---------- path_in: string Returns ------- item iterator that contains information in .lst file
[ "Reads", "the", ".", "lst", "file", "and", "generates", "corresponding", "iterator", ".", "Parameters", "----------", "path_in", ":", "string", "Returns", "-------", "item", "iterator", "that", "contains", "information", "in", ".", "lst", "file" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/tools/im2rec.py#L123-L148
train
apache/incubator-mxnet
tools/im2rec.py
image_encode
def image_encode(args, i, item, q_out): """Reads, preprocesses, packs the image and put it back in output queue. Parameters ---------- args: object i: int item: list q_out: queue """ fullpath = os.path.join(args.root, item[1]) if len(item) > 3 and args.pack_label: header...
python
def image_encode(args, i, item, q_out): """Reads, preprocesses, packs the image and put it back in output queue. Parameters ---------- args: object i: int item: list q_out: queue """ fullpath = os.path.join(args.root, item[1]) if len(item) > 3 and args.pack_label: header...
[ "def", "image_encode", "(", "args", ",", "i", ",", "item", ",", "q_out", ")", ":", "fullpath", "=", "os", ".", "path", ".", "join", "(", "args", ".", "root", ",", "item", "[", "1", "]", ")", "if", "len", "(", "item", ")", ">", "3", "and", "ar...
Reads, preprocesses, packs the image and put it back in output queue. Parameters ---------- args: object i: int item: list q_out: queue
[ "Reads", "preprocesses", "packs", "the", "image", "and", "put", "it", "back", "in", "output", "queue", ".", "Parameters", "----------", "args", ":", "object", "i", ":", "int", "item", ":", "list", "q_out", ":", "queue" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/tools/im2rec.py#L150-L210
train
apache/incubator-mxnet
tools/im2rec.py
read_worker
def read_worker(args, q_in, q_out): """Function that will be spawned to fetch the image from the input queue and put it back to output queue. Parameters ---------- args: object q_in: queue q_out: queue """ while True: deq = q_in.get() if deq is None: break...
python
def read_worker(args, q_in, q_out): """Function that will be spawned to fetch the image from the input queue and put it back to output queue. Parameters ---------- args: object q_in: queue q_out: queue """ while True: deq = q_in.get() if deq is None: break...
[ "def", "read_worker", "(", "args", ",", "q_in", ",", "q_out", ")", ":", "while", "True", ":", "deq", "=", "q_in", ".", "get", "(", ")", "if", "deq", "is", "None", ":", "break", "i", ",", "item", "=", "deq", "image_encode", "(", "args", ",", "i", ...
Function that will be spawned to fetch the image from the input queue and put it back to output queue. Parameters ---------- args: object q_in: queue q_out: queue
[ "Function", "that", "will", "be", "spawned", "to", "fetch", "the", "image", "from", "the", "input", "queue", "and", "put", "it", "back", "to", "output", "queue", ".", "Parameters", "----------", "args", ":", "object", "q_in", ":", "queue", "q_out", ":", ...
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/tools/im2rec.py#L212-L226
train
apache/incubator-mxnet
tools/im2rec.py
write_worker
def write_worker(q_out, fname, working_dir): """Function that will be spawned to fetch processed image from the output queue and write to the .rec file. Parameters ---------- q_out: queue fname: string working_dir: string """ pre_time = time.time() count = 0 fname = os.path.b...
python
def write_worker(q_out, fname, working_dir): """Function that will be spawned to fetch processed image from the output queue and write to the .rec file. Parameters ---------- q_out: queue fname: string working_dir: string """ pre_time = time.time() count = 0 fname = os.path.b...
[ "def", "write_worker", "(", "q_out", ",", "fname", ",", "working_dir", ")", ":", "pre_time", "=", "time", ".", "time", "(", ")", "count", "=", "0", "fname", "=", "os", ".", "path", ".", "basename", "(", "fname", ")", "fname_rec", "=", "os", ".", "p...
Function that will be spawned to fetch processed image from the output queue and write to the .rec file. Parameters ---------- q_out: queue fname: string working_dir: string
[ "Function", "that", "will", "be", "spawned", "to", "fetch", "processed", "image", "from", "the", "output", "queue", "and", "write", "to", "the", ".", "rec", "file", ".", "Parameters", "----------", "q_out", ":", "queue", "fname", ":", "string", "working_dir"...
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/tools/im2rec.py#L228-L263
train
apache/incubator-mxnet
tools/im2rec.py
parse_args
def parse_args(): """Defines all arguments. Returns ------- args object that contains all the params """ parser = argparse.ArgumentParser( formatter_class=argparse.ArgumentDefaultsHelpFormatter, description='Create an image list or \ make a record database by reading from...
python
def parse_args(): """Defines all arguments. Returns ------- args object that contains all the params """ parser = argparse.ArgumentParser( formatter_class=argparse.ArgumentDefaultsHelpFormatter, description='Create an image list or \ make a record database by reading from...
[ "def", "parse_args", "(", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "formatter_class", "=", "argparse", ".", "ArgumentDefaultsHelpFormatter", ",", "description", "=", "'Create an image list or \\\n make a record database by reading from an image li...
Defines all arguments. Returns ------- args object that contains all the params
[ "Defines", "all", "arguments", ".", "Returns", "-------", "args", "object", "that", "contains", "all", "the", "params" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/tools/im2rec.py#L265-L323
train
apache/incubator-mxnet
example/gluon/embedding_learning/data.py
transform
def transform(data, target_wd, target_ht, is_train, box): """Crop and normnalize an image nd array.""" if box is not None: x, y, w, h = box data = data[y:min(y+h, data.shape[0]), x:min(x+w, data.shape[1])] # Resize to target_wd * target_ht. data = mx.image.imresize(data, target_wd, targ...
python
def transform(data, target_wd, target_ht, is_train, box): """Crop and normnalize an image nd array.""" if box is not None: x, y, w, h = box data = data[y:min(y+h, data.shape[0]), x:min(x+w, data.shape[1])] # Resize to target_wd * target_ht. data = mx.image.imresize(data, target_wd, targ...
[ "def", "transform", "(", "data", ",", "target_wd", ",", "target_ht", ",", "is_train", ",", "box", ")", ":", "if", "box", "is", "not", "None", ":", "x", ",", "y", ",", "w", ",", "h", "=", "box", "data", "=", "data", "[", "y", ":", "min", "(", ...
Crop and normnalize an image nd array.
[ "Crop", "and", "normnalize", "an", "image", "nd", "array", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/gluon/embedding_learning/data.py#L26-L53
train
apache/incubator-mxnet
example/gluon/embedding_learning/data.py
cub200_iterator
def cub200_iterator(data_path, batch_k, batch_size, data_shape): """Return training and testing iterator for the CUB200-2011 dataset.""" return (CUB200Iter(data_path, batch_k, batch_size, data_shape, is_train=True), CUB200Iter(data_path, batch_k, batch_size, data_shape, is_train=False))
python
def cub200_iterator(data_path, batch_k, batch_size, data_shape): """Return training and testing iterator for the CUB200-2011 dataset.""" return (CUB200Iter(data_path, batch_k, batch_size, data_shape, is_train=True), CUB200Iter(data_path, batch_k, batch_size, data_shape, is_train=False))
[ "def", "cub200_iterator", "(", "data_path", ",", "batch_k", ",", "batch_size", ",", "data_shape", ")", ":", "return", "(", "CUB200Iter", "(", "data_path", ",", "batch_k", ",", "batch_size", ",", "data_shape", ",", "is_train", "=", "True", ")", ",", "CUB200It...
Return training and testing iterator for the CUB200-2011 dataset.
[ "Return", "training", "and", "testing", "iterator", "for", "the", "CUB200", "-", "2011", "dataset", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/gluon/embedding_learning/data.py#L155-L158
train
apache/incubator-mxnet
example/gluon/embedding_learning/data.py
CUB200Iter.get_image
def get_image(self, img, is_train): """Load and transform an image.""" img_arr = mx.image.imread(img) img_arr = transform(img_arr, 256, 256, is_train, self.boxes[img]) return img_arr
python
def get_image(self, img, is_train): """Load and transform an image.""" img_arr = mx.image.imread(img) img_arr = transform(img_arr, 256, 256, is_train, self.boxes[img]) return img_arr
[ "def", "get_image", "(", "self", ",", "img", ",", "is_train", ")", ":", "img_arr", "=", "mx", ".", "image", ".", "imread", "(", "img", ")", "img_arr", "=", "transform", "(", "img_arr", ",", "256", ",", "256", ",", "is_train", ",", "self", ".", "box...
Load and transform an image.
[ "Load", "and", "transform", "an", "image", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/gluon/embedding_learning/data.py#L105-L109
train
apache/incubator-mxnet
example/gluon/embedding_learning/data.py
CUB200Iter.sample_train_batch
def sample_train_batch(self): """Sample a training batch (data and label).""" batch = [] labels = [] num_groups = self.batch_size // self.batch_k # For CUB200, we use the first 100 classes for training. sampled_classes = np.random.choice(100, num_groups, replace=False) ...
python
def sample_train_batch(self): """Sample a training batch (data and label).""" batch = [] labels = [] num_groups = self.batch_size // self.batch_k # For CUB200, we use the first 100 classes for training. sampled_classes = np.random.choice(100, num_groups, replace=False) ...
[ "def", "sample_train_batch", "(", "self", ")", ":", "batch", "=", "[", "]", "labels", "=", "[", "]", "num_groups", "=", "self", ".", "batch_size", "//", "self", ".", "batch_k", "# For CUB200, we use the first 100 classes for training.", "sampled_classes", "=", "np...
Sample a training batch (data and label).
[ "Sample", "a", "training", "batch", "(", "data", "and", "label", ")", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/gluon/embedding_learning/data.py#L111-L125
train
apache/incubator-mxnet
example/gluon/embedding_learning/data.py
CUB200Iter.next
def next(self): """Return a batch.""" if self.is_train: data, labels = self.sample_train_batch() else: if self.test_count * self.batch_size < len(self.test_image_files): data, labels = self.get_test_batch() self.test_count += 1 ...
python
def next(self): """Return a batch.""" if self.is_train: data, labels = self.sample_train_batch() else: if self.test_count * self.batch_size < len(self.test_image_files): data, labels = self.get_test_batch() self.test_count += 1 ...
[ "def", "next", "(", "self", ")", ":", "if", "self", ".", "is_train", ":", "data", ",", "labels", "=", "self", ".", "sample_train_batch", "(", ")", "else", ":", "if", "self", ".", "test_count", "*", "self", ".", "batch_size", "<", "len", "(", "self", ...
Return a batch.
[ "Return", "a", "batch", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/gluon/embedding_learning/data.py#L142-L153
train
apache/incubator-mxnet
example/bayesian-methods/data_loader.py
load_mnist
def load_mnist(training_num=50000): """Load mnist dataset""" data_path = os.path.join(os.path.dirname(os.path.realpath('__file__')), 'mnist.npz') if not os.path.isfile(data_path): from six.moves import urllib origin = ( 'https://github.com/sxjscience/mxnet/raw/master/example/baye...
python
def load_mnist(training_num=50000): """Load mnist dataset""" data_path = os.path.join(os.path.dirname(os.path.realpath('__file__')), 'mnist.npz') if not os.path.isfile(data_path): from six.moves import urllib origin = ( 'https://github.com/sxjscience/mxnet/raw/master/example/baye...
[ "def", "load_mnist", "(", "training_num", "=", "50000", ")", ":", "data_path", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "os", ".", "path", ".", "realpath", "(", "'__file__'", ")", ")", ",", "'mnist.npz'", ")",...
Load mnist dataset
[ "Load", "mnist", "dataset" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/bayesian-methods/data_loader.py#L24-L44
train
apache/incubator-mxnet
python/mxnet/runtime.py
feature_list
def feature_list(): """ Check the library for compile-time features. The list of features are maintained in libinfo.h and libinfo.cc Returns ------- list List of :class:`.Feature` objects """ lib_features_c_array = ctypes.POINTER(Feature)() lib_features_size = ctypes.c_size_t() ...
python
def feature_list(): """ Check the library for compile-time features. The list of features are maintained in libinfo.h and libinfo.cc Returns ------- list List of :class:`.Feature` objects """ lib_features_c_array = ctypes.POINTER(Feature)() lib_features_size = ctypes.c_size_t() ...
[ "def", "feature_list", "(", ")", ":", "lib_features_c_array", "=", "ctypes", ".", "POINTER", "(", "Feature", ")", "(", ")", "lib_features_size", "=", "ctypes", ".", "c_size_t", "(", ")", "check_call", "(", "_LIB", ".", "MXLibInfoFeatures", "(", "ctypes", "."...
Check the library for compile-time features. The list of features are maintained in libinfo.h and libinfo.cc Returns ------- list List of :class:`.Feature` objects
[ "Check", "the", "library", "for", "compile", "-", "time", "features", ".", "The", "list", "of", "features", "are", "maintained", "in", "libinfo", ".", "h", "and", "libinfo", ".", "cc" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/runtime.py#L57-L70
train
apache/incubator-mxnet
python/mxnet/runtime.py
Features.is_enabled
def is_enabled(self, feature_name): """ Check for a particular feature by name Parameters ---------- feature_name: str The name of a valid feature as string for example 'CUDA' Returns ------- Boolean True if it's enabled, False if...
python
def is_enabled(self, feature_name): """ Check for a particular feature by name Parameters ---------- feature_name: str The name of a valid feature as string for example 'CUDA' Returns ------- Boolean True if it's enabled, False if...
[ "def", "is_enabled", "(", "self", ",", "feature_name", ")", ":", "feature_name", "=", "feature_name", ".", "upper", "(", ")", "if", "feature_name", "not", "in", "self", ":", "raise", "RuntimeError", "(", "\"Feature '{}' is unknown, known features are: {}\"", ".", ...
Check for a particular feature by name Parameters ---------- feature_name: str The name of a valid feature as string for example 'CUDA' Returns ------- Boolean True if it's enabled, False if it's disabled, RuntimeError if the feature is not known
[ "Check", "for", "a", "particular", "feature", "by", "name" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/runtime.py#L82-L100
train
apache/incubator-mxnet
example/ssd/dataset/pascal_voc.py
PascalVoc.cache_path
def cache_path(self): """ make a directory to store all caches Returns: --------- cache path """ cache_path = os.path.join(os.path.dirname(__file__), '..', 'cache') if not os.path.exists(cache_path): os.mkdir(cache_path) return cac...
python
def cache_path(self): """ make a directory to store all caches Returns: --------- cache path """ cache_path = os.path.join(os.path.dirname(__file__), '..', 'cache') if not os.path.exists(cache_path): os.mkdir(cache_path) return cac...
[ "def", "cache_path", "(", "self", ")", ":", "cache_path", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "__file__", ")", ",", "'..'", ",", "'cache'", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "ca...
make a directory to store all caches Returns: --------- cache path
[ "make", "a", "directory", "to", "store", "all", "caches" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/ssd/dataset/pascal_voc.py#L67-L78
train
apache/incubator-mxnet
example/ssd/dataset/pascal_voc.py
PascalVoc._load_image_set_index
def _load_image_set_index(self, shuffle): """ find out which indexes correspond to given image set (train or val) Parameters: ---------- shuffle : boolean whether to shuffle the image list Returns: ---------- entire list of images specified in...
python
def _load_image_set_index(self, shuffle): """ find out which indexes correspond to given image set (train or val) Parameters: ---------- shuffle : boolean whether to shuffle the image list Returns: ---------- entire list of images specified in...
[ "def", "_load_image_set_index", "(", "self", ",", "shuffle", ")", ":", "image_set_index_file", "=", "os", ".", "path", ".", "join", "(", "self", ".", "data_path", ",", "'ImageSets'", ",", "'Main'", ",", "self", ".", "image_set", "+", "'.txt'", ")", "assert...
find out which indexes correspond to given image set (train or val) Parameters: ---------- shuffle : boolean whether to shuffle the image list Returns: ---------- entire list of images specified in the setting
[ "find", "out", "which", "indexes", "correspond", "to", "given", "image", "set", "(", "train", "or", "val", ")" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/ssd/dataset/pascal_voc.py#L80-L98
train
apache/incubator-mxnet
example/ssd/dataset/pascal_voc.py
PascalVoc.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 No...
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 No...
[ "def", "image_path_from_index", "(", "self", ",", "index", ")", ":", "assert", "self", ".", "image_set_index", "is", "not", "None", ",", "\"Dataset not initialized\"", "name", "=", "self", ".", "image_set_index", "[", "index", "]", "image_file", "=", "os", "."...
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/pascal_voc.py#L100-L116
train
apache/incubator-mxnet
example/ssd/dataset/pascal_voc.py
PascalVoc._label_path_from_index
def _label_path_from_index(self, index): """ given image index, find out annotation path Parameters: ---------- index: int index of a specific image Returns: ---------- full path of annotation file """ label_file = os.path.joi...
python
def _label_path_from_index(self, index): """ given image index, find out annotation path Parameters: ---------- index: int index of a specific image Returns: ---------- full path of annotation file """ label_file = os.path.joi...
[ "def", "_label_path_from_index", "(", "self", ",", "index", ")", ":", "label_file", "=", "os", ".", "path", ".", "join", "(", "self", ".", "data_path", ",", "'Annotations'", ",", "index", "+", "'.xml'", ")", "assert", "os", ".", "path", ".", "exists", ...
given image index, find out annotation path Parameters: ---------- index: int index of a specific image Returns: ---------- full path of annotation file
[ "given", "image", "index", "find", "out", "annotation", "path" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/ssd/dataset/pascal_voc.py#L133-L148
train
apache/incubator-mxnet
example/ssd/dataset/pascal_voc.py
PascalVoc._load_image_labels
def _load_image_labels(self): """ preprocess all ground-truths Returns: ---------- labels packed in [num_images x max_num_objects x 5] tensor """ temp = [] # load ground-truth from xml annotations for idx in self.image_set_index: labe...
python
def _load_image_labels(self): """ preprocess all ground-truths Returns: ---------- labels packed in [num_images x max_num_objects x 5] tensor """ temp = [] # load ground-truth from xml annotations for idx in self.image_set_index: labe...
[ "def", "_load_image_labels", "(", "self", ")", ":", "temp", "=", "[", "]", "# load ground-truth from xml annotations", "for", "idx", "in", "self", ".", "image_set_index", ":", "label_file", "=", "self", ".", "_label_path_from_index", "(", "idx", ")", "tree", "="...
preprocess all ground-truths Returns: ---------- labels packed in [num_images x max_num_objects x 5] tensor
[ "preprocess", "all", "ground", "-", "truths" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/ssd/dataset/pascal_voc.py#L150-L185
train
apache/incubator-mxnet
example/ssd/dataset/pascal_voc.py
PascalVoc.evaluate_detections
def evaluate_detections(self, detections): """ top level evaluations Parameters: ---------- detections: list result list, each entry is a matrix of detections Returns: ---------- None """ # make all these folders for results...
python
def evaluate_detections(self, detections): """ top level evaluations Parameters: ---------- detections: list result list, each entry is a matrix of detections Returns: ---------- None """ # make all these folders for results...
[ "def", "evaluate_detections", "(", "self", ",", "detections", ")", ":", "# make all these folders for results", "result_dir", "=", "os", ".", "path", ".", "join", "(", "self", ".", "devkit_path", ",", "'results'", ")", "if", "not", "os", ".", "path", ".", "e...
top level evaluations Parameters: ---------- detections: list result list, each entry is a matrix of detections Returns: ---------- None
[ "top", "level", "evaluations", "Parameters", ":", "----------", "detections", ":", "list", "result", "list", "each", "entry", "is", "a", "matrix", "of", "detections", "Returns", ":", "----------", "None" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/ssd/dataset/pascal_voc.py#L187-L210
train
apache/incubator-mxnet
example/ssd/dataset/pascal_voc.py
PascalVoc.get_result_file_template
def get_result_file_template(self): """ this is a template VOCdevkit/results/VOC2007/Main/<comp_id>_det_test_aeroplane.txt Returns: ---------- a string template """ res_file_folder = os.path.join(self.devkit_path, 'results', 'VOC' + self.year, 'Main')...
python
def get_result_file_template(self): """ this is a template VOCdevkit/results/VOC2007/Main/<comp_id>_det_test_aeroplane.txt Returns: ---------- a string template """ res_file_folder = os.path.join(self.devkit_path, 'results', 'VOC' + self.year, 'Main')...
[ "def", "get_result_file_template", "(", "self", ")", ":", "res_file_folder", "=", "os", ".", "path", ".", "join", "(", "self", ".", "devkit_path", ",", "'results'", ",", "'VOC'", "+", "self", ".", "year", ",", "'Main'", ")", "comp_id", "=", "self", ".", ...
this is a template VOCdevkit/results/VOC2007/Main/<comp_id>_det_test_aeroplane.txt Returns: ---------- a string template
[ "this", "is", "a", "template", "VOCdevkit", "/", "results", "/", "VOC2007", "/", "Main", "/", "<comp_id", ">", "_det_test_aeroplane", ".", "txt" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/ssd/dataset/pascal_voc.py#L212-L225
train
apache/incubator-mxnet
example/ssd/dataset/pascal_voc.py
PascalVoc.write_pascal_results
def write_pascal_results(self, all_boxes): """ write results files in pascal devkit path Parameters: ---------- all_boxes: list boxes to be processed [bbox, confidence] Returns: ---------- None """ for cls_ind, cls in enumerate(...
python
def write_pascal_results(self, all_boxes): """ write results files in pascal devkit path Parameters: ---------- all_boxes: list boxes to be processed [bbox, confidence] Returns: ---------- None """ for cls_ind, cls in enumerate(...
[ "def", "write_pascal_results", "(", "self", ",", "all_boxes", ")", ":", "for", "cls_ind", ",", "cls", "in", "enumerate", "(", "self", ".", "classes", ")", ":", "print", "(", "'Writing {} VOC results file'", ".", "format", "(", "cls", ")", ")", "filename", ...
write results files in pascal devkit path Parameters: ---------- all_boxes: list boxes to be processed [bbox, confidence] Returns: ---------- None
[ "write", "results", "files", "in", "pascal", "devkit", "path", "Parameters", ":", "----------", "all_boxes", ":", "list", "boxes", "to", "be", "processed", "[", "bbox", "confidence", "]", "Returns", ":", "----------", "None" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/ssd/dataset/pascal_voc.py#L227-L253
train
apache/incubator-mxnet
example/ssd/dataset/pascal_voc.py
PascalVoc.do_python_eval
def do_python_eval(self): """ python evaluation wrapper Returns: ---------- None """ annopath = os.path.join(self.data_path, 'Annotations', '{:s}.xml') imageset_file = os.path.join(self.data_path, 'ImageSets', 'Main', self.image_set + '.txt') cach...
python
def do_python_eval(self): """ python evaluation wrapper Returns: ---------- None """ annopath = os.path.join(self.data_path, 'Annotations', '{:s}.xml') imageset_file = os.path.join(self.data_path, 'ImageSets', 'Main', self.image_set + '.txt') cach...
[ "def", "do_python_eval", "(", "self", ")", ":", "annopath", "=", "os", ".", "path", ".", "join", "(", "self", ".", "data_path", ",", "'Annotations'", ",", "'{:s}.xml'", ")", "imageset_file", "=", "os", ".", "path", ".", "join", "(", "self", ".", "data_...
python evaluation wrapper Returns: ---------- None
[ "python", "evaluation", "wrapper" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/ssd/dataset/pascal_voc.py#L255-L276
train
apache/incubator-mxnet
example/ssd/dataset/pascal_voc.py
PascalVoc._get_imsize
def _get_imsize(self, im_name): """ get image size info Returns: ---------- tuple of (height, width) """ img = cv2.imread(im_name) return (img.shape[0], img.shape[1])
python
def _get_imsize(self, im_name): """ get image size info Returns: ---------- tuple of (height, width) """ img = cv2.imread(im_name) return (img.shape[0], img.shape[1])
[ "def", "_get_imsize", "(", "self", ",", "im_name", ")", ":", "img", "=", "cv2", ".", "imread", "(", "im_name", ")", "return", "(", "img", ".", "shape", "[", "0", "]", ",", "img", ".", "shape", "[", "1", "]", ")" ]
get image size info Returns: ---------- tuple of (height, width)
[ "get", "image", "size", "info", "Returns", ":", "----------", "tuple", "of", "(", "height", "width", ")" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/ssd/dataset/pascal_voc.py#L278-L286
train
apache/incubator-mxnet
example/image-classification/common/fit.py
add_fit_args
def add_fit_args(parser): """ parser : argparse.ArgumentParser return a parser added with args required by fit """ train = parser.add_argument_group('Training', 'model training') train.add_argument('--network', type=str, help='the neural network to use') train.add_argu...
python
def add_fit_args(parser): """ parser : argparse.ArgumentParser return a parser added with args required by fit """ train = parser.add_argument_group('Training', 'model training') train.add_argument('--network', type=str, help='the neural network to use') train.add_argu...
[ "def", "add_fit_args", "(", "parser", ")", ":", "train", "=", "parser", ".", "add_argument_group", "(", "'Training'", ",", "'model training'", ")", "train", ".", "add_argument", "(", "'--network'", ",", "type", "=", "str", ",", "help", "=", "'the neural networ...
parser : argparse.ArgumentParser return a parser added with args required by fit
[ "parser", ":", "argparse", ".", "ArgumentParser", "return", "a", "parser", "added", "with", "args", "required", "by", "fit" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/image-classification/common/fit.py#L77-L145
train
apache/incubator-mxnet
example/image-classification/common/fit.py
fit
def fit(args, network, data_loader, **kwargs): """ train a model args : argparse returns network : the symbol definition of the nerual network data_loader : function that returns the train and val data iterators """ # kvstore kv = mx.kvstore.create(args.kv_store) if args.gc_type != '...
python
def fit(args, network, data_loader, **kwargs): """ train a model args : argparse returns network : the symbol definition of the nerual network data_loader : function that returns the train and val data iterators """ # kvstore kv = mx.kvstore.create(args.kv_store) if args.gc_type != '...
[ "def", "fit", "(", "args", ",", "network", ",", "data_loader", ",", "*", "*", "kwargs", ")", ":", "# kvstore", "kv", "=", "mx", ".", "kvstore", ".", "create", "(", "args", ".", "kv_store", ")", "if", "args", ".", "gc_type", "!=", "'none'", ":", "kv...
train a model args : argparse returns network : the symbol definition of the nerual network data_loader : function that returns the train and val data iterators
[ "train", "a", "model", "args", ":", "argparse", "returns", "network", ":", "the", "symbol", "definition", "of", "the", "nerual", "network", "data_loader", ":", "function", "that", "returns", "the", "train", "and", "val", "data", "iterators" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/image-classification/common/fit.py#L148-L338
train
apache/incubator-mxnet
python/mxnet/image/detection.py
CreateMultiRandCropAugmenter
def CreateMultiRandCropAugmenter(min_object_covered=0.1, aspect_ratio_range=(0.75, 1.33), area_range=(0.05, 1.0), min_eject_coverage=0.3, max_attempts=50, skip_prob=0): """Helper function to create multiple random crop augmenters. Parameters ...
python
def CreateMultiRandCropAugmenter(min_object_covered=0.1, aspect_ratio_range=(0.75, 1.33), area_range=(0.05, 1.0), min_eject_coverage=0.3, max_attempts=50, skip_prob=0): """Helper function to create multiple random crop augmenters. Parameters ...
[ "def", "CreateMultiRandCropAugmenter", "(", "min_object_covered", "=", "0.1", ",", "aspect_ratio_range", "=", "(", "0.75", ",", "1.33", ")", ",", "area_range", "=", "(", "0.05", ",", "1.0", ")", ",", "min_eject_coverage", "=", "0.3", ",", "max_attempts", "=", ...
Helper function to create multiple random crop augmenters. Parameters ---------- min_object_covered : float or list of float, default=0.1 The cropped area of the image must contain at least this fraction of any bounding box supplied. The value of this parameter should be non-negative. ...
[ "Helper", "function", "to", "create", "multiple", "random", "crop", "augmenters", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/image/detection.py#L417-L479
train
apache/incubator-mxnet
python/mxnet/image/detection.py
CreateDetAugmenter
def CreateDetAugmenter(data_shape, resize=0, rand_crop=0, rand_pad=0, rand_gray=0, rand_mirror=False, mean=None, std=None, brightness=0, contrast=0, saturation=0, pca_noise=0, hue=0, inter_method=2, min_object_covered=0.1, aspect_ratio_range=(0.75, 1....
python
def CreateDetAugmenter(data_shape, resize=0, rand_crop=0, rand_pad=0, rand_gray=0, rand_mirror=False, mean=None, std=None, brightness=0, contrast=0, saturation=0, pca_noise=0, hue=0, inter_method=2, min_object_covered=0.1, aspect_ratio_range=(0.75, 1....
[ "def", "CreateDetAugmenter", "(", "data_shape", ",", "resize", "=", "0", ",", "rand_crop", "=", "0", ",", "rand_pad", "=", "0", ",", "rand_gray", "=", "0", ",", "rand_mirror", "=", "False", ",", "mean", "=", "None", ",", "std", "=", "None", ",", "bri...
Create augmenters for detection. Parameters ---------- data_shape : tuple of int Shape for output data resize : int Resize shorter edge if larger than 0 at the begining rand_crop : float [0, 1], probability to apply random cropping rand_pad : float [0, 1], probab...
[ "Create", "augmenters", "for", "detection", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/image/detection.py#L482-L621
train
apache/incubator-mxnet
python/mxnet/image/detection.py
DetRandomSelectAug.dumps
def dumps(self): """Override default.""" return [self.__class__.__name__.lower(), [x.dumps() for x in self.aug_list]]
python
def dumps(self): """Override default.""" return [self.__class__.__name__.lower(), [x.dumps() for x in self.aug_list]]
[ "def", "dumps", "(", "self", ")", ":", "return", "[", "self", ".", "__class__", ".", "__name__", ".", "lower", "(", ")", ",", "[", "x", ".", "dumps", "(", ")", "for", "x", "in", "self", ".", "aug_list", "]", "]" ]
Override default.
[ "Override", "default", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/image/detection.py#L113-L115
train
apache/incubator-mxnet
python/mxnet/image/detection.py
DetRandomCropAug._calculate_areas
def _calculate_areas(self, label): """Calculate areas for multiple labels""" heights = np.maximum(0, label[:, 3] - label[:, 1]) widths = np.maximum(0, label[:, 2] - label[:, 0]) return heights * widths
python
def _calculate_areas(self, label): """Calculate areas for multiple labels""" heights = np.maximum(0, label[:, 3] - label[:, 1]) widths = np.maximum(0, label[:, 2] - label[:, 0]) return heights * widths
[ "def", "_calculate_areas", "(", "self", ",", "label", ")", ":", "heights", "=", "np", ".", "maximum", "(", "0", ",", "label", "[", ":", ",", "3", "]", "-", "label", "[", ":", ",", "1", "]", ")", "widths", "=", "np", ".", "maximum", "(", "0", ...
Calculate areas for multiple labels
[ "Calculate", "areas", "for", "multiple", "labels" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/image/detection.py#L213-L217
train
apache/incubator-mxnet
python/mxnet/image/detection.py
DetRandomCropAug._intersect
def _intersect(self, label, xmin, ymin, xmax, ymax): """Calculate intersect areas, normalized.""" left = np.maximum(label[:, 0], xmin) right = np.minimum(label[:, 2], xmax) top = np.maximum(label[:, 1], ymin) bot = np.minimum(label[:, 3], ymax) invalid = np.where(np.logic...
python
def _intersect(self, label, xmin, ymin, xmax, ymax): """Calculate intersect areas, normalized.""" left = np.maximum(label[:, 0], xmin) right = np.minimum(label[:, 2], xmax) top = np.maximum(label[:, 1], ymin) bot = np.minimum(label[:, 3], ymax) invalid = np.where(np.logic...
[ "def", "_intersect", "(", "self", ",", "label", ",", "xmin", ",", "ymin", ",", "xmax", ",", "ymax", ")", ":", "left", "=", "np", ".", "maximum", "(", "label", "[", ":", ",", "0", "]", ",", "xmin", ")", "right", "=", "np", ".", "minimum", "(", ...
Calculate intersect areas, normalized.
[ "Calculate", "intersect", "areas", "normalized", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/image/detection.py#L220-L233
train
apache/incubator-mxnet
python/mxnet/image/detection.py
DetRandomCropAug._check_satisfy_constraints
def _check_satisfy_constraints(self, label, xmin, ymin, xmax, ymax, width, height): """Check if constrains are satisfied""" if (xmax - xmin) * (ymax - ymin) < 2: return False # only 1 pixel x1 = float(xmin) / width y1 = float(ymin) / height x2 = float(xmax) / width ...
python
def _check_satisfy_constraints(self, label, xmin, ymin, xmax, ymax, width, height): """Check if constrains are satisfied""" if (xmax - xmin) * (ymax - ymin) < 2: return False # only 1 pixel x1 = float(xmin) / width y1 = float(ymin) / height x2 = float(xmax) / width ...
[ "def", "_check_satisfy_constraints", "(", "self", ",", "label", ",", "xmin", ",", "ymin", ",", "xmax", ",", "ymax", ",", "width", ",", "height", ")", ":", "if", "(", "xmax", "-", "xmin", ")", "*", "(", "ymax", "-", "ymin", ")", "<", "2", ":", "re...
Check if constrains are satisfied
[ "Check", "if", "constrains", "are", "satisfied" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/image/detection.py#L235-L250
train
apache/incubator-mxnet
python/mxnet/image/detection.py
DetRandomCropAug._update_labels
def _update_labels(self, label, crop_box, height, width): """Convert labels according to crop box""" xmin = float(crop_box[0]) / width ymin = float(crop_box[1]) / height w = float(crop_box[2]) / width h = float(crop_box[3]) / height out = label.copy() out[:, (1, 3...
python
def _update_labels(self, label, crop_box, height, width): """Convert labels according to crop box""" xmin = float(crop_box[0]) / width ymin = float(crop_box[1]) / height w = float(crop_box[2]) / width h = float(crop_box[3]) / height out = label.copy() out[:, (1, 3...
[ "def", "_update_labels", "(", "self", ",", "label", ",", "crop_box", ",", "height", ",", "width", ")", ":", "xmin", "=", "float", "(", "crop_box", "[", "0", "]", ")", "/", "width", "ymin", "=", "float", "(", "crop_box", "[", "1", "]", ")", "/", "...
Convert labels according to crop box
[ "Convert", "labels", "according", "to", "crop", "box" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/image/detection.py#L252-L272
train
apache/incubator-mxnet
python/mxnet/image/detection.py
DetRandomCropAug._random_crop_proposal
def _random_crop_proposal(self, label, height, width): """Propose cropping areas""" from math import sqrt if not self.enabled or height <= 0 or width <= 0: return () min_area = self.area_range[0] * height * width max_area = self.area_range[1] * height * width ...
python
def _random_crop_proposal(self, label, height, width): """Propose cropping areas""" from math import sqrt if not self.enabled or height <= 0 or width <= 0: return () min_area = self.area_range[0] * height * width max_area = self.area_range[1] * height * width ...
[ "def", "_random_crop_proposal", "(", "self", ",", "label", ",", "height", ",", "width", ")", ":", "from", "math", "import", "sqrt", "if", "not", "self", ".", "enabled", "or", "height", "<=", "0", "or", "width", "<=", "0", ":", "return", "(", ")", "mi...
Propose cropping areas
[ "Propose", "cropping", "areas" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/image/detection.py#L274-L320
train
apache/incubator-mxnet
python/mxnet/image/detection.py
DetRandomPadAug._update_labels
def _update_labels(self, label, pad_box, height, width): """Update label according to padding region""" out = label.copy() out[:, (1, 3)] = (out[:, (1, 3)] * width + pad_box[0]) / pad_box[2] out[:, (2, 4)] = (out[:, (2, 4)] * height + pad_box[1]) / pad_box[3] return out
python
def _update_labels(self, label, pad_box, height, width): """Update label according to padding region""" out = label.copy() out[:, (1, 3)] = (out[:, (1, 3)] * width + pad_box[0]) / pad_box[2] out[:, (2, 4)] = (out[:, (2, 4)] * height + pad_box[1]) / pad_box[3] return out
[ "def", "_update_labels", "(", "self", ",", "label", ",", "pad_box", ",", "height", ",", "width", ")", ":", "out", "=", "label", ".", "copy", "(", ")", "out", "[", ":", ",", "(", "1", ",", "3", ")", "]", "=", "(", "out", "[", ":", ",", "(", ...
Update label according to padding region
[ "Update", "label", "according", "to", "padding", "region" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/image/detection.py#L378-L383
train
apache/incubator-mxnet
python/mxnet/image/detection.py
DetRandomPadAug._random_pad_proposal
def _random_pad_proposal(self, label, height, width): """Generate random padding region""" from math import sqrt if not self.enabled or height <= 0 or width <= 0: return () min_area = self.area_range[0] * height * width max_area = self.area_range[1] * height * width ...
python
def _random_pad_proposal(self, label, height, width): """Generate random padding region""" from math import sqrt if not self.enabled or height <= 0 or width <= 0: return () min_area = self.area_range[0] * height * width max_area = self.area_range[1] * height * width ...
[ "def", "_random_pad_proposal", "(", "self", ",", "label", ",", "height", ",", "width", ")", ":", "from", "math", "import", "sqrt", "if", "not", "self", ".", "enabled", "or", "height", "<=", "0", "or", "width", "<=", "0", ":", "return", "(", ")", "min...
Generate random padding region
[ "Generate", "random", "padding", "region" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/image/detection.py#L385-L414
train