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/ndarray/ndarray.py
NDArray.dtype
def dtype(self): """Data-type of the array's elements. Returns ------- numpy.dtype This NDArray's data type. Examples -------- >>> x = mx.nd.zeros((2,3)) >>> x.dtype <type 'numpy.float32'> >>> y = mx.nd.zeros((2,3), dtype='int...
python
def dtype(self): """Data-type of the array's elements. Returns ------- numpy.dtype This NDArray's data type. Examples -------- >>> x = mx.nd.zeros((2,3)) >>> x.dtype <type 'numpy.float32'> >>> y = mx.nd.zeros((2,3), dtype='int...
[ "def", "dtype", "(", "self", ")", ":", "mx_dtype", "=", "ctypes", ".", "c_int", "(", ")", "check_call", "(", "_LIB", ".", "MXNDArrayGetDType", "(", "self", ".", "handle", ",", "ctypes", ".", "byref", "(", "mx_dtype", ")", ")", ")", "return", "_DTYPE_MX...
Data-type of the array's elements. Returns ------- numpy.dtype This NDArray's data type. Examples -------- >>> x = mx.nd.zeros((2,3)) >>> x.dtype <type 'numpy.float32'> >>> y = mx.nd.zeros((2,3), dtype='int32') >>> y.dtype ...
[ "Data", "-", "type", "of", "the", "array", "s", "elements", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/ndarray/ndarray.py#L1900-L1920
train
apache/incubator-mxnet
python/mxnet/ndarray/ndarray.py
NDArray._fresh_grad
def _fresh_grad(self): """Whether this array's corresponding gradient array (registered via `autograd.mark_variables`) has been updated by `autograd.backward` since last reset. `_fresh_grad` need to be manually set to False after consuming gradient (usually after updating this ...
python
def _fresh_grad(self): """Whether this array's corresponding gradient array (registered via `autograd.mark_variables`) has been updated by `autograd.backward` since last reset. `_fresh_grad` need to be manually set to False after consuming gradient (usually after updating this ...
[ "def", "_fresh_grad", "(", "self", ")", ":", "out", "=", "ctypes", ".", "c_int", "(", ")", "check_call", "(", "_LIB", ".", "MXNDArrayGetGradState", "(", "self", ".", "handle", ",", "ctypes", ".", "byref", "(", "out", ")", ")", ")", "return", "out", "...
Whether this array's corresponding gradient array (registered via `autograd.mark_variables`) has been updated by `autograd.backward` since last reset. `_fresh_grad` need to be manually set to False after consuming gradient (usually after updating this array).
[ "Whether", "this", "array", "s", "corresponding", "gradient", "array", "(", "registered", "via", "autograd", ".", "mark_variables", ")", "has", "been", "updated", "by", "autograd", ".", "backward", "since", "last", "reset", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/ndarray/ndarray.py#L1957-L1968
train
apache/incubator-mxnet
python/mxnet/ndarray/ndarray.py
NDArray.asnumpy
def asnumpy(self): """Returns a ``numpy.ndarray`` object with value copied from this array. Examples -------- >>> x = mx.nd.ones((2,3)) >>> y = x.asnumpy() >>> type(y) <type 'numpy.ndarray'> >>> y array([[ 1., 1., 1.], [ 1., 1., ...
python
def asnumpy(self): """Returns a ``numpy.ndarray`` object with value copied from this array. Examples -------- >>> x = mx.nd.ones((2,3)) >>> y = x.asnumpy() >>> type(y) <type 'numpy.ndarray'> >>> y array([[ 1., 1., 1.], [ 1., 1., ...
[ "def", "asnumpy", "(", "self", ")", ":", "data", "=", "np", ".", "empty", "(", "self", ".", "shape", ",", "dtype", "=", "self", ".", "dtype", ")", "check_call", "(", "_LIB", ".", "MXNDArraySyncCopyToCPU", "(", "self", ".", "handle", ",", "data", ".",...
Returns a ``numpy.ndarray`` object with value copied from this array. Examples -------- >>> x = mx.nd.ones((2,3)) >>> y = x.asnumpy() >>> type(y) <type 'numpy.ndarray'> >>> y array([[ 1., 1., 1.], [ 1., 1., 1.]], dtype=float32) ...
[ "Returns", "a", "numpy", ".", "ndarray", "object", "with", "value", "copied", "from", "this", "array", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/ndarray/ndarray.py#L1974-L1996
train
apache/incubator-mxnet
python/mxnet/ndarray/ndarray.py
NDArray.astype
def astype(self, dtype, copy=True): """Returns a copy of the array after casting to a specified type. Parameters ---------- dtype : numpy.dtype or str The type of the returned array. copy : bool Default `True`. By default, astype always returns a newly ...
python
def astype(self, dtype, copy=True): """Returns a copy of the array after casting to a specified type. Parameters ---------- dtype : numpy.dtype or str The type of the returned array. copy : bool Default `True`. By default, astype always returns a newly ...
[ "def", "astype", "(", "self", ",", "dtype", ",", "copy", "=", "True", ")", ":", "if", "not", "copy", "and", "np", ".", "dtype", "(", "dtype", ")", "==", "self", ".", "dtype", ":", "return", "self", "res", "=", "empty", "(", "self", ".", "shape", ...
Returns a copy of the array after casting to a specified type. Parameters ---------- dtype : numpy.dtype or str The type of the returned array. copy : bool Default `True`. By default, astype always returns a newly allocated ndarray on the same context...
[ "Returns", "a", "copy", "of", "the", "array", "after", "casting", "to", "a", "specified", "type", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/ndarray/ndarray.py#L2015-L2048
train
apache/incubator-mxnet
python/mxnet/ndarray/ndarray.py
NDArray.copyto
def copyto(self, other): """Copies the value of this array to another array. If ``other`` is a ``NDArray`` object, then ``other.shape`` and ``self.shape`` should be the same. This function copies the value from ``self`` to ``other``. If ``other`` is a context, a new ``NDArray``...
python
def copyto(self, other): """Copies the value of this array to another array. If ``other`` is a ``NDArray`` object, then ``other.shape`` and ``self.shape`` should be the same. This function copies the value from ``self`` to ``other``. If ``other`` is a context, a new ``NDArray``...
[ "def", "copyto", "(", "self", ",", "other", ")", ":", "if", "isinstance", "(", "other", ",", "NDArray", ")", ":", "if", "other", ".", "handle", "is", "self", ".", "handle", ":", "warnings", ".", "warn", "(", "'You are attempting to copy an array to itself'",...
Copies the value of this array to another array. If ``other`` is a ``NDArray`` object, then ``other.shape`` and ``self.shape`` should be the same. This function copies the value from ``self`` to ``other``. If ``other`` is a context, a new ``NDArray`` will be first created on th...
[ "Copies", "the", "value", "of", "this", "array", "to", "another", "array", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/ndarray/ndarray.py#L2050-L2094
train
apache/incubator-mxnet
python/mxnet/ndarray/ndarray.py
NDArray.as_in_context
def as_in_context(self, context): """Returns an array on the target device with the same value as this array. If the target context is the same as ``self.context``, then ``self`` is returned. Otherwise, a copy is made. Parameters ---------- context : Context ...
python
def as_in_context(self, context): """Returns an array on the target device with the same value as this array. If the target context is the same as ``self.context``, then ``self`` is returned. Otherwise, a copy is made. Parameters ---------- context : Context ...
[ "def", "as_in_context", "(", "self", ",", "context", ")", ":", "if", "self", ".", "context", "==", "context", ":", "return", "self", "return", "self", ".", "copyto", "(", "context", ")" ]
Returns an array on the target device with the same value as this array. If the target context is the same as ``self.context``, then ``self`` is returned. Otherwise, a copy is made. Parameters ---------- context : Context The target context. Returns ...
[ "Returns", "an", "array", "on", "the", "target", "device", "with", "the", "same", "value", "as", "this", "array", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/ndarray/ndarray.py#L2114-L2143
train
apache/incubator-mxnet
python/mxnet/ndarray/ndarray.py
NDArray.attach_grad
def attach_grad(self, grad_req='write', stype=None): """Attach a gradient buffer to this NDArray, so that `backward` can compute gradient with respect to it. Parameters ---------- grad_req : {'write', 'add', 'null'} How gradient will be accumulated. - 'wr...
python
def attach_grad(self, grad_req='write', stype=None): """Attach a gradient buffer to this NDArray, so that `backward` can compute gradient with respect to it. Parameters ---------- grad_req : {'write', 'add', 'null'} How gradient will be accumulated. - 'wr...
[ "def", "attach_grad", "(", "self", ",", "grad_req", "=", "'write'", ",", "stype", "=", "None", ")", ":", "from", ".", "import", "zeros", "as", "_zeros", "if", "stype", "is", "not", "None", ":", "grad", "=", "_zeros", "(", "self", ".", "shape", ",", ...
Attach a gradient buffer to this NDArray, so that `backward` can compute gradient with respect to it. Parameters ---------- grad_req : {'write', 'add', 'null'} How gradient will be accumulated. - 'write': gradient will be overwritten on every backward. ...
[ "Attach", "a", "gradient", "buffer", "to", "this", "NDArray", "so", "that", "backward", "can", "compute", "gradient", "with", "respect", "to", "it", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/ndarray/ndarray.py#L2145-L2168
train
apache/incubator-mxnet
python/mxnet/ndarray/ndarray.py
NDArray.grad
def grad(self): """Returns gradient buffer attached to this NDArray.""" from . import _ndarray_cls hdl = NDArrayHandle() check_call(_LIB.MXNDArrayGetGrad(self.handle, ctypes.byref(hdl))) if hdl.value is None: return None return _ndarray_cls(hdl)
python
def grad(self): """Returns gradient buffer attached to this NDArray.""" from . import _ndarray_cls hdl = NDArrayHandle() check_call(_LIB.MXNDArrayGetGrad(self.handle, ctypes.byref(hdl))) if hdl.value is None: return None return _ndarray_cls(hdl)
[ "def", "grad", "(", "self", ")", ":", "from", ".", "import", "_ndarray_cls", "hdl", "=", "NDArrayHandle", "(", ")", "check_call", "(", "_LIB", ".", "MXNDArrayGetGrad", "(", "self", ".", "handle", ",", "ctypes", ".", "byref", "(", "hdl", ")", ")", ")", ...
Returns gradient buffer attached to this NDArray.
[ "Returns", "gradient", "buffer", "attached", "to", "this", "NDArray", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/ndarray/ndarray.py#L2171-L2178
train
apache/incubator-mxnet
python/mxnet/ndarray/ndarray.py
NDArray.detach
def detach(self): """Returns a new NDArray, detached from the current graph.""" from . import _ndarray_cls hdl = NDArrayHandle() check_call(_LIB.MXNDArrayDetach(self.handle, ctypes.byref(hdl))) return _ndarray_cls(hdl)
python
def detach(self): """Returns a new NDArray, detached from the current graph.""" from . import _ndarray_cls hdl = NDArrayHandle() check_call(_LIB.MXNDArrayDetach(self.handle, ctypes.byref(hdl))) return _ndarray_cls(hdl)
[ "def", "detach", "(", "self", ")", ":", "from", ".", "import", "_ndarray_cls", "hdl", "=", "NDArrayHandle", "(", ")", "check_call", "(", "_LIB", ".", "MXNDArrayDetach", "(", "self", ".", "handle", ",", "ctypes", ".", "byref", "(", "hdl", ")", ")", ")",...
Returns a new NDArray, detached from the current graph.
[ "Returns", "a", "new", "NDArray", "detached", "from", "the", "current", "graph", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/ndarray/ndarray.py#L2180-L2185
train
apache/incubator-mxnet
python/mxnet/ndarray/ndarray.py
NDArray.backward
def backward(self, out_grad=None, retain_graph=False, train_mode=True): """Compute the gradients of this NDArray w.r.t variables. Parameters ---------- out_grad : NDArray, optional Gradient with respect to head. retain_graph : bool, optional Whether to re...
python
def backward(self, out_grad=None, retain_graph=False, train_mode=True): """Compute the gradients of this NDArray w.r.t variables. Parameters ---------- out_grad : NDArray, optional Gradient with respect to head. retain_graph : bool, optional Whether to re...
[ "def", "backward", "(", "self", ",", "out_grad", "=", "None", ",", "retain_graph", "=", "False", ",", "train_mode", "=", "True", ")", ":", "if", "out_grad", "is", "None", ":", "ograd_handles", "=", "[", "NDArrayHandle", "(", "0", ")", "]", "else", ":",...
Compute the gradients of this NDArray w.r.t variables. Parameters ---------- out_grad : NDArray, optional Gradient with respect to head. retain_graph : bool, optional Whether to retain the computaion graph for another backward pass on the same graph. ...
[ "Compute", "the", "gradients", "of", "this", "NDArray", "w", ".", "r", ".", "t", "variables", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/ndarray/ndarray.py#L2187-L2215
train
apache/incubator-mxnet
example/gluon/lipnet/utils/align.py
Align.build
def build(self, align_path): """ Build the align array """ file = open(align_path, 'r') lines = file.readlines() file.close() # words: list([op, ed, word]) words = [] for line in lines: _op, _ed, word = line.strip().split(' ') ...
python
def build(self, align_path): """ Build the align array """ file = open(align_path, 'r') lines = file.readlines() file.close() # words: list([op, ed, word]) words = [] for line in lines: _op, _ed, word = line.strip().split(' ') ...
[ "def", "build", "(", "self", ",", "align_path", ")", ":", "file", "=", "open", "(", "align_path", ",", "'r'", ")", "lines", "=", "file", ".", "readlines", "(", ")", "file", ".", "close", "(", ")", "# words: list([op, ed, word])", "words", "=", "[", "]"...
Build the align array
[ "Build", "the", "align", "array" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/gluon/lipnet/utils/align.py#L36-L52
train
apache/incubator-mxnet
example/gluon/lipnet/utils/align.py
Align.sentence
def sentence(self, padding=75): """ Get sentence """ vec = word_to_vector(self.sentence_str) vec += [-1] * (padding - self.sentence_length) return np.array(vec, dtype=np.int32)
python
def sentence(self, padding=75): """ Get sentence """ vec = word_to_vector(self.sentence_str) vec += [-1] * (padding - self.sentence_length) return np.array(vec, dtype=np.int32)
[ "def", "sentence", "(", "self", ",", "padding", "=", "75", ")", ":", "vec", "=", "word_to_vector", "(", "self", ".", "sentence_str", ")", "vec", "+=", "[", "-", "1", "]", "*", "(", "padding", "-", "self", ".", "sentence_length", ")", "return", "np", ...
Get sentence
[ "Get", "sentence" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/gluon/lipnet/utils/align.py#L54-L60
train
apache/incubator-mxnet
example/gluon/lipnet/utils/align.py
Align.word
def word(self, _id, padding=75): """ Get words """ word = self.words[_id][2] vec = word_to_vector(word) vec += [-1] * (padding - len(vec)) return np.array(vec, dtype=np.int32)
python
def word(self, _id, padding=75): """ Get words """ word = self.words[_id][2] vec = word_to_vector(word) vec += [-1] * (padding - len(vec)) return np.array(vec, dtype=np.int32)
[ "def", "word", "(", "self", ",", "_id", ",", "padding", "=", "75", ")", ":", "word", "=", "self", ".", "words", "[", "_id", "]", "[", "2", "]", "vec", "=", "word_to_vector", "(", "word", ")", "vec", "+=", "[", "-", "1", "]", "*", "(", "paddin...
Get words
[ "Get", "words" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/gluon/lipnet/utils/align.py#L62-L69
train
apache/incubator-mxnet
example/gluon/lipnet/utils/align.py
Align.word_frame_pos
def word_frame_pos(self, _id): """ Get the position of words """ left = int(self.words[_id][0]/1000) right = max(left+1, int(self.words[_id][1]/1000)) return (left, right)
python
def word_frame_pos(self, _id): """ Get the position of words """ left = int(self.words[_id][0]/1000) right = max(left+1, int(self.words[_id][1]/1000)) return (left, right)
[ "def", "word_frame_pos", "(", "self", ",", "_id", ")", ":", "left", "=", "int", "(", "self", ".", "words", "[", "_id", "]", "[", "0", "]", "/", "1000", ")", "right", "=", "max", "(", "left", "+", "1", ",", "int", "(", "self", ".", "words", "[...
Get the position of words
[ "Get", "the", "position", "of", "words" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/gluon/lipnet/utils/align.py#L77-L83
train
apache/incubator-mxnet
example/rnn/large_word_lm/custom_module.py
CustomModule.prepare_sparse_params
def prepare_sparse_params(self, param_rowids): '''Prepares the module for processing a data batch by pulling row_sparse parameters from kvstore to all devices based on rowids. Parameters ---------- param_rowids : dict of str to NDArray of list of NDArrays ''' if ...
python
def prepare_sparse_params(self, param_rowids): '''Prepares the module for processing a data batch by pulling row_sparse parameters from kvstore to all devices based on rowids. Parameters ---------- param_rowids : dict of str to NDArray of list of NDArrays ''' if ...
[ "def", "prepare_sparse_params", "(", "self", ",", "param_rowids", ")", ":", "if", "not", "self", ".", "_kvstore", ":", "return", "assert", "(", "isinstance", "(", "param_rowids", ",", "dict", ")", ")", "for", "param_name", ",", "rowids", "in", "param_rowids"...
Prepares the module for processing a data batch by pulling row_sparse parameters from kvstore to all devices based on rowids. Parameters ---------- param_rowids : dict of str to NDArray of list of NDArrays
[ "Prepares", "the", "module", "for", "processing", "a", "data", "batch", "by", "pulling", "row_sparse", "parameters", "from", "kvstore", "to", "all", "devices", "based", "on", "rowids", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/rnn/large_word_lm/custom_module.py#L38-L60
train
apache/incubator-mxnet
example/rnn/large_word_lm/custom_module.py
CustomModule.save_params
def save_params(self, fname): """Saves model parameters to file. Parameters ---------- fname : str Path to output param file. Examples -------- >>> # An example of saving module parameters. >>> mod.save_params('myfile') """ arg_...
python
def save_params(self, fname): """Saves model parameters to file. Parameters ---------- fname : str Path to output param file. Examples -------- >>> # An example of saving module parameters. >>> mod.save_params('myfile') """ arg_...
[ "def", "save_params", "(", "self", ",", "fname", ")", ":", "arg_params", ",", "aux_params", "=", "self", ".", "get_params_from_kv", "(", "self", ".", "_arg_params", ",", "self", ".", "_aux_params", ")", "save_dict", "=", "{", "(", "'arg:%s'", "%", "k", "...
Saves model parameters to file. Parameters ---------- fname : str Path to output param file. Examples -------- >>> # An example of saving module parameters. >>> mod.save_params('myfile')
[ "Saves", "model", "parameters", "to", "file", ".", "Parameters", "----------", "fname", ":", "str", "Path", "to", "output", "param", "file", ".", "Examples", "--------", ">>>", "#", "An", "example", "of", "saving", "module", "parameters", ".", ">>>", "mod", ...
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/rnn/large_word_lm/custom_module.py#L102-L116
train
apache/incubator-mxnet
example/rnn/large_word_lm/custom_module.py
CustomModule.get_params_from_kv
def get_params_from_kv(self, arg_params, aux_params): """ Copy data from kvstore to `arg_params` and `aux_params`. Parameters ---------- arg_params : list of NDArray Target parameter arrays. aux_params : list of NDArray Target aux arrays. Notes ...
python
def get_params_from_kv(self, arg_params, aux_params): """ Copy data from kvstore to `arg_params` and `aux_params`. Parameters ---------- arg_params : list of NDArray Target parameter arrays. aux_params : list of NDArray Target aux arrays. Notes ...
[ "def", "get_params_from_kv", "(", "self", ",", "arg_params", ",", "aux_params", ")", ":", "assert", "(", "self", ".", "_kvstore", "is", "not", "None", ")", "for", "name", ",", "block", "in", "zip", "(", "self", ".", "_exec_group", ".", "param_names", ","...
Copy data from kvstore to `arg_params` and `aux_params`. Parameters ---------- arg_params : list of NDArray Target parameter arrays. aux_params : list of NDArray Target aux arrays. Notes ----- - This function will inplace update the NDArray...
[ "Copy", "data", "from", "kvstore", "to", "arg_params", "and", "aux_params", ".", "Parameters", "----------", "arg_params", ":", "list", "of", "NDArray", "Target", "parameter", "arrays", ".", "aux_params", ":", "list", "of", "NDArray", "Target", "aux", "arrays", ...
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/rnn/large_word_lm/custom_module.py#L118-L141
train
apache/incubator-mxnet
example/rnn/large_word_lm/custom_module.py
CustomModule.clip_by_global_norm_per_ctx
def clip_by_global_norm_per_ctx(self, max_norm=1.0, param_names=None): """Clips gradient norm. The norm is computed over all gradients together, as if they were concatenated into a single vector. Gradients are modified in-place. The method is first used in `[ICML2013] On the ...
python
def clip_by_global_norm_per_ctx(self, max_norm=1.0, param_names=None): """Clips gradient norm. The norm is computed over all gradients together, as if they were concatenated into a single vector. Gradients are modified in-place. The method is first used in `[ICML2013] On the ...
[ "def", "clip_by_global_norm_per_ctx", "(", "self", ",", "max_norm", "=", "1.0", ",", "param_names", "=", "None", ")", ":", "assert", "self", ".", "binded", "and", "self", ".", "params_initialized", "and", "self", ".", "optimizer_initialized", "num_ctx", "=", "...
Clips gradient norm. The norm is computed over all gradients together, as if they were concatenated into a single vector. Gradients are modified in-place. The method is first used in `[ICML2013] On the difficulty of training recurrent neural networks` Note that the gradients...
[ "Clips", "gradient", "norm", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/rnn/large_word_lm/custom_module.py#L143-L174
train
apache/incubator-mxnet
example/rnn/large_word_lm/custom_module.py
CustomModule.rescale_grad
def rescale_grad(self, scale=None, param_name=None): """ Rescale the gradient of provided parameters by a certain scale """ if scale is None or param_name is None: return param_idx = self._exec_group.param_names.index(param_name) grad_vals = self._exec_group.grad_arrays[param...
python
def rescale_grad(self, scale=None, param_name=None): """ Rescale the gradient of provided parameters by a certain scale """ if scale is None or param_name is None: return param_idx = self._exec_group.param_names.index(param_name) grad_vals = self._exec_group.grad_arrays[param...
[ "def", "rescale_grad", "(", "self", ",", "scale", "=", "None", ",", "param_name", "=", "None", ")", ":", "if", "scale", "is", "None", "or", "param_name", "is", "None", ":", "return", "param_idx", "=", "self", ".", "_exec_group", ".", "param_names", ".", ...
Rescale the gradient of provided parameters by a certain scale
[ "Rescale", "the", "gradient", "of", "provided", "parameters", "by", "a", "certain", "scale" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/rnn/large_word_lm/custom_module.py#L176-L183
train
apache/incubator-mxnet
example/sparse/factorization_machine/model.py
factorization_machine_model
def factorization_machine_model(factor_size, num_features, lr_mult_config, wd_mult_config, init_config): """ builds factorization machine network with proper formulation: y = w_0 \sum(x_i w_i) + 0.5(\sum\sum<v_i,v_j>x_ix_j - \sum<v_iv_i>x_i^2) """ x = mx.symbol.Variable("...
python
def factorization_machine_model(factor_size, num_features, lr_mult_config, wd_mult_config, init_config): """ builds factorization machine network with proper formulation: y = w_0 \sum(x_i w_i) + 0.5(\sum\sum<v_i,v_j>x_ix_j - \sum<v_iv_i>x_i^2) """ x = mx.symbol.Variable("...
[ "def", "factorization_machine_model", "(", "factor_size", ",", "num_features", ",", "lr_mult_config", ",", "wd_mult_config", ",", "init_config", ")", ":", "x", "=", "mx", ".", "symbol", ".", "Variable", "(", "\"data\"", ",", "stype", "=", "'csr'", ")", "# fact...
builds factorization machine network with proper formulation: y = w_0 \sum(x_i w_i) + 0.5(\sum\sum<v_i,v_j>x_ix_j - \sum<v_iv_i>x_i^2)
[ "builds", "factorization", "machine", "network", "with", "proper", "formulation", ":", "y", "=", "w_0", "\\", "sum", "(", "x_i", "w_i", ")", "+", "0", ".", "5", "(", "\\", "sum", "\\", "sum<v_i", "v_j", ">", "x_ix_j", "-", "\\", "sum<v_iv_i", ">", "x...
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/sparse/factorization_machine/model.py#L20-L54
train
apache/incubator-mxnet
example/rnn/word_lm/data.py
batchify
def batchify(data, batch_size): """Reshape data into (num_example, batch_size)""" nbatch = data.shape[0] // batch_size data = data[:nbatch * batch_size] data = data.reshape((batch_size, nbatch)).T return data
python
def batchify(data, batch_size): """Reshape data into (num_example, batch_size)""" nbatch = data.shape[0] // batch_size data = data[:nbatch * batch_size] data = data.reshape((batch_size, nbatch)).T return data
[ "def", "batchify", "(", "data", ",", "batch_size", ")", ":", "nbatch", "=", "data", ".", "shape", "[", "0", "]", "//", "batch_size", "data", "=", "data", "[", ":", "nbatch", "*", "batch_size", "]", "data", "=", "data", ".", "reshape", "(", "(", "ba...
Reshape data into (num_example, batch_size)
[ "Reshape", "data", "into", "(", "num_example", "batch_size", ")" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/rnn/word_lm/data.py#L72-L77
train
apache/incubator-mxnet
example/rnn/word_lm/data.py
Corpus.tokenize
def tokenize(self, path): """Tokenizes a text file.""" assert os.path.exists(path) # Add words to the dictionary with open(path, 'r') as f: tokens = 0 for line in f: words = line.split() + ['<eos>'] tokens += len(words) ...
python
def tokenize(self, path): """Tokenizes a text file.""" assert os.path.exists(path) # Add words to the dictionary with open(path, 'r') as f: tokens = 0 for line in f: words = line.split() + ['<eos>'] tokens += len(words) ...
[ "def", "tokenize", "(", "self", ",", "path", ")", ":", "assert", "os", ".", "path", ".", "exists", "(", "path", ")", "# Add words to the dictionary", "with", "open", "(", "path", ",", "'r'", ")", "as", "f", ":", "tokens", "=", "0", "for", "line", "in...
Tokenizes a text file.
[ "Tokenizes", "a", "text", "file", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/rnn/word_lm/data.py#L48-L70
train
apache/incubator-mxnet
python/mxnet/symbol_doc.py
_build_doc
def _build_doc(func_name, desc, arg_names, arg_types, arg_desc, key_var_num_args=None, ret_type=None): """Build docstring for symbolic functions.""" param_str = _build_param_doc(arg_names, arg_types, arg_desc) if key_v...
python
def _build_doc(func_name, desc, arg_names, arg_types, arg_desc, key_var_num_args=None, ret_type=None): """Build docstring for symbolic functions.""" param_str = _build_param_doc(arg_names, arg_types, arg_desc) if key_v...
[ "def", "_build_doc", "(", "func_name", ",", "desc", ",", "arg_names", ",", "arg_types", ",", "arg_desc", ",", "key_var_num_args", "=", "None", ",", "ret_type", "=", "None", ")", ":", "param_str", "=", "_build_param_doc", "(", "arg_names", ",", "arg_types", "...
Build docstring for symbolic functions.
[ "Build", "docstring", "for", "symbolic", "functions", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/symbol_doc.py#L212-L236
train
apache/incubator-mxnet
python/mxnet/symbol_doc.py
SymbolDoc.get_output_shape
def get_output_shape(sym, **input_shapes): """Get user friendly information of the output shapes.""" _, s_outputs, _ = sym.infer_shape(**input_shapes) return dict(zip(sym.list_outputs(), s_outputs))
python
def get_output_shape(sym, **input_shapes): """Get user friendly information of the output shapes.""" _, s_outputs, _ = sym.infer_shape(**input_shapes) return dict(zip(sym.list_outputs(), s_outputs))
[ "def", "get_output_shape", "(", "sym", ",", "*", "*", "input_shapes", ")", ":", "_", ",", "s_outputs", ",", "_", "=", "sym", ".", "infer_shape", "(", "*", "*", "input_shapes", ")", "return", "dict", "(", "zip", "(", "sym", ".", "list_outputs", "(", "...
Get user friendly information of the output shapes.
[ "Get", "user", "friendly", "information", "of", "the", "output", "shapes", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/symbol_doc.py#L56-L59
train
apache/incubator-mxnet
python/mxnet/context.py
num_gpus
def num_gpus(): """Query CUDA for the number of GPUs present. Raises ------ Will raise an exception on any CUDA error. Returns ------- count : int The number of GPUs. """ count = ctypes.c_int() check_call(_LIB.MXGetGPUCount(ctypes.byref(count))) return count.value
python
def num_gpus(): """Query CUDA for the number of GPUs present. Raises ------ Will raise an exception on any CUDA error. Returns ------- count : int The number of GPUs. """ count = ctypes.c_int() check_call(_LIB.MXGetGPUCount(ctypes.byref(count))) return count.value
[ "def", "num_gpus", "(", ")", ":", "count", "=", "ctypes", ".", "c_int", "(", ")", "check_call", "(", "_LIB", ".", "MXGetGPUCount", "(", "ctypes", ".", "byref", "(", "count", ")", ")", ")", "return", "count", ".", "value" ]
Query CUDA for the number of GPUs present. Raises ------ Will raise an exception on any CUDA error. Returns ------- count : int The number of GPUs.
[ "Query", "CUDA", "for", "the", "number", "of", "GPUs", "present", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/context.py#L244-L259
train
apache/incubator-mxnet
python/mxnet/context.py
gpu_memory_info
def gpu_memory_info(device_id=0): """Query CUDA for the free and total bytes of GPU global memory. Parameters ---------- device_id : int, optional The device id of the GPU device. Raises ------ Will raise an exception on any CUDA error. Returns ------- (free, total) : ...
python
def gpu_memory_info(device_id=0): """Query CUDA for the free and total bytes of GPU global memory. Parameters ---------- device_id : int, optional The device id of the GPU device. Raises ------ Will raise an exception on any CUDA error. Returns ------- (free, total) : ...
[ "def", "gpu_memory_info", "(", "device_id", "=", "0", ")", ":", "free", "=", "ctypes", ".", "c_uint64", "(", ")", "total", "=", "ctypes", ".", "c_uint64", "(", ")", "dev_id", "=", "ctypes", ".", "c_int", "(", "device_id", ")", "check_call", "(", "_LIB"...
Query CUDA for the free and total bytes of GPU global memory. Parameters ---------- device_id : int, optional The device id of the GPU device. Raises ------ Will raise an exception on any CUDA error. Returns ------- (free, total) : (int, int) The number of GPUs.
[ "Query", "CUDA", "for", "the", "free", "and", "total", "bytes", "of", "GPU", "global", "memory", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/context.py#L261-L283
train
apache/incubator-mxnet
python/mxnet/context.py
current_context
def current_context(): """Returns the current context. By default, `mx.cpu()` is used for all the computations and it can be overridden by using `with mx.Context(x)` statement where x can be cpu(device_id) or gpu(device_id). Examples ------- >>> mx.current_context() cpu(0) >>> with...
python
def current_context(): """Returns the current context. By default, `mx.cpu()` is used for all the computations and it can be overridden by using `with mx.Context(x)` statement where x can be cpu(device_id) or gpu(device_id). Examples ------- >>> mx.current_context() cpu(0) >>> with...
[ "def", "current_context", "(", ")", ":", "if", "not", "hasattr", "(", "Context", ".", "_default_ctx", ",", "\"value\"", ")", ":", "Context", ".", "_default_ctx", ".", "value", "=", "Context", "(", "'cpu'", ",", "0", ")", "return", "Context", ".", "_defau...
Returns the current context. By default, `mx.cpu()` is used for all the computations and it can be overridden by using `with mx.Context(x)` statement where x can be cpu(device_id) or gpu(device_id). Examples ------- >>> mx.current_context() cpu(0) >>> with mx.Context('gpu', 1): # Cont...
[ "Returns", "the", "current", "context", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/context.py#L285-L309
train
apache/incubator-mxnet
example/gluon/audio/urban_sounds/datasets.py
AudioFolderDataset._list_audio_files
def _list_audio_files(self, root, skip_rows=0): """Populates synsets - a map of index to label for the data items. Populates the data in the dataset, making tuples of (data, label) """ self.synsets = [] self.items = [] if not self._train_csv: # The audio files...
python
def _list_audio_files(self, root, skip_rows=0): """Populates synsets - a map of index to label for the data items. Populates the data in the dataset, making tuples of (data, label) """ self.synsets = [] self.items = [] if not self._train_csv: # The audio files...
[ "def", "_list_audio_files", "(", "self", ",", "root", ",", "skip_rows", "=", "0", ")", ":", "self", ".", "synsets", "=", "[", "]", "self", ".", "items", "=", "[", "]", "if", "not", "self", ".", "_train_csv", ":", "# The audio files are organized in folder ...
Populates synsets - a map of index to label for the data items. Populates the data in the dataset, making tuples of (data, label)
[ "Populates", "synsets", "-", "a", "map", "of", "index", "to", "label", "for", "the", "data", "items", ".", "Populates", "the", "data", "in", "the", "dataset", "making", "tuples", "of", "(", "data", "label", ")" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/gluon/audio/urban_sounds/datasets.py#L86-L107
train
apache/incubator-mxnet
example/gluon/audio/urban_sounds/datasets.py
AudioFolderDataset.transform_first
def transform_first(self, fn, lazy=False): """Returns a new dataset with the first element of each sample transformed by the transformer function `fn`. This is useful, for example, when you only want to transform data while keeping label as is. lazy=False is passed to transform_...
python
def transform_first(self, fn, lazy=False): """Returns a new dataset with the first element of each sample transformed by the transformer function `fn`. This is useful, for example, when you only want to transform data while keeping label as is. lazy=False is passed to transform_...
[ "def", "transform_first", "(", "self", ",", "fn", ",", "lazy", "=", "False", ")", ":", "return", "super", "(", "AudioFolderDataset", ",", "self", ")", ".", "transform_first", "(", "fn", ",", "lazy", "=", "lazy", ")" ]
Returns a new dataset with the first element of each sample transformed by the transformer function `fn`. This is useful, for example, when you only want to transform data while keeping label as is. lazy=False is passed to transform_first for dataset so that all tramsforms could be perf...
[ "Returns", "a", "new", "dataset", "with", "the", "first", "element", "of", "each", "sample", "transformed", "by", "the", "transformer", "function", "fn", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/gluon/audio/urban_sounds/datasets.py#L153-L179
train
apache/incubator-mxnet
python/setup.py
config_cython
def config_cython(): """Try to configure cython and return cython configuration""" if not with_cython: return [] # pylint: disable=unreachable if os.name == 'nt': print("WARNING: Cython is not supported on Windows, will compile without cython module") return [] try: ...
python
def config_cython(): """Try to configure cython and return cython configuration""" if not with_cython: return [] # pylint: disable=unreachable if os.name == 'nt': print("WARNING: Cython is not supported on Windows, will compile without cython module") return [] try: ...
[ "def", "config_cython", "(", ")", ":", "if", "not", "with_cython", ":", "return", "[", "]", "# pylint: disable=unreachable", "if", "os", ".", "name", "==", "'nt'", ":", "print", "(", "\"WARNING: Cython is not supported on Windows, will compile without cython module\"", ...
Try to configure cython and return cython configuration
[ "Try", "to", "configure", "cython", "and", "return", "cython", "configuration" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/setup.py#L62-L100
train
apache/incubator-mxnet
python/mxnet/_ctypes/symbol.py
SymbolBase._compose
def _compose(self, *args, **kwargs): """Compose symbol on inputs. This call mutates the current symbol. Parameters ---------- args: provide positional arguments kwargs: provide keyword arguments Returns ------- the resul...
python
def _compose(self, *args, **kwargs): """Compose symbol on inputs. This call mutates the current symbol. Parameters ---------- args: provide positional arguments kwargs: provide keyword arguments Returns ------- the resul...
[ "def", "_compose", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "name", "=", "kwargs", ".", "pop", "(", "'name'", ",", "None", ")", "if", "name", ":", "name", "=", "c_str", "(", "name", ")", "if", "len", "(", "args", ")", ...
Compose symbol on inputs. This call mutates the current symbol. Parameters ---------- args: provide positional arguments kwargs: provide keyword arguments Returns ------- the resulting symbol
[ "Compose", "symbol", "on", "inputs", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/_ctypes/symbol.py#L48-L88
train
apache/incubator-mxnet
python/mxnet/_ctypes/symbol.py
SymbolBase._set_attr
def _set_attr(self, **kwargs): """Set the attribute of the symbol. Parameters ---------- **kwargs The attributes to set """ keys = c_str_array(kwargs.keys()) vals = c_str_array([str(s) for s in kwargs.values()]) num_args = mx_uint(len(kwargs))...
python
def _set_attr(self, **kwargs): """Set the attribute of the symbol. Parameters ---------- **kwargs The attributes to set """ keys = c_str_array(kwargs.keys()) vals = c_str_array([str(s) for s in kwargs.values()]) num_args = mx_uint(len(kwargs))...
[ "def", "_set_attr", "(", "self", ",", "*", "*", "kwargs", ")", ":", "keys", "=", "c_str_array", "(", "kwargs", ".", "keys", "(", ")", ")", "vals", "=", "c_str_array", "(", "[", "str", "(", "s", ")", "for", "s", "in", "kwargs", ".", "values", "(",...
Set the attribute of the symbol. Parameters ---------- **kwargs The attributes to set
[ "Set", "the", "attribute", "of", "the", "symbol", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/_ctypes/symbol.py#L90-L102
train
apache/incubator-mxnet
example/ssd/symbol/symbol_factory.py
get_config
def get_config(network, data_shape, **kwargs): """Configuration factory for various networks Parameters ---------- network : str base network name, such as vgg_reduced, inceptionv3, resnet... data_shape : int input data dimension kwargs : dict extra arguments """ ...
python
def get_config(network, data_shape, **kwargs): """Configuration factory for various networks Parameters ---------- network : str base network name, such as vgg_reduced, inceptionv3, resnet... data_shape : int input data dimension kwargs : dict extra arguments """ ...
[ "def", "get_config", "(", "network", ",", "data_shape", ",", "*", "*", "kwargs", ")", ":", "if", "network", "==", "'vgg16_reduced'", ":", "if", "data_shape", ">=", "448", ":", "from_layers", "=", "[", "'relu4_3'", ",", "'relu7'", ",", "''", ",", "''", ...
Configuration factory for various networks Parameters ---------- network : str base network name, such as vgg_reduced, inceptionv3, resnet... data_shape : int input data dimension kwargs : dict extra arguments
[ "Configuration", "factory", "for", "various", "networks" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/ssd/symbol/symbol_factory.py#L22-L101
train
apache/incubator-mxnet
example/ssd/symbol/symbol_factory.py
get_symbol_train
def get_symbol_train(network, data_shape, **kwargs): """Wrapper for get symbol for train Parameters ---------- network : str name for the base network symbol data_shape : int input shape kwargs : dict see symbol_builder.get_symbol_train for more details """ if ne...
python
def get_symbol_train(network, data_shape, **kwargs): """Wrapper for get symbol for train Parameters ---------- network : str name for the base network symbol data_shape : int input shape kwargs : dict see symbol_builder.get_symbol_train for more details """ if ne...
[ "def", "get_symbol_train", "(", "network", ",", "data_shape", ",", "*", "*", "kwargs", ")", ":", "if", "network", ".", "startswith", "(", "'legacy'", ")", ":", "logging", ".", "warn", "(", "'Using legacy model.'", ")", "return", "symbol_builder", ".", "impor...
Wrapper for get symbol for train Parameters ---------- network : str name for the base network symbol data_shape : int input shape kwargs : dict see symbol_builder.get_symbol_train for more details
[ "Wrapper", "for", "get", "symbol", "for", "train" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/ssd/symbol/symbol_factory.py#L103-L120
train
apache/incubator-mxnet
python/mxnet/gluon/parameter.py
Parameter._set_trainer
def _set_trainer(self, trainer): """ Set the trainer this parameter is associated with. """ # trainer cannot be replaced for sparse params if self._stype != 'default' and self._trainer and trainer and self._trainer is not trainer: raise RuntimeError( "Failed to set th...
python
def _set_trainer(self, trainer): """ Set the trainer this parameter is associated with. """ # trainer cannot be replaced for sparse params if self._stype != 'default' and self._trainer and trainer and self._trainer is not trainer: raise RuntimeError( "Failed to set th...
[ "def", "_set_trainer", "(", "self", ",", "trainer", ")", ":", "# trainer cannot be replaced for sparse params", "if", "self", ".", "_stype", "!=", "'default'", "and", "self", ".", "_trainer", "and", "trainer", "and", "self", ".", "_trainer", "is", "not", "traine...
Set the trainer this parameter is associated with.
[ "Set", "the", "trainer", "this", "parameter", "is", "associated", "with", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/gluon/parameter.py#L174-L182
train
apache/incubator-mxnet
python/mxnet/gluon/parameter.py
Parameter._get_row_sparse
def _get_row_sparse(self, arr_list, ctx, row_id): """ Get row_sparse data from row_sparse parameters based on row_id. """ # get row sparse params based on row ids if not isinstance(row_id, ndarray.NDArray): raise TypeError("row_id must have NDArray type, but %s is given"%(type(row_id...
python
def _get_row_sparse(self, arr_list, ctx, row_id): """ Get row_sparse data from row_sparse parameters based on row_id. """ # get row sparse params based on row ids if not isinstance(row_id, ndarray.NDArray): raise TypeError("row_id must have NDArray type, but %s is given"%(type(row_id...
[ "def", "_get_row_sparse", "(", "self", ",", "arr_list", ",", "ctx", ",", "row_id", ")", ":", "# get row sparse params based on row ids", "if", "not", "isinstance", "(", "row_id", ",", "ndarray", ".", "NDArray", ")", ":", "raise", "TypeError", "(", "\"row_id must...
Get row_sparse data from row_sparse parameters based on row_id.
[ "Get", "row_sparse", "data", "from", "row_sparse", "parameters", "based", "on", "row_id", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/gluon/parameter.py#L216-L228
train
apache/incubator-mxnet
python/mxnet/gluon/parameter.py
Parameter._load_init
def _load_init(self, data, ctx): """(Re)initializes by loading from data.""" if self.shape: for self_dim, data_dim in zip(self.shape, data.shape): assert self_dim in (0, data_dim), \ "Failed loading Parameter '%s' from saved params: " \ ...
python
def _load_init(self, data, ctx): """(Re)initializes by loading from data.""" if self.shape: for self_dim, data_dim in zip(self.shape, data.shape): assert self_dim in (0, data_dim), \ "Failed loading Parameter '%s' from saved params: " \ ...
[ "def", "_load_init", "(", "self", ",", "data", ",", "ctx", ")", ":", "if", "self", ".", "shape", ":", "for", "self_dim", ",", "data_dim", "in", "zip", "(", "self", ".", "shape", ",", "data", ".", "shape", ")", ":", "assert", "self_dim", "in", "(", ...
(Re)initializes by loading from data.
[ "(", "Re", ")", "initializes", "by", "loading", "from", "data", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/gluon/parameter.py#L230-L264
train
apache/incubator-mxnet
python/mxnet/gluon/parameter.py
Parameter._finish_deferred_init
def _finish_deferred_init(self): """Finishes deferred initialization.""" if not self._deferred_init: return init, ctx, default_init, data = self._deferred_init self._deferred_init = () assert self.shape is not None and np.prod(self.shape) > 0, \ "Cannot in...
python
def _finish_deferred_init(self): """Finishes deferred initialization.""" if not self._deferred_init: return init, ctx, default_init, data = self._deferred_init self._deferred_init = () assert self.shape is not None and np.prod(self.shape) > 0, \ "Cannot in...
[ "def", "_finish_deferred_init", "(", "self", ")", ":", "if", "not", "self", ".", "_deferred_init", ":", "return", "init", ",", "ctx", ",", "default_init", ",", "data", "=", "self", ".", "_deferred_init", "self", ".", "_deferred_init", "=", "(", ")", "asser...
Finishes deferred initialization.
[ "Finishes", "deferred", "initialization", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/gluon/parameter.py#L266-L285
train
apache/incubator-mxnet
python/mxnet/gluon/parameter.py
Parameter._init_impl
def _init_impl(self, data, ctx_list): """Sets data and grad.""" self._ctx_list = list(ctx_list) self._ctx_map = [[], []] for i, ctx in enumerate(self._ctx_list): dev_list = self._ctx_map[ctx.device_typeid&1] while len(dev_list) <= ctx.device_id: de...
python
def _init_impl(self, data, ctx_list): """Sets data and grad.""" self._ctx_list = list(ctx_list) self._ctx_map = [[], []] for i, ctx in enumerate(self._ctx_list): dev_list = self._ctx_map[ctx.device_typeid&1] while len(dev_list) <= ctx.device_id: de...
[ "def", "_init_impl", "(", "self", ",", "data", ",", "ctx_list", ")", ":", "self", ".", "_ctx_list", "=", "list", "(", "ctx_list", ")", "self", ".", "_ctx_map", "=", "[", "[", "]", ",", "[", "]", "]", "for", "i", ",", "ctx", "in", "enumerate", "("...
Sets data and grad.
[ "Sets", "data", "and", "grad", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/gluon/parameter.py#L287-L298
train
apache/incubator-mxnet
python/mxnet/gluon/parameter.py
Parameter._init_grad
def _init_grad(self): """Initialize grad buffers.""" if self.grad_req == 'null': self._grad = None return self._grad = [ndarray.zeros(shape=i.shape, dtype=i.dtype, ctx=i.context, stype=self._grad_stype) for i in self._data] au...
python
def _init_grad(self): """Initialize grad buffers.""" if self.grad_req == 'null': self._grad = None return self._grad = [ndarray.zeros(shape=i.shape, dtype=i.dtype, ctx=i.context, stype=self._grad_stype) for i in self._data] au...
[ "def", "_init_grad", "(", "self", ")", ":", "if", "self", ".", "grad_req", "==", "'null'", ":", "self", ".", "_grad", "=", "None", "return", "self", ".", "_grad", "=", "[", "ndarray", ".", "zeros", "(", "shape", "=", "i", ".", "shape", ",", "dtype"...
Initialize grad buffers.
[ "Initialize", "grad", "buffers", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/gluon/parameter.py#L300-L310
train
apache/incubator-mxnet
python/mxnet/gluon/parameter.py
Parameter._reduce
def _reduce(self): """Reduce data from multiple context to cpu.""" ctx = context.cpu() if self._stype == 'default': block = self.list_data() data = ndarray.add_n(*(w.copyto(ctx) for w in block)) / len(block) else: # fetch all rows for 'row_sparse' para...
python
def _reduce(self): """Reduce data from multiple context to cpu.""" ctx = context.cpu() if self._stype == 'default': block = self.list_data() data = ndarray.add_n(*(w.copyto(ctx) for w in block)) / len(block) else: # fetch all rows for 'row_sparse' para...
[ "def", "_reduce", "(", "self", ")", ":", "ctx", "=", "context", ".", "cpu", "(", ")", "if", "self", ".", "_stype", "==", "'default'", ":", "block", "=", "self", ".", "list_data", "(", ")", "data", "=", "ndarray", ".", "add_n", "(", "*", "(", "w",...
Reduce data from multiple context to cpu.
[ "Reduce", "data", "from", "multiple", "context", "to", "cpu", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/gluon/parameter.py#L312-L323
train
apache/incubator-mxnet
python/mxnet/gluon/parameter.py
Parameter.initialize
def initialize(self, init=None, ctx=None, default_init=initializer.Uniform(), force_reinit=False): """Initializes parameter and gradient arrays. Only used for :py:class:`NDArray` API. Parameters ---------- init : Initializer The initializer to use. Overrid...
python
def initialize(self, init=None, ctx=None, default_init=initializer.Uniform(), force_reinit=False): """Initializes parameter and gradient arrays. Only used for :py:class:`NDArray` API. Parameters ---------- init : Initializer The initializer to use. Overrid...
[ "def", "initialize", "(", "self", ",", "init", "=", "None", ",", "ctx", "=", "None", ",", "default_init", "=", "initializer", ".", "Uniform", "(", ")", ",", "force_reinit", "=", "False", ")", ":", "if", "self", ".", "_data", "is", "not", "None", "and...
Initializes parameter and gradient arrays. Only used for :py:class:`NDArray` API. Parameters ---------- init : Initializer The initializer to use. Overrides :py:meth:`Parameter.init` and default_init. ctx : Context or list of Context, defaults to :py:meth:`context.current_co...
[ "Initializes", "parameter", "and", "gradient", "arrays", ".", "Only", "used", "for", ":", "py", ":", "class", ":", "NDArray", "API", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/gluon/parameter.py#L325-L391
train
apache/incubator-mxnet
python/mxnet/gluon/parameter.py
Parameter.reset_ctx
def reset_ctx(self, ctx): """Re-assign Parameter to other contexts. Parameters ---------- ctx : Context or list of Context, default ``context.current_context()``. Assign Parameter to given context. If ctx is a list of Context, a copy will be made for each context...
python
def reset_ctx(self, ctx): """Re-assign Parameter to other contexts. Parameters ---------- ctx : Context or list of Context, default ``context.current_context()``. Assign Parameter to given context. If ctx is a list of Context, a copy will be made for each context...
[ "def", "reset_ctx", "(", "self", ",", "ctx", ")", ":", "if", "ctx", "is", "None", ":", "ctx", "=", "[", "context", ".", "current_context", "(", ")", "]", "if", "isinstance", "(", "ctx", ",", "Context", ")", ":", "ctx", "=", "[", "ctx", "]", "if",...
Re-assign Parameter to other contexts. Parameters ---------- ctx : Context or list of Context, default ``context.current_context()``. Assign Parameter to given context. If ctx is a list of Context, a copy will be made for each context.
[ "Re", "-", "assign", "Parameter", "to", "other", "contexts", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/gluon/parameter.py#L393-L415
train
apache/incubator-mxnet
python/mxnet/gluon/parameter.py
Parameter.set_data
def set_data(self, data): """Sets this parameter's value on all contexts.""" self.shape = data.shape if self._data is None: assert self._deferred_init, \ "Parameter '%s' has not been initialized"%self.name self._deferred_init = self._deferred_init[:3] + (...
python
def set_data(self, data): """Sets this parameter's value on all contexts.""" self.shape = data.shape if self._data is None: assert self._deferred_init, \ "Parameter '%s' has not been initialized"%self.name self._deferred_init = self._deferred_init[:3] + (...
[ "def", "set_data", "(", "self", ",", "data", ")", ":", "self", ".", "shape", "=", "data", ".", "shape", "if", "self", ".", "_data", "is", "None", ":", "assert", "self", ".", "_deferred_init", ",", "\"Parameter '%s' has not been initialized\"", "%", "self", ...
Sets this parameter's value on all contexts.
[ "Sets", "this", "parameter", "s", "value", "on", "all", "contexts", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/gluon/parameter.py#L418-L434
train
apache/incubator-mxnet
python/mxnet/gluon/parameter.py
Parameter.row_sparse_data
def row_sparse_data(self, row_id): """Returns a copy of the 'row_sparse' parameter on the same context as row_id's. The copy only retains rows whose ids occur in provided row ids. The parameter must have been initialized on this context before. Parameters ---------- row_...
python
def row_sparse_data(self, row_id): """Returns a copy of the 'row_sparse' parameter on the same context as row_id's. The copy only retains rows whose ids occur in provided row ids. The parameter must have been initialized on this context before. Parameters ---------- row_...
[ "def", "row_sparse_data", "(", "self", ",", "row_id", ")", ":", "if", "self", ".", "_stype", "!=", "'row_sparse'", ":", "raise", "RuntimeError", "(", "\"Cannot return a copy of Parameter %s via row_sparse_data() \"", "\"because its storage type is %s. Please use data() instead....
Returns a copy of the 'row_sparse' parameter on the same context as row_id's. The copy only retains rows whose ids occur in provided row ids. The parameter must have been initialized on this context before. Parameters ---------- row_id: NDArray Row ids to retain for ...
[ "Returns", "a", "copy", "of", "the", "row_sparse", "parameter", "on", "the", "same", "context", "as", "row_id", "s", ".", "The", "copy", "only", "retains", "rows", "whose", "ids", "occur", "in", "provided", "row", "ids", ".", "The", "parameter", "must", ...
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/gluon/parameter.py#L436-L454
train
apache/incubator-mxnet
python/mxnet/gluon/parameter.py
Parameter.list_row_sparse_data
def list_row_sparse_data(self, row_id): """Returns copies of the 'row_sparse' parameter on all contexts, in the same order as creation. The copy only retains rows whose ids occur in provided row ids. The parameter must have been initialized before. Parameters ---------- ...
python
def list_row_sparse_data(self, row_id): """Returns copies of the 'row_sparse' parameter on all contexts, in the same order as creation. The copy only retains rows whose ids occur in provided row ids. The parameter must have been initialized before. Parameters ---------- ...
[ "def", "list_row_sparse_data", "(", "self", ",", "row_id", ")", ":", "if", "self", ".", "_stype", "!=", "'row_sparse'", ":", "raise", "RuntimeError", "(", "\"Cannot return copies of Parameter '%s' on all contexts via \"", "\"list_row_sparse_data() because its storage type is %s...
Returns copies of the 'row_sparse' parameter on all contexts, in the same order as creation. The copy only retains rows whose ids occur in provided row ids. The parameter must have been initialized before. Parameters ---------- row_id: NDArray Row ids to retain for t...
[ "Returns", "copies", "of", "the", "row_sparse", "parameter", "on", "all", "contexts", "in", "the", "same", "order", "as", "creation", ".", "The", "copy", "only", "retains", "rows", "whose", "ids", "occur", "in", "provided", "row", "ids", ".", "The", "param...
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/gluon/parameter.py#L456-L474
train
apache/incubator-mxnet
python/mxnet/gluon/parameter.py
Parameter.data
def data(self, ctx=None): """Returns a copy of this parameter on one context. Must have been initialized on this context before. For sparse parameters, use :py:meth:`Parameter.row_sparse_data` instead. Parameters ---------- ctx : Context Desired context. ...
python
def data(self, ctx=None): """Returns a copy of this parameter on one context. Must have been initialized on this context before. For sparse parameters, use :py:meth:`Parameter.row_sparse_data` instead. Parameters ---------- ctx : Context Desired context. ...
[ "def", "data", "(", "self", ",", "ctx", "=", "None", ")", ":", "if", "self", ".", "_stype", "!=", "'default'", ":", "raise", "RuntimeError", "(", "\"Cannot return a copy of Parameter '%s' on ctx %s via data() \"", "\"because its storage type is %s. Please use row_sparse_dat...
Returns a copy of this parameter on one context. Must have been initialized on this context before. For sparse parameters, use :py:meth:`Parameter.row_sparse_data` instead. Parameters ---------- ctx : Context Desired context. Returns ------- ...
[ "Returns", "a", "copy", "of", "this", "parameter", "on", "one", "context", ".", "Must", "have", "been", "initialized", "on", "this", "context", "before", ".", "For", "sparse", "parameters", "use", ":", "py", ":", "meth", ":", "Parameter", ".", "row_sparse_...
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/gluon/parameter.py#L476-L494
train
apache/incubator-mxnet
python/mxnet/gluon/parameter.py
Parameter.list_data
def list_data(self): """Returns copies of this parameter on all contexts, in the same order as creation. For sparse parameters, use :py:meth:`Parameter.list_row_sparse_data` instead. Returns ------- list of NDArrays """ if self._stype != 'default': ...
python
def list_data(self): """Returns copies of this parameter on all contexts, in the same order as creation. For sparse parameters, use :py:meth:`Parameter.list_row_sparse_data` instead. Returns ------- list of NDArrays """ if self._stype != 'default': ...
[ "def", "list_data", "(", "self", ")", ":", "if", "self", ".", "_stype", "!=", "'default'", ":", "raise", "RuntimeError", "(", "\"Cannot return copies of Parameter '%s' on all contexts via \"", "\"list_data() because its storage type is %s. Please use \"", "\"row_sparse_data() ins...
Returns copies of this parameter on all contexts, in the same order as creation. For sparse parameters, use :py:meth:`Parameter.list_row_sparse_data` instead. Returns ------- list of NDArrays
[ "Returns", "copies", "of", "this", "parameter", "on", "all", "contexts", "in", "the", "same", "order", "as", "creation", ".", "For", "sparse", "parameters", "use", ":", "py", ":", "meth", ":", "Parameter", ".", "list_row_sparse_data", "instead", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/gluon/parameter.py#L496-L509
train
apache/incubator-mxnet
python/mxnet/gluon/parameter.py
Parameter.grad
def grad(self, ctx=None): """Returns a gradient buffer for this parameter on one context. Parameters ---------- ctx : Context Desired context. """ if self._data is not None and self._grad is None: raise RuntimeError( "Cannot get gr...
python
def grad(self, ctx=None): """Returns a gradient buffer for this parameter on one context. Parameters ---------- ctx : Context Desired context. """ if self._data is not None and self._grad is None: raise RuntimeError( "Cannot get gr...
[ "def", "grad", "(", "self", ",", "ctx", "=", "None", ")", ":", "if", "self", ".", "_data", "is", "not", "None", "and", "self", ".", "_grad", "is", "None", ":", "raise", "RuntimeError", "(", "\"Cannot get gradient array for Parameter '%s' \"", "\"because grad_r...
Returns a gradient buffer for this parameter on one context. Parameters ---------- ctx : Context Desired context.
[ "Returns", "a", "gradient", "buffer", "for", "this", "parameter", "on", "one", "context", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/gluon/parameter.py#L511-L523
train
apache/incubator-mxnet
python/mxnet/gluon/parameter.py
Parameter.list_grad
def list_grad(self): """Returns gradient buffers on all contexts, in the same order as :py:meth:`values`.""" if self._data is not None and self._grad is None: raise RuntimeError( "Cannot get gradient array for Parameter '%s' " \ "because grad_req='null...
python
def list_grad(self): """Returns gradient buffers on all contexts, in the same order as :py:meth:`values`.""" if self._data is not None and self._grad is None: raise RuntimeError( "Cannot get gradient array for Parameter '%s' " \ "because grad_req='null...
[ "def", "list_grad", "(", "self", ")", ":", "if", "self", ".", "_data", "is", "not", "None", "and", "self", ".", "_grad", "is", "None", ":", "raise", "RuntimeError", "(", "\"Cannot get gradient array for Parameter '%s' \"", "\"because grad_req='null'\"", "%", "(", ...
Returns gradient buffers on all contexts, in the same order as :py:meth:`values`.
[ "Returns", "gradient", "buffers", "on", "all", "contexts", "in", "the", "same", "order", "as", ":", "py", ":", "meth", ":", "values", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/gluon/parameter.py#L525-L532
train
apache/incubator-mxnet
python/mxnet/gluon/parameter.py
Parameter.list_ctx
def list_ctx(self): """Returns a list of contexts this parameter is initialized on.""" if self._data is None: if self._deferred_init: return self._deferred_init[1] raise RuntimeError("Parameter '%s' has not been initialized"%self.name) return self._ctx_lis...
python
def list_ctx(self): """Returns a list of contexts this parameter is initialized on.""" if self._data is None: if self._deferred_init: return self._deferred_init[1] raise RuntimeError("Parameter '%s' has not been initialized"%self.name) return self._ctx_lis...
[ "def", "list_ctx", "(", "self", ")", ":", "if", "self", ".", "_data", "is", "None", ":", "if", "self", ".", "_deferred_init", ":", "return", "self", ".", "_deferred_init", "[", "1", "]", "raise", "RuntimeError", "(", "\"Parameter '%s' has not been initialized\...
Returns a list of contexts this parameter is initialized on.
[ "Returns", "a", "list", "of", "contexts", "this", "parameter", "is", "initialized", "on", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/gluon/parameter.py#L534-L540
train
apache/incubator-mxnet
python/mxnet/gluon/parameter.py
Parameter.zero_grad
def zero_grad(self): """Sets gradient buffer on all contexts to 0. No action is taken if parameter is uninitialized or doesn't require gradient.""" if self._grad is None: return for i in self._grad: ndarray.zeros_like(i, out=i)
python
def zero_grad(self): """Sets gradient buffer on all contexts to 0. No action is taken if parameter is uninitialized or doesn't require gradient.""" if self._grad is None: return for i in self._grad: ndarray.zeros_like(i, out=i)
[ "def", "zero_grad", "(", "self", ")", ":", "if", "self", ".", "_grad", "is", "None", ":", "return", "for", "i", "in", "self", ".", "_grad", ":", "ndarray", ".", "zeros_like", "(", "i", ",", "out", "=", "i", ")" ]
Sets gradient buffer on all contexts to 0. No action is taken if parameter is uninitialized or doesn't require gradient.
[ "Sets", "gradient", "buffer", "on", "all", "contexts", "to", "0", ".", "No", "action", "is", "taken", "if", "parameter", "is", "uninitialized", "or", "doesn", "t", "require", "gradient", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/gluon/parameter.py#L542-L548
train
apache/incubator-mxnet
python/mxnet/gluon/parameter.py
Parameter.var
def var(self): """Returns a symbol representing this parameter.""" if self._var is None: self._var = symbol.var(self.name, shape=self.shape, dtype=self.dtype, lr_mult=self.lr_mult, wd_mult=self.wd_mult, init=self.init, sty...
python
def var(self): """Returns a symbol representing this parameter.""" if self._var is None: self._var = symbol.var(self.name, shape=self.shape, dtype=self.dtype, lr_mult=self.lr_mult, wd_mult=self.wd_mult, init=self.init, sty...
[ "def", "var", "(", "self", ")", ":", "if", "self", ".", "_var", "is", "None", ":", "self", ".", "_var", "=", "symbol", ".", "var", "(", "self", ".", "name", ",", "shape", "=", "self", ".", "shape", ",", "dtype", "=", "self", ".", "dtype", ",", ...
Returns a symbol representing this parameter.
[ "Returns", "a", "symbol", "representing", "this", "parameter", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/gluon/parameter.py#L550-L556
train
apache/incubator-mxnet
python/mxnet/gluon/parameter.py
Parameter.cast
def cast(self, dtype): """Cast data and gradient of this Parameter to a new data type. Parameters ---------- dtype : str or numpy.dtype The new data type. """ self.dtype = dtype if self._data is None: return with autograd.pause(): ...
python
def cast(self, dtype): """Cast data and gradient of this Parameter to a new data type. Parameters ---------- dtype : str or numpy.dtype The new data type. """ self.dtype = dtype if self._data is None: return with autograd.pause(): ...
[ "def", "cast", "(", "self", ",", "dtype", ")", ":", "self", ".", "dtype", "=", "dtype", "if", "self", ".", "_data", "is", "None", ":", "return", "with", "autograd", ".", "pause", "(", ")", ":", "self", ".", "_data", "=", "[", "i", ".", "astype", ...
Cast data and gradient of this Parameter to a new data type. Parameters ---------- dtype : str or numpy.dtype The new data type.
[ "Cast", "data", "and", "gradient", "of", "this", "Parameter", "to", "a", "new", "data", "type", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/gluon/parameter.py#L558-L574
train
apache/incubator-mxnet
python/mxnet/gluon/parameter.py
ParameterDict.get
def get(self, name, **kwargs): """Retrieves a :py:class:`Parameter` with name ``self.prefix+name``. If not found, :py:func:`get` will first try to retrieve it from "shared" dict. If still not found, :py:func:`get` will create a new :py:class:`Parameter` with key-word arguments and insert...
python
def get(self, name, **kwargs): """Retrieves a :py:class:`Parameter` with name ``self.prefix+name``. If not found, :py:func:`get` will first try to retrieve it from "shared" dict. If still not found, :py:func:`get` will create a new :py:class:`Parameter` with key-word arguments and insert...
[ "def", "get", "(", "self", ",", "name", ",", "*", "*", "kwargs", ")", ":", "name", "=", "self", ".", "prefix", "+", "name", "param", "=", "self", ".", "_get_impl", "(", "name", ")", "if", "param", "is", "None", ":", "# pylint: disable=too-many-nested-b...
Retrieves a :py:class:`Parameter` with name ``self.prefix+name``. If not found, :py:func:`get` will first try to retrieve it from "shared" dict. If still not found, :py:func:`get` will create a new :py:class:`Parameter` with key-word arguments and insert it to self. Parameters -...
[ "Retrieves", "a", ":", "py", ":", "class", ":", "Parameter", "with", "name", "self", ".", "prefix", "+", "name", ".", "If", "not", "found", ":", "py", ":", "func", ":", "get", "will", "first", "try", "to", "retrieve", "it", "from", "shared", "dict", ...
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/gluon/parameter.py#L685-L740
train
apache/incubator-mxnet
python/mxnet/gluon/parameter.py
ParameterDict.get_constant
def get_constant(self, name, value=None): """Retrieves a :py:class:`.Constant` with name ``self.prefix+name``. If not found, :py:func:`get` will first try to retrieve it from "shared" dict. If still not found, :py:func:`get` will create a new :py:class:`.Constant` with key-word arguments...
python
def get_constant(self, name, value=None): """Retrieves a :py:class:`.Constant` with name ``self.prefix+name``. If not found, :py:func:`get` will first try to retrieve it from "shared" dict. If still not found, :py:func:`get` will create a new :py:class:`.Constant` with key-word arguments...
[ "def", "get_constant", "(", "self", ",", "name", ",", "value", "=", "None", ")", ":", "name", "=", "self", ".", "prefix", "+", "name", "param", "=", "self", ".", "_get_impl", "(", "name", ")", "if", "param", "is", "None", ":", "if", "value", "is", ...
Retrieves a :py:class:`.Constant` with name ``self.prefix+name``. If not found, :py:func:`get` will first try to retrieve it from "shared" dict. If still not found, :py:func:`get` will create a new :py:class:`.Constant` with key-word arguments and insert it to self. Parameters -...
[ "Retrieves", "a", ":", "py", ":", "class", ":", ".", "Constant", "with", "name", "self", ".", "prefix", "+", "name", ".", "If", "not", "found", ":", "py", ":", "func", ":", "get", "will", "first", "try", "to", "retrieve", "it", "from", "shared", "d...
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/gluon/parameter.py#L742-L780
train
apache/incubator-mxnet
python/mxnet/gluon/parameter.py
ParameterDict.update
def update(self, other): """Copies all Parameters in ``other`` to self.""" for k, v in other.items(): if k in self._params: assert self._params[k] is v, \ "Cannot update self with other because they have different " \ "Parameters with t...
python
def update(self, other): """Copies all Parameters in ``other`` to self.""" for k, v in other.items(): if k in self._params: assert self._params[k] is v, \ "Cannot update self with other because they have different " \ "Parameters with t...
[ "def", "update", "(", "self", ",", "other", ")", ":", "for", "k", ",", "v", "in", "other", ".", "items", "(", ")", ":", "if", "k", "in", "self", ".", "_params", ":", "assert", "self", ".", "_params", "[", "k", "]", "is", "v", ",", "\"Cannot upd...
Copies all Parameters in ``other`` to self.
[ "Copies", "all", "Parameters", "in", "other", "to", "self", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/gluon/parameter.py#L782-L791
train
apache/incubator-mxnet
python/mxnet/gluon/parameter.py
ParameterDict.initialize
def initialize(self, init=initializer.Uniform(), ctx=None, verbose=False, force_reinit=False): """Initializes all Parameters managed by this dictionary to be used for :py:class:`NDArray` API. It has no effect when using :py:class:`Symbol` API. Parameters ---------- ...
python
def initialize(self, init=initializer.Uniform(), ctx=None, verbose=False, force_reinit=False): """Initializes all Parameters managed by this dictionary to be used for :py:class:`NDArray` API. It has no effect when using :py:class:`Symbol` API. Parameters ---------- ...
[ "def", "initialize", "(", "self", ",", "init", "=", "initializer", ".", "Uniform", "(", ")", ",", "ctx", "=", "None", ",", "verbose", "=", "False", ",", "force_reinit", "=", "False", ")", ":", "if", "verbose", ":", "init", ".", "set_verbosity", "(", ...
Initializes all Parameters managed by this dictionary to be used for :py:class:`NDArray` API. It has no effect when using :py:class:`Symbol` API. Parameters ---------- init : Initializer Global default Initializer to be used when :py:meth:`Parameter.init` is ``None``. ...
[ "Initializes", "all", "Parameters", "managed", "by", "this", "dictionary", "to", "be", "used", "for", ":", "py", ":", "class", ":", "NDArray", "API", ".", "It", "has", "no", "effect", "when", "using", ":", "py", ":", "class", ":", "Symbol", "API", "." ...
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/gluon/parameter.py#L793-L813
train
apache/incubator-mxnet
python/mxnet/gluon/parameter.py
ParameterDict.setattr
def setattr(self, name, value): """Set an attribute to a new value for all Parameters. For example, set grad_req to null if you don't need gradient w.r.t a model's Parameters:: model.collect_params().setattr('grad_req', 'null') or change the learning rate multiplier:: ...
python
def setattr(self, name, value): """Set an attribute to a new value for all Parameters. For example, set grad_req to null if you don't need gradient w.r.t a model's Parameters:: model.collect_params().setattr('grad_req', 'null') or change the learning rate multiplier:: ...
[ "def", "setattr", "(", "self", ",", "name", ",", "value", ")", ":", "for", "i", "in", "self", ".", "values", "(", ")", ":", "setattr", "(", "i", ",", "name", ",", "value", ")" ]
Set an attribute to a new value for all Parameters. For example, set grad_req to null if you don't need gradient w.r.t a model's Parameters:: model.collect_params().setattr('grad_req', 'null') or change the learning rate multiplier:: model.collect_params().setattr('lr...
[ "Set", "an", "attribute", "to", "a", "new", "value", "for", "all", "Parameters", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/gluon/parameter.py#L832-L852
train
apache/incubator-mxnet
python/mxnet/gluon/parameter.py
ParameterDict.save
def save(self, filename, strip_prefix=''): """Save parameters to file. Parameters ---------- filename : str Path to parameter file. strip_prefix : str, default '' Strip prefix from parameter names before saving. """ arg_dict = {} f...
python
def save(self, filename, strip_prefix=''): """Save parameters to file. Parameters ---------- filename : str Path to parameter file. strip_prefix : str, default '' Strip prefix from parameter names before saving. """ arg_dict = {} f...
[ "def", "save", "(", "self", ",", "filename", ",", "strip_prefix", "=", "''", ")", ":", "arg_dict", "=", "{", "}", "for", "param", "in", "self", ".", "values", "(", ")", ":", "weight", "=", "param", ".", "_reduce", "(", ")", "if", "not", "param", ...
Save parameters to file. Parameters ---------- filename : str Path to parameter file. strip_prefix : str, default '' Strip prefix from parameter names before saving.
[ "Save", "parameters", "to", "file", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/gluon/parameter.py#L854-L877
train
apache/incubator-mxnet
python/mxnet/gluon/parameter.py
ParameterDict.load
def load(self, filename, ctx=None, allow_missing=False, ignore_extra=False, restore_prefix=''): """Load parameters from file. Parameters ---------- filename : str Path to parameter file. ctx : Context or list of Context Context(s) initialize ...
python
def load(self, filename, ctx=None, allow_missing=False, ignore_extra=False, restore_prefix=''): """Load parameters from file. Parameters ---------- filename : str Path to parameter file. ctx : Context or list of Context Context(s) initialize ...
[ "def", "load", "(", "self", ",", "filename", ",", "ctx", "=", "None", ",", "allow_missing", "=", "False", ",", "ignore_extra", "=", "False", ",", "restore_prefix", "=", "''", ")", ":", "if", "restore_prefix", ":", "for", "name", "in", "self", ".", "key...
Load parameters from file. Parameters ---------- filename : str Path to parameter file. ctx : Context or list of Context Context(s) initialize loaded parameters on. allow_missing : bool, default False Whether to silently skip loading parameter...
[ "Load", "parameters", "from", "file", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/gluon/parameter.py#L879-L920
train
apache/incubator-mxnet
python/mxnet/torch.py
_make_torch_function
def _make_torch_function(handle): """Create a Torch function from the FunctionHandle.""" # Get the property of function n_used_vars = mx_uint() n_scalars = mx_uint() n_mutate_vars = mx_uint() type_mask = ctypes.c_int() check_call(_LIB.MXFuncDescribe( handle, ctypes.byref(n_us...
python
def _make_torch_function(handle): """Create a Torch function from the FunctionHandle.""" # Get the property of function n_used_vars = mx_uint() n_scalars = mx_uint() n_mutate_vars = mx_uint() type_mask = ctypes.c_int() check_call(_LIB.MXFuncDescribe( handle, ctypes.byref(n_us...
[ "def", "_make_torch_function", "(", "handle", ")", ":", "# Get the property of function", "n_used_vars", "=", "mx_uint", "(", ")", "n_scalars", "=", "mx_uint", "(", ")", "n_mutate_vars", "=", "mx_uint", "(", ")", "type_mask", "=", "ctypes", ".", "c_int", "(", ...
Create a Torch function from the FunctionHandle.
[ "Create", "a", "Torch", "function", "from", "the", "FunctionHandle", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/torch.py#L37-L163
train
apache/incubator-mxnet
python/mxnet/torch.py
_init_torch_module
def _init_torch_module(): """List and add all the torch backed ndarray functions to current module.""" plist = ctypes.POINTER(FunctionHandle)() size = ctypes.c_uint() check_call(_LIB.MXListFunctions(ctypes.byref(size), ctypes.byref(plist))) module_obj = sys.modul...
python
def _init_torch_module(): """List and add all the torch backed ndarray functions to current module.""" plist = ctypes.POINTER(FunctionHandle)() size = ctypes.c_uint() check_call(_LIB.MXListFunctions(ctypes.byref(size), ctypes.byref(plist))) module_obj = sys.modul...
[ "def", "_init_torch_module", "(", ")", ":", "plist", "=", "ctypes", ".", "POINTER", "(", "FunctionHandle", ")", "(", ")", "size", "=", "ctypes", ".", "c_uint", "(", ")", "check_call", "(", "_LIB", ".", "MXListFunctions", "(", "ctypes", ".", "byref", "(",...
List and add all the torch backed ndarray functions to current module.
[ "List", "and", "add", "all", "the", "torch", "backed", "ndarray", "functions", "to", "current", "module", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/torch.py#L167-L180
train
apache/incubator-mxnet
python/mxnet/gluon/model_zoo/vision/inception.py
inception_v3
def inception_v3(pretrained=False, ctx=cpu(), root=os.path.join(base.data_dir(), 'models'), **kwargs): r"""Inception v3 model from `"Rethinking the Inception Architecture for Computer Vision" <http://arxiv.org/abs/1512.00567>`_ paper. Parameters ---------- pretrained : bool, de...
python
def inception_v3(pretrained=False, ctx=cpu(), root=os.path.join(base.data_dir(), 'models'), **kwargs): r"""Inception v3 model from `"Rethinking the Inception Architecture for Computer Vision" <http://arxiv.org/abs/1512.00567>`_ paper. Parameters ---------- pretrained : bool, de...
[ "def", "inception_v3", "(", "pretrained", "=", "False", ",", "ctx", "=", "cpu", "(", ")", ",", "root", "=", "os", ".", "path", ".", "join", "(", "base", ".", "data_dir", "(", ")", ",", "'models'", ")", ",", "*", "*", "kwargs", ")", ":", "net", ...
r"""Inception v3 model from `"Rethinking the Inception Architecture for Computer Vision" <http://arxiv.org/abs/1512.00567>`_ paper. Parameters ---------- pretrained : bool, default False Whether to load the pretrained weights for model. ctx : Context, default CPU The context in ...
[ "r", "Inception", "v3", "model", "from", "Rethinking", "the", "Inception", "Architecture", "for", "Computer", "Vision", "<http", ":", "//", "arxiv", ".", "org", "/", "abs", "/", "1512", ".", "00567", ">", "_", "paper", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/gluon/model_zoo/vision/inception.py#L202-L221
train
apache/incubator-mxnet
python/mxnet/recordio.py
pack
def pack(header, s): """Pack a string into MXImageRecord. Parameters ---------- header : IRHeader Header of the image record. ``header.label`` can be a number or an array. See more detail in ``IRHeader``. s : str Raw image string to be packed. Returns ------- s ...
python
def pack(header, s): """Pack a string into MXImageRecord. Parameters ---------- header : IRHeader Header of the image record. ``header.label`` can be a number or an array. See more detail in ``IRHeader``. s : str Raw image string to be packed. Returns ------- s ...
[ "def", "pack", "(", "header", ",", "s", ")", ":", "header", "=", "IRHeader", "(", "*", "header", ")", "if", "isinstance", "(", "header", ".", "label", ",", "numbers", ".", "Number", ")", ":", "header", "=", "header", ".", "_replace", "(", "flag", "...
Pack a string into MXImageRecord. Parameters ---------- header : IRHeader Header of the image record. ``header.label`` can be a number or an array. See more detail in ``IRHeader``. s : str Raw image string to be packed. Returns ------- s : str The packed str...
[ "Pack", "a", "string", "into", "MXImageRecord", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/recordio.py#L358-L391
train
apache/incubator-mxnet
python/mxnet/recordio.py
unpack
def unpack(s): """Unpack a MXImageRecord to string. Parameters ---------- s : str String buffer from ``MXRecordIO.read``. Returns ------- header : IRHeader Header of the image record. s : str Unpacked string. Examples -------- >>> record = mx.record...
python
def unpack(s): """Unpack a MXImageRecord to string. Parameters ---------- s : str String buffer from ``MXRecordIO.read``. Returns ------- header : IRHeader Header of the image record. s : str Unpacked string. Examples -------- >>> record = mx.record...
[ "def", "unpack", "(", "s", ")", ":", "header", "=", "IRHeader", "(", "*", "struct", ".", "unpack", "(", "_IR_FORMAT", ",", "s", "[", ":", "_IR_SIZE", "]", ")", ")", "s", "=", "s", "[", "_IR_SIZE", ":", "]", "if", "header", ".", "flag", ">", "0"...
Unpack a MXImageRecord to string. Parameters ---------- s : str String buffer from ``MXRecordIO.read``. Returns ------- header : IRHeader Header of the image record. s : str Unpacked string. Examples -------- >>> record = mx.recordio.MXRecordIO('test.re...
[ "Unpack", "a", "MXImageRecord", "to", "string", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/recordio.py#L393-L421
train
apache/incubator-mxnet
python/mxnet/recordio.py
unpack_img
def unpack_img(s, iscolor=-1): """Unpack a MXImageRecord to image. Parameters ---------- s : str String buffer from ``MXRecordIO.read``. iscolor : int Image format option for ``cv2.imdecode``. Returns ------- header : IRHeader Header of the image record. img...
python
def unpack_img(s, iscolor=-1): """Unpack a MXImageRecord to image. Parameters ---------- s : str String buffer from ``MXRecordIO.read``. iscolor : int Image format option for ``cv2.imdecode``. Returns ------- header : IRHeader Header of the image record. img...
[ "def", "unpack_img", "(", "s", ",", "iscolor", "=", "-", "1", ")", ":", "header", ",", "s", "=", "unpack", "(", "s", ")", "img", "=", "np", ".", "frombuffer", "(", "s", ",", "dtype", "=", "np", ".", "uint8", ")", "assert", "cv2", "is", "not", ...
Unpack a MXImageRecord to image. Parameters ---------- s : str String buffer from ``MXRecordIO.read``. iscolor : int Image format option for ``cv2.imdecode``. Returns ------- header : IRHeader Header of the image record. img : numpy.ndarray Unpacked imag...
[ "Unpack", "a", "MXImageRecord", "to", "image", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/recordio.py#L423-L464
train
apache/incubator-mxnet
python/mxnet/recordio.py
pack_img
def pack_img(header, img, quality=95, img_fmt='.jpg'): """Pack an image into ``MXImageRecord``. Parameters ---------- header : IRHeader Header of the image record. ``header.label`` can be a number or an array. See more detail in ``IRHeader``. img : numpy.ndarray Image to be ...
python
def pack_img(header, img, quality=95, img_fmt='.jpg'): """Pack an image into ``MXImageRecord``. Parameters ---------- header : IRHeader Header of the image record. ``header.label`` can be a number or an array. See more detail in ``IRHeader``. img : numpy.ndarray Image to be ...
[ "def", "pack_img", "(", "header", ",", "img", ",", "quality", "=", "95", ",", "img_fmt", "=", "'.jpg'", ")", ":", "assert", "cv2", "is", "not", "None", "jpg_formats", "=", "[", "'.JPG'", ",", "'.JPEG'", "]", "png_formats", "=", "[", "'.PNG'", "]", "e...
Pack an image into ``MXImageRecord``. Parameters ---------- header : IRHeader Header of the image record. ``header.label`` can be a number or an array. See more detail in ``IRHeader``. img : numpy.ndarray Image to be packed. quality : int Quality for JPEG encoding in...
[ "Pack", "an", "image", "into", "MXImageRecord", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/recordio.py#L466-L505
train
apache/incubator-mxnet
python/mxnet/recordio.py
MXRecordIO.open
def open(self): """Opens the record file.""" if self.flag == "w": check_call(_LIB.MXRecordIOWriterCreate(self.uri, ctypes.byref(self.handle))) self.writable = True elif self.flag == "r": check_call(_LIB.MXRecordIOReaderCreate(self.uri, ctypes.byref(self.handle...
python
def open(self): """Opens the record file.""" if self.flag == "w": check_call(_LIB.MXRecordIOWriterCreate(self.uri, ctypes.byref(self.handle))) self.writable = True elif self.flag == "r": check_call(_LIB.MXRecordIOReaderCreate(self.uri, ctypes.byref(self.handle...
[ "def", "open", "(", "self", ")", ":", "if", "self", ".", "flag", "==", "\"w\"", ":", "check_call", "(", "_LIB", ".", "MXRecordIOWriterCreate", "(", "self", ".", "uri", ",", "ctypes", ".", "byref", "(", "self", ".", "handle", ")", ")", ")", "self", ...
Opens the record file.
[ "Opens", "the", "record", "file", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/recordio.py#L73-L84
train
apache/incubator-mxnet
python/mxnet/recordio.py
MXRecordIO._check_pid
def _check_pid(self, allow_reset=False): """Check process id to ensure integrity, reset if in new process.""" if not self.pid == current_process().pid: if allow_reset: self.reset() else: raise RuntimeError("Forbidden operation in multiple processes...
python
def _check_pid(self, allow_reset=False): """Check process id to ensure integrity, reset if in new process.""" if not self.pid == current_process().pid: if allow_reset: self.reset() else: raise RuntimeError("Forbidden operation in multiple processes...
[ "def", "_check_pid", "(", "self", ",", "allow_reset", "=", "False", ")", ":", "if", "not", "self", ".", "pid", "==", "current_process", "(", ")", ".", "pid", ":", "if", "allow_reset", ":", "self", ".", "reset", "(", ")", "else", ":", "raise", "Runtim...
Check process id to ensure integrity, reset if in new process.
[ "Check", "process", "id", "to", "ensure", "integrity", "reset", "if", "in", "new", "process", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/recordio.py#L115-L121
train
apache/incubator-mxnet
python/mxnet/recordio.py
MXRecordIO.close
def close(self): """Closes the record file.""" if not self.is_open: return if self.writable: check_call(_LIB.MXRecordIOWriterFree(self.handle)) else: check_call(_LIB.MXRecordIOReaderFree(self.handle)) self.is_open = False self.pid = Non...
python
def close(self): """Closes the record file.""" if not self.is_open: return if self.writable: check_call(_LIB.MXRecordIOWriterFree(self.handle)) else: check_call(_LIB.MXRecordIOReaderFree(self.handle)) self.is_open = False self.pid = Non...
[ "def", "close", "(", "self", ")", ":", "if", "not", "self", ".", "is_open", ":", "return", "if", "self", ".", "writable", ":", "check_call", "(", "_LIB", ".", "MXRecordIOWriterFree", "(", "self", ".", "handle", ")", ")", "else", ":", "check_call", "(",...
Closes the record file.
[ "Closes", "the", "record", "file", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/recordio.py#L123-L132
train
apache/incubator-mxnet
python/mxnet/recordio.py
MXRecordIO.write
def write(self, buf): """Inserts a string buffer as a record. Examples --------- >>> record = mx.recordio.MXRecordIO('tmp.rec', 'w') >>> for i in range(5): ... record.write('record_%d'%i) >>> record.close() Parameters ---------- buf : ...
python
def write(self, buf): """Inserts a string buffer as a record. Examples --------- >>> record = mx.recordio.MXRecordIO('tmp.rec', 'w') >>> for i in range(5): ... record.write('record_%d'%i) >>> record.close() Parameters ---------- buf : ...
[ "def", "write", "(", "self", ",", "buf", ")", ":", "assert", "self", ".", "writable", "self", ".", "_check_pid", "(", "allow_reset", "=", "False", ")", "check_call", "(", "_LIB", ".", "MXRecordIOWriterWriteRecord", "(", "self", ".", "handle", ",", "ctypes"...
Inserts a string buffer as a record. Examples --------- >>> record = mx.recordio.MXRecordIO('tmp.rec', 'w') >>> for i in range(5): ... record.write('record_%d'%i) >>> record.close() Parameters ---------- buf : string (python2), bytes (python3)...
[ "Inserts", "a", "string", "buffer", "as", "a", "record", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/recordio.py#L155-L174
train
apache/incubator-mxnet
python/mxnet/recordio.py
MXRecordIO.read
def read(self): """Returns record as a string. Examples --------- >>> record = mx.recordio.MXRecordIO('tmp.rec', 'r') >>> for i in range(5): ... item = record.read() ... print(item) record_0 record_1 record_2 record_3 ...
python
def read(self): """Returns record as a string. Examples --------- >>> record = mx.recordio.MXRecordIO('tmp.rec', 'r') >>> for i in range(5): ... item = record.read() ... print(item) record_0 record_1 record_2 record_3 ...
[ "def", "read", "(", "self", ")", ":", "assert", "not", "self", ".", "writable", "# trying to implicitly read from multiple processes is forbidden,", "# there's no elegant way to handle unless lock is introduced", "self", ".", "_check_pid", "(", "allow_reset", "=", "False", ")...
Returns record as a string. Examples --------- >>> record = mx.recordio.MXRecordIO('tmp.rec', 'r') >>> for i in range(5): ... item = record.read() ... print(item) record_0 record_1 record_2 record_3 record_4 >>> recor...
[ "Returns", "record", "as", "a", "string", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/recordio.py#L176-L210
train
apache/incubator-mxnet
python/mxnet/recordio.py
MXIndexedRecordIO.close
def close(self): """Closes the record file.""" if not self.is_open: return super(MXIndexedRecordIO, self).close() self.fidx.close()
python
def close(self): """Closes the record file.""" if not self.is_open: return super(MXIndexedRecordIO, self).close() self.fidx.close()
[ "def", "close", "(", "self", ")", ":", "if", "not", "self", ".", "is_open", ":", "return", "super", "(", "MXIndexedRecordIO", ",", "self", ")", ".", "close", "(", ")", "self", ".", "fidx", ".", "close", "(", ")" ]
Closes the record file.
[ "Closes", "the", "record", "file", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/recordio.py#L255-L260
train
apache/incubator-mxnet
python/mxnet/recordio.py
MXIndexedRecordIO.seek
def seek(self, idx): """Sets the current read pointer position. This function is internally called by `read_idx(idx)` to find the current reader pointer position. It doesn't return anything.""" assert not self.writable self._check_pid(allow_reset=True) pos = ctypes.c_siz...
python
def seek(self, idx): """Sets the current read pointer position. This function is internally called by `read_idx(idx)` to find the current reader pointer position. It doesn't return anything.""" assert not self.writable self._check_pid(allow_reset=True) pos = ctypes.c_siz...
[ "def", "seek", "(", "self", ",", "idx", ")", ":", "assert", "not", "self", ".", "writable", "self", ".", "_check_pid", "(", "allow_reset", "=", "True", ")", "pos", "=", "ctypes", ".", "c_size_t", "(", "self", ".", "idx", "[", "idx", "]", ")", "chec...
Sets the current read pointer position. This function is internally called by `read_idx(idx)` to find the current reader pointer position. It doesn't return anything.
[ "Sets", "the", "current", "read", "pointer", "position", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/recordio.py#L268-L276
train
apache/incubator-mxnet
python/mxnet/recordio.py
MXIndexedRecordIO.tell
def tell(self): """Returns the current position of write head. Examples --------- >>> record = mx.recordio.MXIndexedRecordIO('tmp.idx', 'tmp.rec', 'w') >>> print(record.tell()) 0 >>> for i in range(5): ... record.write_idx(i, 'record_%d'%i) .....
python
def tell(self): """Returns the current position of write head. Examples --------- >>> record = mx.recordio.MXIndexedRecordIO('tmp.idx', 'tmp.rec', 'w') >>> print(record.tell()) 0 >>> for i in range(5): ... record.write_idx(i, 'record_%d'%i) .....
[ "def", "tell", "(", "self", ")", ":", "assert", "self", ".", "writable", "pos", "=", "ctypes", ".", "c_size_t", "(", ")", "check_call", "(", "_LIB", ".", "MXRecordIOWriterTell", "(", "self", ".", "handle", ",", "ctypes", ".", "byref", "(", "pos", ")", ...
Returns the current position of write head. Examples --------- >>> record = mx.recordio.MXIndexedRecordIO('tmp.idx', 'tmp.rec', 'w') >>> print(record.tell()) 0 >>> for i in range(5): ... record.write_idx(i, 'record_%d'%i) ... print(record.tell()) ...
[ "Returns", "the", "current", "position", "of", "write", "head", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/recordio.py#L278-L298
train
apache/incubator-mxnet
python/mxnet/recordio.py
MXIndexedRecordIO.write_idx
def write_idx(self, idx, buf): """Inserts input record at given index. Examples --------- >>> for i in range(5): ... record.write_idx(i, 'record_%d'%i) >>> record.close() Parameters ---------- idx : int Index of a file. bu...
python
def write_idx(self, idx, buf): """Inserts input record at given index. Examples --------- >>> for i in range(5): ... record.write_idx(i, 'record_%d'%i) >>> record.close() Parameters ---------- idx : int Index of a file. bu...
[ "def", "write_idx", "(", "self", ",", "idx", ",", "buf", ")", ":", "key", "=", "self", ".", "key_type", "(", "idx", ")", "pos", "=", "self", ".", "tell", "(", ")", "self", ".", "write", "(", "buf", ")", "self", ".", "fidx", ".", "write", "(", ...
Inserts input record at given index. Examples --------- >>> for i in range(5): ... record.write_idx(i, 'record_%d'%i) >>> record.close() Parameters ---------- idx : int Index of a file. buf : Record to write.
[ "Inserts", "input", "record", "at", "given", "index", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/recordio.py#L316-L337
train
apache/incubator-mxnet
python/mxnet/notebook/callback.py
_add_new_columns
def _add_new_columns(dataframe, metrics): """Add new metrics as new columns to selected pandas dataframe. Parameters ---------- dataframe : pandas.DataFrame Selected dataframe needs to be modified. metrics : metric.EvalMetric New metrics to be added. """ #TODO(leodirac): we ...
python
def _add_new_columns(dataframe, metrics): """Add new metrics as new columns to selected pandas dataframe. Parameters ---------- dataframe : pandas.DataFrame Selected dataframe needs to be modified. metrics : metric.EvalMetric New metrics to be added. """ #TODO(leodirac): we ...
[ "def", "_add_new_columns", "(", "dataframe", ",", "metrics", ")", ":", "#TODO(leodirac): we don't really need to do this on every update. Optimize", "new_columns", "=", "set", "(", "metrics", ".", "keys", "(", ")", ")", "-", "set", "(", "dataframe", ".", "columns", ...
Add new metrics as new columns to selected pandas dataframe. Parameters ---------- dataframe : pandas.DataFrame Selected dataframe needs to be modified. metrics : metric.EvalMetric New metrics to be added.
[ "Add", "new", "metrics", "as", "new", "columns", "to", "selected", "pandas", "dataframe", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/notebook/callback.py#L49-L62
train
apache/incubator-mxnet
python/mxnet/notebook/callback.py
args_wrapper
def args_wrapper(*args): """Generates callback arguments for model.fit() for a set of callback objects. Callback objects like PandasLogger(), LiveLearningCurve() get passed in. This assembles all their callback arguments. """ out = defaultdict(list) for callback in args: callback_ar...
python
def args_wrapper(*args): """Generates callback arguments for model.fit() for a set of callback objects. Callback objects like PandasLogger(), LiveLearningCurve() get passed in. This assembles all their callback arguments. """ out = defaultdict(list) for callback in args: callback_ar...
[ "def", "args_wrapper", "(", "*", "args", ")", ":", "out", "=", "defaultdict", "(", "list", ")", "for", "callback", "in", "args", ":", "callback_args", "=", "callback", ".", "callback_args", "(", ")", "for", "k", ",", "v", "in", "callback_args", ".", "i...
Generates callback arguments for model.fit() for a set of callback objects. Callback objects like PandasLogger(), LiveLearningCurve() get passed in. This assembles all their callback arguments.
[ "Generates", "callback", "arguments", "for", "model", ".", "fit", "()", "for", "a", "set", "of", "callback", "objects", ".", "Callback", "objects", "like", "PandasLogger", "()", "LiveLearningCurve", "()", "get", "passed", "in", ".", "This", "assembles", "all",...
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/notebook/callback.py#L392-L403
train
apache/incubator-mxnet
python/mxnet/notebook/callback.py
PandasLogger.append_metrics
def append_metrics(self, metrics, df_name): """Append new metrics to selected dataframes. Parameters ---------- metrics : metric.EvalMetric New metrics to be added. df_name : str Name of the dataframe to be modified. """ dataframe = self._...
python
def append_metrics(self, metrics, df_name): """Append new metrics to selected dataframes. Parameters ---------- metrics : metric.EvalMetric New metrics to be added. df_name : str Name of the dataframe to be modified. """ dataframe = self._...
[ "def", "append_metrics", "(", "self", ",", "metrics", ",", "df_name", ")", ":", "dataframe", "=", "self", ".", "_dataframes", "[", "df_name", "]", "_add_new_columns", "(", "dataframe", ",", "metrics", ")", "dataframe", ".", "loc", "[", "len", "(", "datafra...
Append new metrics to selected dataframes. Parameters ---------- metrics : metric.EvalMetric New metrics to be added. df_name : str Name of the dataframe to be modified.
[ "Append", "new", "metrics", "to", "selected", "dataframes", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/notebook/callback.py#L130-L142
train
apache/incubator-mxnet
python/mxnet/notebook/callback.py
PandasLogger.train_cb
def train_cb(self, param): """Callback funtion for training. """ if param.nbatch % self.frequent == 0: self._process_batch(param, 'train')
python
def train_cb(self, param): """Callback funtion for training. """ if param.nbatch % self.frequent == 0: self._process_batch(param, 'train')
[ "def", "train_cb", "(", "self", ",", "param", ")", ":", "if", "param", ".", "nbatch", "%", "self", ".", "frequent", "==", "0", ":", "self", ".", "_process_batch", "(", "param", ",", "'train'", ")" ]
Callback funtion for training.
[ "Callback", "funtion", "for", "training", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/notebook/callback.py#L144-L148
train
apache/incubator-mxnet
python/mxnet/notebook/callback.py
PandasLogger._process_batch
def _process_batch(self, param, dataframe): """Update parameters for selected dataframe after a completed batch Parameters ---------- dataframe : pandas.DataFrame Selected dataframe needs to be modified. """ now = time.time() if param.eval_metric is no...
python
def _process_batch(self, param, dataframe): """Update parameters for selected dataframe after a completed batch Parameters ---------- dataframe : pandas.DataFrame Selected dataframe needs to be modified. """ now = time.time() if param.eval_metric is no...
[ "def", "_process_batch", "(", "self", ",", "param", ",", "dataframe", ")", ":", "now", "=", "time", ".", "time", "(", ")", "if", "param", ".", "eval_metric", "is", "not", "None", ":", "metrics", "=", "dict", "(", "param", ".", "eval_metric", ".", "ge...
Update parameters for selected dataframe after a completed batch Parameters ---------- dataframe : pandas.DataFrame Selected dataframe needs to be modified.
[ "Update", "parameters", "for", "selected", "dataframe", "after", "a", "completed", "batch", "Parameters", "----------", "dataframe", ":", "pandas", ".", "DataFrame", "Selected", "dataframe", "needs", "to", "be", "modified", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/notebook/callback.py#L155-L179
train
apache/incubator-mxnet
python/mxnet/notebook/callback.py
PandasLogger.epoch_cb
def epoch_cb(self): """Callback function after each epoch. Now it records each epoch time and append it to epoch dataframe. """ metrics = {} metrics['elapsed'] = self.elapsed() now = datetime.datetime.now() metrics['epoch_time'] = now - self.last_epoch_time ...
python
def epoch_cb(self): """Callback function after each epoch. Now it records each epoch time and append it to epoch dataframe. """ metrics = {} metrics['elapsed'] = self.elapsed() now = datetime.datetime.now() metrics['epoch_time'] = now - self.last_epoch_time ...
[ "def", "epoch_cb", "(", "self", ")", ":", "metrics", "=", "{", "}", "metrics", "[", "'elapsed'", "]", "=", "self", ".", "elapsed", "(", ")", "now", "=", "datetime", ".", "datetime", ".", "now", "(", ")", "metrics", "[", "'epoch_time'", "]", "=", "n...
Callback function after each epoch. Now it records each epoch time and append it to epoch dataframe.
[ "Callback", "function", "after", "each", "epoch", ".", "Now", "it", "records", "each", "epoch", "time", "and", "append", "it", "to", "epoch", "dataframe", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/notebook/callback.py#L181-L190
train
apache/incubator-mxnet
python/mxnet/notebook/callback.py
LiveBokehChart._push_render
def _push_render(self): """Render the plot with bokeh.io and push to notebook. """ bokeh.io.push_notebook(handle=self.handle) self.last_update = time.time()
python
def _push_render(self): """Render the plot with bokeh.io and push to notebook. """ bokeh.io.push_notebook(handle=self.handle) self.last_update = time.time()
[ "def", "_push_render", "(", "self", ")", ":", "bokeh", ".", "io", ".", "push_notebook", "(", "handle", "=", "self", ".", "handle", ")", "self", ".", "last_update", "=", "time", ".", "time", "(", ")" ]
Render the plot with bokeh.io and push to notebook.
[ "Render", "the", "plot", "with", "bokeh", ".", "io", "and", "push", "to", "notebook", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/notebook/callback.py#L243-L247
train
apache/incubator-mxnet
python/mxnet/notebook/callback.py
LiveLearningCurve._process_batch
def _process_batch(self, param, df_name): """Update selected dataframe after a completed batch Parameters ---------- df_name : str Selected dataframe name needs to be modified. """ if param.eval_metric is not None: metrics = dict(param.eval_metric....
python
def _process_batch(self, param, df_name): """Update selected dataframe after a completed batch Parameters ---------- df_name : str Selected dataframe name needs to be modified. """ if param.eval_metric is not None: metrics = dict(param.eval_metric....
[ "def", "_process_batch", "(", "self", ",", "param", ",", "df_name", ")", ":", "if", "param", ".", "eval_metric", "is", "not", "None", ":", "metrics", "=", "dict", "(", "param", ".", "eval_metric", ".", "get_name_value", "(", ")", ")", "param", ".", "ev...
Update selected dataframe after a completed batch Parameters ---------- df_name : str Selected dataframe name needs to be modified.
[ "Update", "selected", "dataframe", "after", "a", "completed", "batch", "Parameters", "----------", "df_name", ":", "str", "Selected", "dataframe", "name", "needs", "to", "be", "modified", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/notebook/callback.py#L360-L376
train
apache/incubator-mxnet
example/named_entity_recognition/src/ner.py
build_vocab
def build_vocab(nested_list): """ :param nested_list: list of list of string :return: dictionary mapping from string to int, inverse of that dictionary """ # Build vocabulary word_counts = Counter(itertools.chain(*nested_list)) # Mapping from index to label vocabulary_inv = [x[0] for x ...
python
def build_vocab(nested_list): """ :param nested_list: list of list of string :return: dictionary mapping from string to int, inverse of that dictionary """ # Build vocabulary word_counts = Counter(itertools.chain(*nested_list)) # Mapping from index to label vocabulary_inv = [x[0] for x ...
[ "def", "build_vocab", "(", "nested_list", ")", ":", "# Build vocabulary", "word_counts", "=", "Counter", "(", "itertools", ".", "chain", "(", "*", "nested_list", ")", ")", "# Mapping from index to label", "vocabulary_inv", "=", "[", "x", "[", "0", "]", "for", ...
:param nested_list: list of list of string :return: dictionary mapping from string to int, inverse of that dictionary
[ ":", "param", "nested_list", ":", "list", "of", "list", "of", "string", ":", "return", ":", "dictionary", "mapping", "from", "string", "to", "int", "inverse", "of", "that", "dictionary" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/named_entity_recognition/src/ner.py#L89-L102
train
apache/incubator-mxnet
example/named_entity_recognition/src/ner.py
build_iters
def build_iters(data_dir, max_records, train_fraction, batch_size, buckets=None): """ Reads a csv of sentences/tag sequences into a pandas dataframe. Converts into X = array(list(int)) & Y = array(list(int)) Splits into training and test sets Builds dictionaries mapping from index labels to labels/ ...
python
def build_iters(data_dir, max_records, train_fraction, batch_size, buckets=None): """ Reads a csv of sentences/tag sequences into a pandas dataframe. Converts into X = array(list(int)) & Y = array(list(int)) Splits into training and test sets Builds dictionaries mapping from index labels to labels/ ...
[ "def", "build_iters", "(", "data_dir", ",", "max_records", ",", "train_fraction", ",", "batch_size", ",", "buckets", "=", "None", ")", ":", "# Read in data as numpy array", "df", "=", "pd", ".", "read_pickle", "(", "os", ".", "path", ".", "join", "(", "data_...
Reads a csv of sentences/tag sequences into a pandas dataframe. Converts into X = array(list(int)) & Y = array(list(int)) Splits into training and test sets Builds dictionaries mapping from index labels to labels/ indexed features to features :param data_dir: directory to read in csv data from :para...
[ "Reads", "a", "csv", "of", "sentences", "/", "tag", "sequences", "into", "a", "pandas", "dataframe", ".", "Converts", "into", "X", "=", "array", "(", "list", "(", "int", "))", "&", "Y", "=", "array", "(", "list", "(", "int", "))", "Splits", "into", ...
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/named_entity_recognition/src/ner.py#L104-L146
train
apache/incubator-mxnet
example/named_entity_recognition/src/ner.py
sym_gen
def sym_gen(seq_len): """ Build NN symbol depending on the length of the input sequence """ sentence_shape = train_iter.provide_data[0][1] char_sentence_shape = train_iter.provide_data[1][1] entities_shape = train_iter.provide_label[0][1] X_sent = mx.symbol.Variable(train_iter.provide_data[...
python
def sym_gen(seq_len): """ Build NN symbol depending on the length of the input sequence """ sentence_shape = train_iter.provide_data[0][1] char_sentence_shape = train_iter.provide_data[1][1] entities_shape = train_iter.provide_label[0][1] X_sent = mx.symbol.Variable(train_iter.provide_data[...
[ "def", "sym_gen", "(", "seq_len", ")", ":", "sentence_shape", "=", "train_iter", ".", "provide_data", "[", "0", "]", "[", "1", "]", "char_sentence_shape", "=", "train_iter", ".", "provide_data", "[", "1", "]", "[", "1", "]", "entities_shape", "=", "train_i...
Build NN symbol depending on the length of the input sequence
[ "Build", "NN", "symbol", "depending", "on", "the", "length", "of", "the", "input", "sequence" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/named_entity_recognition/src/ner.py#L148-L203
train
apache/incubator-mxnet
python/mxnet/symbol/contrib.py
rand_zipfian
def rand_zipfian(true_classes, num_sampled, range_max): """Draw random samples from an approximately log-uniform or Zipfian distribution. This operation randomly samples *num_sampled* candidates the range of integers [0, range_max). The elements of sampled_candidates are drawn with replacement from the bas...
python
def rand_zipfian(true_classes, num_sampled, range_max): """Draw random samples from an approximately log-uniform or Zipfian distribution. This operation randomly samples *num_sampled* candidates the range of integers [0, range_max). The elements of sampled_candidates are drawn with replacement from the bas...
[ "def", "rand_zipfian", "(", "true_classes", ",", "num_sampled", ",", "range_max", ")", ":", "assert", "(", "isinstance", "(", "true_classes", ",", "Symbol", ")", ")", ",", "\"unexpected type %s\"", "%", "type", "(", "true_classes", ")", "log_range", "=", "math...
Draw random samples from an approximately log-uniform or Zipfian distribution. This operation randomly samples *num_sampled* candidates the range of integers [0, range_max). The elements of sampled_candidates are drawn with replacement from the base distribution. The base distribution for this operator is...
[ "Draw", "random", "samples", "from", "an", "approximately", "log", "-", "uniform", "or", "Zipfian", "distribution", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/symbol/contrib.py#L39-L98
train
apache/incubator-mxnet
python/mxnet/symbol/contrib.py
foreach
def foreach(body, data, init_states, name="foreach"): """Run a for loop with user-defined computation over Symbols on dimension 0. This operator simulates a for loop and body has the computation for an iteration of the for loop. It runs the computation in body on each slice from the input NDArrays. ...
python
def foreach(body, data, init_states, name="foreach"): """Run a for loop with user-defined computation over Symbols on dimension 0. This operator simulates a for loop and body has the computation for an iteration of the for loop. It runs the computation in body on each slice from the input NDArrays. ...
[ "def", "foreach", "(", "body", ",", "data", ",", "init_states", ",", "name", "=", "\"foreach\"", ")", ":", "flatten_data", ",", "data_fmt", "=", "_flatten", "(", "data", ",", "\"foreach input\"", ")", "_check_data", "(", "flatten_data", ",", "symbol", ".", ...
Run a for loop with user-defined computation over Symbols on dimension 0. This operator simulates a for loop and body has the computation for an iteration of the for loop. It runs the computation in body on each slice from the input NDArrays. body takes two arguments as input and outputs a tuple of tw...
[ "Run", "a", "for", "loop", "with", "user", "-", "defined", "computation", "over", "Symbols", "on", "dimension", "0", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/symbol/contrib.py#L212-L373
train
apache/incubator-mxnet
python/mxnet/symbol/contrib.py
while_loop
def while_loop(cond, func, loop_vars, max_iterations=None, name="while_loop"): """Run a while loop with user-defined computation and loop condition. This operator simulates a while loop which iterately does customized computation as long as the condition is satisfied. `loop_vars` is a Symbol or nested...
python
def while_loop(cond, func, loop_vars, max_iterations=None, name="while_loop"): """Run a while loop with user-defined computation and loop condition. This operator simulates a while loop which iterately does customized computation as long as the condition is satisfied. `loop_vars` is a Symbol or nested...
[ "def", "while_loop", "(", "cond", ",", "func", ",", "loop_vars", ",", "max_iterations", "=", "None", ",", "name", "=", "\"while_loop\"", ")", ":", "def", "_to_python_scalar", "(", "inputs", ",", "type_", ",", "name", ")", ":", "\"\"\"Converts \"inputs\", possi...
Run a while loop with user-defined computation and loop condition. This operator simulates a while loop which iterately does customized computation as long as the condition is satisfied. `loop_vars` is a Symbol or nested lists of Symbols on which the computation uses. `cond` is a user-defined functio...
[ "Run", "a", "while", "loop", "with", "user", "-", "defined", "computation", "and", "loop", "condition", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/symbol/contrib.py#L375-L596
train
apache/incubator-mxnet
python/mxnet/symbol/contrib.py
cond
def cond(pred, then_func, else_func, name="cond"): """Run an if-then-else using user-defined condition and computation This operator simulates a if-like branch which chooses to do one of the two customized computations according to the specified condition. `pred` is a scalar MXNet Symbol, indicati...
python
def cond(pred, then_func, else_func, name="cond"): """Run an if-then-else using user-defined condition and computation This operator simulates a if-like branch which chooses to do one of the two customized computations according to the specified condition. `pred` is a scalar MXNet Symbol, indicati...
[ "def", "cond", "(", "pred", ",", "then_func", ",", "else_func", ",", "name", "=", "\"cond\"", ")", ":", "def", "_create_subgraph", "(", "graph_vars", ",", "graph_func", ",", "subgraph_name", ")", ":", "subgraph_name", "=", "_get_unique_subgraph_name", "(", "su...
Run an if-then-else using user-defined condition and computation This operator simulates a if-like branch which chooses to do one of the two customized computations according to the specified condition. `pred` is a scalar MXNet Symbol, indicating which branch of computation should be used. `then_...
[ "Run", "an", "if", "-", "then", "-", "else", "using", "user", "-", "defined", "condition", "and", "computation" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/symbol/contrib.py#L598-L729
train
apache/incubator-mxnet
python/mxnet/contrib/text/vocab.py
Vocabulary._index_unknown_and_reserved_tokens
def _index_unknown_and_reserved_tokens(self, unknown_token, reserved_tokens): """Indexes unknown and reserved tokens.""" self._unknown_token = unknown_token # Thus, constants.UNKNOWN_IDX must be 0. self._idx_to_token = [unknown_token] if reserved_tokens is None: sel...
python
def _index_unknown_and_reserved_tokens(self, unknown_token, reserved_tokens): """Indexes unknown and reserved tokens.""" self._unknown_token = unknown_token # Thus, constants.UNKNOWN_IDX must be 0. self._idx_to_token = [unknown_token] if reserved_tokens is None: sel...
[ "def", "_index_unknown_and_reserved_tokens", "(", "self", ",", "unknown_token", ",", "reserved_tokens", ")", ":", "self", ".", "_unknown_token", "=", "unknown_token", "# Thus, constants.UNKNOWN_IDX must be 0.", "self", ".", "_idx_to_token", "=", "[", "unknown_token", "]",...
Indexes unknown and reserved tokens.
[ "Indexes", "unknown", "and", "reserved", "tokens", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/contrib/text/vocab.py#L94-L107
train
apache/incubator-mxnet
python/mxnet/contrib/text/vocab.py
Vocabulary._index_counter_keys
def _index_counter_keys(self, counter, unknown_token, reserved_tokens, most_freq_count, min_freq): """Indexes keys of `counter`. Indexes keys of `counter` according to frequency thresholds such as `most_freq_count` and `min_freq`. """ assert isinsta...
python
def _index_counter_keys(self, counter, unknown_token, reserved_tokens, most_freq_count, min_freq): """Indexes keys of `counter`. Indexes keys of `counter` according to frequency thresholds such as `most_freq_count` and `min_freq`. """ assert isinsta...
[ "def", "_index_counter_keys", "(", "self", ",", "counter", ",", "unknown_token", ",", "reserved_tokens", ",", "most_freq_count", ",", "min_freq", ")", ":", "assert", "isinstance", "(", "counter", ",", "collections", ".", "Counter", ")", ",", "'`counter` must be an...
Indexes keys of `counter`. Indexes keys of `counter` according to frequency thresholds such as `most_freq_count` and `min_freq`.
[ "Indexes", "keys", "of", "counter", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/contrib/text/vocab.py#L109-L135
train
apache/incubator-mxnet
python/mxnet/contrib/text/vocab.py
Vocabulary.to_indices
def to_indices(self, tokens): """Converts tokens to indices according to the vocabulary. Parameters ---------- tokens : str or list of strs A source token or tokens to be converted. Returns ------- int or list of ints A token index or a...
python
def to_indices(self, tokens): """Converts tokens to indices according to the vocabulary. Parameters ---------- tokens : str or list of strs A source token or tokens to be converted. Returns ------- int or list of ints A token index or a...
[ "def", "to_indices", "(", "self", ",", "tokens", ")", ":", "to_reduce", "=", "False", "if", "not", "isinstance", "(", "tokens", ",", "list", ")", ":", "tokens", "=", "[", "tokens", "]", "to_reduce", "=", "True", "indices", "=", "[", "self", ".", "tok...
Converts tokens to indices according to the vocabulary. Parameters ---------- tokens : str or list of strs A source token or tokens to be converted. Returns ------- int or list of ints A token index or a list of token indices according to the v...
[ "Converts", "tokens", "to", "indices", "according", "to", "the", "vocabulary", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/contrib/text/vocab.py#L162-L186
train
apache/incubator-mxnet
python/mxnet/contrib/text/vocab.py
Vocabulary.to_tokens
def to_tokens(self, indices): """Converts token indices to tokens according to the vocabulary. Parameters ---------- indices : int or list of ints A source token index or token indices to be converted. Returns ------- str or list of strs ...
python
def to_tokens(self, indices): """Converts token indices to tokens according to the vocabulary. Parameters ---------- indices : int or list of ints A source token index or token indices to be converted. Returns ------- str or list of strs ...
[ "def", "to_tokens", "(", "self", ",", "indices", ")", ":", "to_reduce", "=", "False", "if", "not", "isinstance", "(", "indices", ",", "list", ")", ":", "indices", "=", "[", "indices", "]", "to_reduce", "=", "True", "max_idx", "=", "len", "(", "self", ...
Converts token indices to tokens according to the vocabulary. Parameters ---------- indices : int or list of ints A source token index or token indices to be converted. Returns ------- str or list of strs A token or a list of tokens according t...
[ "Converts", "token", "indices", "to", "tokens", "according", "to", "the", "vocabulary", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/contrib/text/vocab.py#L188-L218
train
apache/incubator-mxnet
python/mxnet/io/io.py
_make_io_iterator
def _make_io_iterator(handle): """Create an io iterator by handle.""" name = ctypes.c_char_p() desc = ctypes.c_char_p() num_args = mx_uint() arg_names = ctypes.POINTER(ctypes.c_char_p)() arg_types = ctypes.POINTER(ctypes.c_char_p)() arg_descs = ctypes.POINTER(ctypes.c_char_p)() check_ca...
python
def _make_io_iterator(handle): """Create an io iterator by handle.""" name = ctypes.c_char_p() desc = ctypes.c_char_p() num_args = mx_uint() arg_names = ctypes.POINTER(ctypes.c_char_p)() arg_types = ctypes.POINTER(ctypes.c_char_p)() arg_descs = ctypes.POINTER(ctypes.c_char_p)() check_ca...
[ "def", "_make_io_iterator", "(", "handle", ")", ":", "name", "=", "ctypes", ".", "c_char_p", "(", ")", "desc", "=", "ctypes", ".", "c_char_p", "(", ")", "num_args", "=", "mx_uint", "(", ")", "arg_names", "=", "ctypes", ".", "POINTER", "(", "ctypes", "....
Create an io iterator by handle.
[ "Create", "an", "io", "iterator", "by", "handle", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/io/io.py#L899-L967
train
apache/incubator-mxnet
python/mxnet/io/io.py
_init_io_module
def _init_io_module(): """List and add all the data iterators to current module.""" plist = ctypes.POINTER(ctypes.c_void_p)() size = ctypes.c_uint() check_call(_LIB.MXListDataIters(ctypes.byref(size), ctypes.byref(plist))) module_obj = sys.modules[__name__] for i in range(size.value): hd...
python
def _init_io_module(): """List and add all the data iterators to current module.""" plist = ctypes.POINTER(ctypes.c_void_p)() size = ctypes.c_uint() check_call(_LIB.MXListDataIters(ctypes.byref(size), ctypes.byref(plist))) module_obj = sys.modules[__name__] for i in range(size.value): hd...
[ "def", "_init_io_module", "(", ")", ":", "plist", "=", "ctypes", ".", "POINTER", "(", "ctypes", ".", "c_void_p", ")", "(", ")", "size", "=", "ctypes", ".", "c_uint", "(", ")", "check_call", "(", "_LIB", ".", "MXListDataIters", "(", "ctypes", ".", "byre...
List and add all the data iterators to current module.
[ "List", "and", "add", "all", "the", "data", "iterators", "to", "current", "module", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/io/io.py#L969-L978
train
apache/incubator-mxnet
python/mxnet/io/io.py
DataDesc.get_list
def get_list(shapes, types): """Get DataDesc list from attribute lists. Parameters ---------- shapes : a tuple of (name_, shape_) types : a tuple of (name_, np.dtype) """ if types is not None: type_dict = dict(types) return [DataDesc(x[0]...
python
def get_list(shapes, types): """Get DataDesc list from attribute lists. Parameters ---------- shapes : a tuple of (name_, shape_) types : a tuple of (name_, np.dtype) """ if types is not None: type_dict = dict(types) return [DataDesc(x[0]...
[ "def", "get_list", "(", "shapes", ",", "types", ")", ":", "if", "types", "is", "not", "None", ":", "type_dict", "=", "dict", "(", "types", ")", "return", "[", "DataDesc", "(", "x", "[", "0", "]", ",", "x", "[", "1", "]", ",", "type_dict", "[", ...
Get DataDesc list from attribute lists. Parameters ---------- shapes : a tuple of (name_, shape_) types : a tuple of (name_, np.dtype)
[ "Get", "DataDesc", "list", "from", "attribute", "lists", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/io/io.py#L100-L112
train
apache/incubator-mxnet
python/mxnet/io/io.py
DataIter.next
def next(self): """Get next data batch from iterator. Returns ------- DataBatch The data of next batch. Raises ------ StopIteration If the end of the data is reached. """ if self.iter_next(): return DataBatch(d...
python
def next(self): """Get next data batch from iterator. Returns ------- DataBatch The data of next batch. Raises ------ StopIteration If the end of the data is reached. """ if self.iter_next(): return DataBatch(d...
[ "def", "next", "(", "self", ")", ":", "if", "self", ".", "iter_next", "(", ")", ":", "return", "DataBatch", "(", "data", "=", "self", ".", "getdata", "(", ")", ",", "label", "=", "self", ".", "getlabel", "(", ")", ",", "pad", "=", "self", ".", ...
Get next data batch from iterator. Returns ------- DataBatch The data of next batch. Raises ------ StopIteration If the end of the data is reached.
[ "Get", "next", "data", "batch", "from", "iterator", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/io/io.py#L208-L225
train