id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
24,100
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
24,101
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
24,102
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
24,103
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
24,104
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
24,105
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
24,106
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
24,107
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
24,108
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
24,109
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
24,110
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
24,111
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
24,112
apache/incubator-mxnet
python/mxnet/io/io.py
NDArrayIter.hard_reset
def hard_reset(self): """Ignore roll over data and set to start.""" if self.shuffle: self._shuffle_data() self.cursor = -self.batch_size self._cache_data = None self._cache_label = None
python
def hard_reset(self): """Ignore roll over data and set to start.""" if self.shuffle: self._shuffle_data() self.cursor = -self.batch_size self._cache_data = None self._cache_label = None
[ "def", "hard_reset", "(", "self", ")", ":", "if", "self", ".", "shuffle", ":", "self", ".", "_shuffle_data", "(", ")", "self", ".", "cursor", "=", "-", "self", ".", "batch_size", "self", ".", "_cache_data", "=", "None", "self", ".", "_cache_label", "="...
Ignore roll over data and set to start.
[ "Ignore", "roll", "over", "data", "and", "set", "to", "start", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/io/io.py#L650-L656
24,113
apache/incubator-mxnet
python/mxnet/io/io.py
NDArrayIter.iter_next
def iter_next(self): """Increments the coursor by batch_size for next batch and check current cursor if it exceed the number of data points.""" self.cursor += self.batch_size return self.cursor < self.num_data
python
def iter_next(self): """Increments the coursor by batch_size for next batch and check current cursor if it exceed the number of data points.""" self.cursor += self.batch_size return self.cursor < self.num_data
[ "def", "iter_next", "(", "self", ")", ":", "self", ".", "cursor", "+=", "self", ".", "batch_size", "return", "self", ".", "cursor", "<", "self", ".", "num_data" ]
Increments the coursor by batch_size for next batch and check current cursor if it exceed the number of data points.
[ "Increments", "the", "coursor", "by", "batch_size", "for", "next", "batch", "and", "check", "current", "cursor", "if", "it", "exceed", "the", "number", "of", "data", "points", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/io/io.py#L670-L674
24,114
apache/incubator-mxnet
python/mxnet/io/io.py
NDArrayIter._getdata
def _getdata(self, data_source, start=None, end=None): """Load data from underlying arrays.""" assert start is not None or end is not None, 'should at least specify start or end' start = start if start is not None else 0 if end is None: end = data_source[0][1].shape[0] if dat...
python
def _getdata(self, data_source, start=None, end=None): """Load data from underlying arrays.""" assert start is not None or end is not None, 'should at least specify start or end' start = start if start is not None else 0 if end is None: end = data_source[0][1].shape[0] if dat...
[ "def", "_getdata", "(", "self", ",", "data_source", ",", "start", "=", "None", ",", "end", "=", "None", ")", ":", "assert", "start", "is", "not", "None", "or", "end", "is", "not", "None", ",", "'should at least specify start or end'", "start", "=", "start"...
Load data from underlying arrays.
[ "Load", "data", "from", "underlying", "arrays", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/io/io.py#L691-L706
24,115
apache/incubator-mxnet
python/mxnet/io/io.py
NDArrayIter._concat
def _concat(self, first_data, second_data): """Helper function to concat two NDArrays.""" assert len(first_data) == len( second_data), 'data source should contain the same size' if first_data and second_data: return [ concat( first_data...
python
def _concat(self, first_data, second_data): """Helper function to concat two NDArrays.""" assert len(first_data) == len( second_data), 'data source should contain the same size' if first_data and second_data: return [ concat( first_data...
[ "def", "_concat", "(", "self", ",", "first_data", ",", "second_data", ")", ":", "assert", "len", "(", "first_data", ")", "==", "len", "(", "second_data", ")", ",", "'data source should contain the same size'", "if", "first_data", "and", "second_data", ":", "retu...
Helper function to concat two NDArrays.
[ "Helper", "function", "to", "concat", "two", "NDArrays", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/io/io.py#L708-L726
24,116
apache/incubator-mxnet
python/mxnet/io/io.py
NDArrayIter._batchify
def _batchify(self, data_source): """Load data from underlying arrays, internal use only.""" assert self.cursor < self.num_data, 'DataIter needs reset.' # first batch of next epoch with 'roll_over' if self.last_batch_handle == 'roll_over' and \ -self.batch_size < self.cursor ...
python
def _batchify(self, data_source): """Load data from underlying arrays, internal use only.""" assert self.cursor < self.num_data, 'DataIter needs reset.' # first batch of next epoch with 'roll_over' if self.last_batch_handle == 'roll_over' and \ -self.batch_size < self.cursor ...
[ "def", "_batchify", "(", "self", ",", "data_source", ")", ":", "assert", "self", ".", "cursor", "<", "self", ".", "num_data", ",", "'DataIter needs reset.'", "# first batch of next epoch with 'roll_over'", "if", "self", ".", "last_batch_handle", "==", "'roll_over'", ...
Load data from underlying arrays, internal use only.
[ "Load", "data", "from", "underlying", "arrays", "internal", "use", "only", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/io/io.py#L728-L758
24,117
apache/incubator-mxnet
python/mxnet/io/io.py
NDArrayIter.getpad
def getpad(self): """Get pad value of DataBatch.""" if self.last_batch_handle == 'pad' and \ self.cursor + self.batch_size > self.num_data: return self.cursor + self.batch_size - self.num_data # check the first batch elif self.last_batch_handle == 'roll_over' and \...
python
def getpad(self): """Get pad value of DataBatch.""" if self.last_batch_handle == 'pad' and \ self.cursor + self.batch_size > self.num_data: return self.cursor + self.batch_size - self.num_data # check the first batch elif self.last_batch_handle == 'roll_over' and \...
[ "def", "getpad", "(", "self", ")", ":", "if", "self", ".", "last_batch_handle", "==", "'pad'", "and", "self", ".", "cursor", "+", "self", ".", "batch_size", ">", "self", ".", "num_data", ":", "return", "self", ".", "cursor", "+", "self", ".", "batch_si...
Get pad value of DataBatch.
[ "Get", "pad", "value", "of", "DataBatch", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/io/io.py#L768-L778
24,118
apache/incubator-mxnet
python/mxnet/contrib/quantization.py
_quantize_params
def _quantize_params(qsym, params, th_dict): """Given a quantized symbol and a dict of params that have not been quantized, generate quantized params. Currently only supports quantizing the arg_params with names of `weight` or `bias`, not aux_params. If `qsym` contains symbols that are excluded from bei...
python
def _quantize_params(qsym, params, th_dict): """Given a quantized symbol and a dict of params that have not been quantized, generate quantized params. Currently only supports quantizing the arg_params with names of `weight` or `bias`, not aux_params. If `qsym` contains symbols that are excluded from bei...
[ "def", "_quantize_params", "(", "qsym", ",", "params", ",", "th_dict", ")", ":", "inputs_name", "=", "qsym", ".", "list_arguments", "(", ")", "quantized_params", "=", "{", "}", "for", "name", "in", "inputs_name", ":", "if", "name", ".", "endswith", "(", ...
Given a quantized symbol and a dict of params that have not been quantized, generate quantized params. Currently only supports quantizing the arg_params with names of `weight` or `bias`, not aux_params. If `qsym` contains symbols that are excluded from being quantized, their corresponding params will no...
[ "Given", "a", "quantized", "symbol", "and", "a", "dict", "of", "params", "that", "have", "not", "been", "quantized", "generate", "quantized", "params", ".", "Currently", "only", "supports", "quantizing", "the", "arg_params", "with", "names", "of", "weight", "o...
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/contrib/quantization.py#L43-L81
24,119
apache/incubator-mxnet
python/mxnet/contrib/quantization.py
_quantize_symbol
def _quantize_symbol(sym, excluded_symbols=None, offline_params=None, quantized_dtype='int8'): """Given a symbol object representing a neural network of data type FP32, quantize it into a INT8 network. Parameters ---------- sym : Symbol FP32 neural network symbol. excluded_sym_names : l...
python
def _quantize_symbol(sym, excluded_symbols=None, offline_params=None, quantized_dtype='int8'): """Given a symbol object representing a neural network of data type FP32, quantize it into a INT8 network. Parameters ---------- sym : Symbol FP32 neural network symbol. excluded_sym_names : l...
[ "def", "_quantize_symbol", "(", "sym", ",", "excluded_symbols", "=", "None", ",", "offline_params", "=", "None", ",", "quantized_dtype", "=", "'int8'", ")", ":", "num_excluded_symbols", "=", "0", "if", "excluded_symbols", "is", "not", "None", ":", "assert", "i...
Given a symbol object representing a neural network of data type FP32, quantize it into a INT8 network. Parameters ---------- sym : Symbol FP32 neural network symbol. excluded_sym_names : list of strings A list of strings representing the names of the symbols that users want to excl...
[ "Given", "a", "symbol", "object", "representing", "a", "neural", "network", "of", "data", "type", "FP32", "quantize", "it", "into", "a", "INT8", "network", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/contrib/quantization.py#L83-L124
24,120
apache/incubator-mxnet
python/mxnet/contrib/quantization.py
_calibrate_quantized_sym
def _calibrate_quantized_sym(qsym, th_dict): """Given a dictionary containing the thresholds for quantizing the layers, set the thresholds into the quantized symbol as the params of requantize operators. """ if th_dict is None or len(th_dict) == 0: return qsym num_layer_outputs = len(th_dict...
python
def _calibrate_quantized_sym(qsym, th_dict): """Given a dictionary containing the thresholds for quantizing the layers, set the thresholds into the quantized symbol as the params of requantize operators. """ if th_dict is None or len(th_dict) == 0: return qsym num_layer_outputs = len(th_dict...
[ "def", "_calibrate_quantized_sym", "(", "qsym", ",", "th_dict", ")", ":", "if", "th_dict", "is", "None", "or", "len", "(", "th_dict", ")", "==", "0", ":", "return", "qsym", "num_layer_outputs", "=", "len", "(", "th_dict", ")", "layer_output_names", "=", "[...
Given a dictionary containing the thresholds for quantizing the layers, set the thresholds into the quantized symbol as the params of requantize operators.
[ "Given", "a", "dictionary", "containing", "the", "thresholds", "for", "quantizing", "the", "layers", "set", "the", "thresholds", "into", "the", "quantized", "symbol", "as", "the", "params", "of", "requantize", "operators", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/contrib/quantization.py#L179-L201
24,121
apache/incubator-mxnet
python/mxnet/contrib/quantization.py
_collect_layer_output_min_max
def _collect_layer_output_min_max(mod, data, include_layer=None, max_num_examples=None, logger=None): """Collect min and max values from layer outputs and save them in a dictionary mapped by layer names. """ collector = _LayerOutputMinMaxCollector(include_layer=include_...
python
def _collect_layer_output_min_max(mod, data, include_layer=None, max_num_examples=None, logger=None): """Collect min and max values from layer outputs and save them in a dictionary mapped by layer names. """ collector = _LayerOutputMinMaxCollector(include_layer=include_...
[ "def", "_collect_layer_output_min_max", "(", "mod", ",", "data", ",", "include_layer", "=", "None", ",", "max_num_examples", "=", "None", ",", "logger", "=", "None", ")", ":", "collector", "=", "_LayerOutputMinMaxCollector", "(", "include_layer", "=", "include_lay...
Collect min and max values from layer outputs and save them in a dictionary mapped by layer names.
[ "Collect", "min", "and", "max", "values", "from", "layer", "outputs", "and", "save", "them", "in", "a", "dictionary", "mapped", "by", "layer", "names", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/contrib/quantization.py#L223-L230
24,122
apache/incubator-mxnet
python/mxnet/contrib/quantization.py
_collect_layer_outputs
def _collect_layer_outputs(mod, data, include_layer=None, max_num_examples=None, logger=None): """Collect layer outputs and save them in a dictionary mapped by layer names.""" collector = _LayerOutputCollector(include_layer=include_layer, logger=logger) num_examples = _collect_layer_statistics(mod, data, co...
python
def _collect_layer_outputs(mod, data, include_layer=None, max_num_examples=None, logger=None): """Collect layer outputs and save them in a dictionary mapped by layer names.""" collector = _LayerOutputCollector(include_layer=include_layer, logger=logger) num_examples = _collect_layer_statistics(mod, data, co...
[ "def", "_collect_layer_outputs", "(", "mod", ",", "data", ",", "include_layer", "=", "None", ",", "max_num_examples", "=", "None", ",", "logger", "=", "None", ")", ":", "collector", "=", "_LayerOutputCollector", "(", "include_layer", "=", "include_layer", ",", ...
Collect layer outputs and save them in a dictionary mapped by layer names.
[ "Collect", "layer", "outputs", "and", "save", "them", "in", "a", "dictionary", "mapped", "by", "layer", "names", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/contrib/quantization.py#L233-L237
24,123
apache/incubator-mxnet
python/mxnet/contrib/quantization.py
_get_optimal_thresholds
def _get_optimal_thresholds(nd_dict, quantized_dtype, num_bins=8001, num_quantized_bins=255, logger=None): """Given a ndarray dict, find the optimal threshold for quantizing each value of the key.""" if stats is None: raise ImportError('scipy.stats is required for running entropy mode of calculating' ...
python
def _get_optimal_thresholds(nd_dict, quantized_dtype, num_bins=8001, num_quantized_bins=255, logger=None): """Given a ndarray dict, find the optimal threshold for quantizing each value of the key.""" if stats is None: raise ImportError('scipy.stats is required for running entropy mode of calculating' ...
[ "def", "_get_optimal_thresholds", "(", "nd_dict", ",", "quantized_dtype", ",", "num_bins", "=", "8001", ",", "num_quantized_bins", "=", "255", ",", "logger", "=", "None", ")", ":", "if", "stats", "is", "None", ":", "raise", "ImportError", "(", "'scipy.stats is...
Given a ndarray dict, find the optimal threshold for quantizing each value of the key.
[ "Given", "a", "ndarray", "dict", "find", "the", "optimal", "threshold", "for", "quantizing", "each", "value", "of", "the", "key", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/contrib/quantization.py#L355-L381
24,124
apache/incubator-mxnet
python/mxnet/contrib/quantization.py
_load_sym
def _load_sym(sym, logger=logging): """Given a str as a path the symbol .json file or a symbol, returns a Symbol object.""" if isinstance(sym, str): # sym is a symbol file path cur_path = os.path.dirname(os.path.realpath(__file__)) symbol_file_path = os.path.join(cur_path, sym) logger.i...
python
def _load_sym(sym, logger=logging): """Given a str as a path the symbol .json file or a symbol, returns a Symbol object.""" if isinstance(sym, str): # sym is a symbol file path cur_path = os.path.dirname(os.path.realpath(__file__)) symbol_file_path = os.path.join(cur_path, sym) logger.i...
[ "def", "_load_sym", "(", "sym", ",", "logger", "=", "logging", ")", ":", "if", "isinstance", "(", "sym", ",", "str", ")", ":", "# sym is a symbol file path", "cur_path", "=", "os", ".", "path", ".", "dirname", "(", "os", ".", "path", ".", "realpath", "...
Given a str as a path the symbol .json file or a symbol, returns a Symbol object.
[ "Given", "a", "str", "as", "a", "path", "the", "symbol", ".", "json", "file", "or", "a", "symbol", "returns", "a", "Symbol", "object", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/contrib/quantization.py#L384-L395
24,125
apache/incubator-mxnet
python/mxnet/contrib/quantization.py
_load_params
def _load_params(params, logger=logging): """Given a str as a path to the .params file or a pair of params, returns two dictionaries representing arg_params and aux_params. """ if isinstance(params, str): cur_path = os.path.dirname(os.path.realpath(__file__)) param_file_path = os.path.jo...
python
def _load_params(params, logger=logging): """Given a str as a path to the .params file or a pair of params, returns two dictionaries representing arg_params and aux_params. """ if isinstance(params, str): cur_path = os.path.dirname(os.path.realpath(__file__)) param_file_path = os.path.jo...
[ "def", "_load_params", "(", "params", ",", "logger", "=", "logging", ")", ":", "if", "isinstance", "(", "params", ",", "str", ")", ":", "cur_path", "=", "os", ".", "path", ".", "dirname", "(", "os", ".", "path", ".", "realpath", "(", "__file__", ")",...
Given a str as a path to the .params file or a pair of params, returns two dictionaries representing arg_params and aux_params.
[ "Given", "a", "str", "as", "a", "path", "to", "the", ".", "params", "file", "or", "a", "pair", "of", "params", "returns", "two", "dictionaries", "representing", "arg_params", "and", "aux_params", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/contrib/quantization.py#L398-L420
24,126
apache/incubator-mxnet
python/mxnet/contrib/quantization.py
_LayerOutputCollector.collect
def collect(self, name, arr): """Callback function for collecting layer output NDArrays.""" name = py_str(name) if self.include_layer is not None and not self.include_layer(name): return handle = ctypes.cast(arr, NDArrayHandle) arr = NDArray(handle, writable=False).co...
python
def collect(self, name, arr): """Callback function for collecting layer output NDArrays.""" name = py_str(name) if self.include_layer is not None and not self.include_layer(name): return handle = ctypes.cast(arr, NDArrayHandle) arr = NDArray(handle, writable=False).co...
[ "def", "collect", "(", "self", ",", "name", ",", "arr", ")", ":", "name", "=", "py_str", "(", "name", ")", "if", "self", ".", "include_layer", "is", "not", "None", "and", "not", "self", ".", "include_layer", "(", "name", ")", ":", "return", "handle",...
Callback function for collecting layer output NDArrays.
[ "Callback", "function", "for", "collecting", "layer", "output", "NDArrays", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/contrib/quantization.py#L137-L149
24,127
apache/incubator-mxnet
python/mxnet/contrib/quantization.py
_LayerOutputMinMaxCollector.collect
def collect(self, name, arr): """Callback function for collecting min and max values from an NDArray.""" name = py_str(name) if self.include_layer is not None and not self.include_layer(name): return handle = ctypes.cast(arr, NDArrayHandle) arr = NDArray(handle, writa...
python
def collect(self, name, arr): """Callback function for collecting min and max values from an NDArray.""" name = py_str(name) if self.include_layer is not None and not self.include_layer(name): return handle = ctypes.cast(arr, NDArrayHandle) arr = NDArray(handle, writa...
[ "def", "collect", "(", "self", ",", "name", ",", "arr", ")", ":", "name", "=", "py_str", "(", "name", ")", "if", "self", ".", "include_layer", "is", "not", "None", "and", "not", "self", ".", "include_layer", "(", "name", ")", ":", "return", "handle",...
Callback function for collecting min and max values from an NDArray.
[ "Callback", "function", "for", "collecting", "min", "and", "max", "values", "from", "an", "NDArray", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/contrib/quantization.py#L160-L177
24,128
apache/incubator-mxnet
example/vae-gan/vaegan_mxnet.py
encoder
def encoder(nef, z_dim, batch_size, no_bias=True, fix_gamma=True, eps=1e-5 + 1e-12): '''The encoder is a CNN which takes 32x32 image as input generates the 100 dimensional shape embedding as a sample from normal distribution using predicted meand and variance ''' BatchNorm = mx.sym.BatchNorm da...
python
def encoder(nef, z_dim, batch_size, no_bias=True, fix_gamma=True, eps=1e-5 + 1e-12): '''The encoder is a CNN which takes 32x32 image as input generates the 100 dimensional shape embedding as a sample from normal distribution using predicted meand and variance ''' BatchNorm = mx.sym.BatchNorm da...
[ "def", "encoder", "(", "nef", ",", "z_dim", ",", "batch_size", ",", "no_bias", "=", "True", ",", "fix_gamma", "=", "True", ",", "eps", "=", "1e-5", "+", "1e-12", ")", ":", "BatchNorm", "=", "mx", ".", "sym", ".", "BatchNorm", "data", "=", "mx", "."...
The encoder is a CNN which takes 32x32 image as input generates the 100 dimensional shape embedding as a sample from normal distribution using predicted meand and variance
[ "The", "encoder", "is", "a", "CNN", "which", "takes", "32x32", "image", "as", "input", "generates", "the", "100", "dimensional", "shape", "embedding", "as", "a", "sample", "from", "normal", "distribution", "using", "predicted", "meand", "and", "variance" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/vae-gan/vaegan_mxnet.py#L54-L86
24,129
apache/incubator-mxnet
example/vae-gan/vaegan_mxnet.py
generator
def generator(ngf, nc, no_bias=True, fix_gamma=True, eps=1e-5 + 1e-12, z_dim=100, activation='sigmoid'): '''The genrator is a CNN which takes 100 dimensional embedding as input and reconstructs the input image given to the encoder ''' BatchNorm = mx.sym.BatchNorm rand = mx.sym.Variable('rand') ...
python
def generator(ngf, nc, no_bias=True, fix_gamma=True, eps=1e-5 + 1e-12, z_dim=100, activation='sigmoid'): '''The genrator is a CNN which takes 100 dimensional embedding as input and reconstructs the input image given to the encoder ''' BatchNorm = mx.sym.BatchNorm rand = mx.sym.Variable('rand') ...
[ "def", "generator", "(", "ngf", ",", "nc", ",", "no_bias", "=", "True", ",", "fix_gamma", "=", "True", ",", "eps", "=", "1e-5", "+", "1e-12", ",", "z_dim", "=", "100", ",", "activation", "=", "'sigmoid'", ")", ":", "BatchNorm", "=", "mx", ".", "sym...
The genrator is a CNN which takes 100 dimensional embedding as input and reconstructs the input image given to the encoder
[ "The", "genrator", "is", "a", "CNN", "which", "takes", "100", "dimensional", "embedding", "as", "input", "and", "reconstructs", "the", "input", "image", "given", "to", "the", "encoder" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/vae-gan/vaegan_mxnet.py#L88-L116
24,130
apache/incubator-mxnet
example/vae-gan/vaegan_mxnet.py
discriminator1
def discriminator1(ndf, no_bias=True, fix_gamma=True, eps=1e-5 + 1e-12): '''First part of the discriminator which takes a 32x32 image as input and output a convolutional feature map, this is required to calculate the layer loss''' BatchNorm = mx.sym.BatchNorm data = mx.sym.Variable('data') d1 ...
python
def discriminator1(ndf, no_bias=True, fix_gamma=True, eps=1e-5 + 1e-12): '''First part of the discriminator which takes a 32x32 image as input and output a convolutional feature map, this is required to calculate the layer loss''' BatchNorm = mx.sym.BatchNorm data = mx.sym.Variable('data') d1 ...
[ "def", "discriminator1", "(", "ndf", ",", "no_bias", "=", "True", ",", "fix_gamma", "=", "True", ",", "eps", "=", "1e-5", "+", "1e-12", ")", ":", "BatchNorm", "=", "mx", ".", "sym", ".", "BatchNorm", "data", "=", "mx", ".", "sym", ".", "Variable", ...
First part of the discriminator which takes a 32x32 image as input and output a convolutional feature map, this is required to calculate the layer loss
[ "First", "part", "of", "the", "discriminator", "which", "takes", "a", "32x32", "image", "as", "input", "and", "output", "a", "convolutional", "feature", "map", "this", "is", "required", "to", "calculate", "the", "layer", "loss" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/vae-gan/vaegan_mxnet.py#L118-L137
24,131
apache/incubator-mxnet
example/vae-gan/vaegan_mxnet.py
discriminator2
def discriminator2(ndf, no_bias=True, fix_gamma=True, eps=1e-5 + 1e-12): '''Second part of the discriminator which takes a 256x8x8 feature map as input and generates the loss based on whether the input image was a real one or fake one''' BatchNorm = mx.sym.BatchNorm data = mx.sym.Variable('data') ...
python
def discriminator2(ndf, no_bias=True, fix_gamma=True, eps=1e-5 + 1e-12): '''Second part of the discriminator which takes a 256x8x8 feature map as input and generates the loss based on whether the input image was a real one or fake one''' BatchNorm = mx.sym.BatchNorm data = mx.sym.Variable('data') ...
[ "def", "discriminator2", "(", "ndf", ",", "no_bias", "=", "True", ",", "fix_gamma", "=", "True", ",", "eps", "=", "1e-5", "+", "1e-12", ")", ":", "BatchNorm", "=", "mx", ".", "sym", ".", "BatchNorm", "data", "=", "mx", ".", "sym", ".", "Variable", ...
Second part of the discriminator which takes a 256x8x8 feature map as input and generates the loss based on whether the input image was a real one or fake one
[ "Second", "part", "of", "the", "discriminator", "which", "takes", "a", "256x8x8", "feature", "map", "as", "input", "and", "generates", "the", "loss", "based", "on", "whether", "the", "input", "image", "was", "a", "real", "one", "or", "fake", "one" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/vae-gan/vaegan_mxnet.py#L139-L159
24,132
apache/incubator-mxnet
example/vae-gan/vaegan_mxnet.py
GaussianLogDensity
def GaussianLogDensity(x, mu, log_var, name='GaussianLogDensity', EPSILON = 1e-6): '''GaussianLogDensity loss calculation for layer wise loss ''' c = mx.sym.ones_like(log_var)*2.0 * 3.1416 c = mx.symbol.log(c) var = mx.sym.exp(log_var) x_mu2 = mx.symbol.square(x - mu) # [Issue] not sure the di...
python
def GaussianLogDensity(x, mu, log_var, name='GaussianLogDensity', EPSILON = 1e-6): '''GaussianLogDensity loss calculation for layer wise loss ''' c = mx.sym.ones_like(log_var)*2.0 * 3.1416 c = mx.symbol.log(c) var = mx.sym.exp(log_var) x_mu2 = mx.symbol.square(x - mu) # [Issue] not sure the di...
[ "def", "GaussianLogDensity", "(", "x", ",", "mu", ",", "log_var", ",", "name", "=", "'GaussianLogDensity'", ",", "EPSILON", "=", "1e-6", ")", ":", "c", "=", "mx", ".", "sym", ".", "ones_like", "(", "log_var", ")", "*", "2.0", "*", "3.1416", "c", "=",...
GaussianLogDensity loss calculation for layer wise loss
[ "GaussianLogDensity", "loss", "calculation", "for", "layer", "wise", "loss" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/vae-gan/vaegan_mxnet.py#L161-L171
24,133
apache/incubator-mxnet
example/vae-gan/vaegan_mxnet.py
DiscriminatorLayerLoss
def DiscriminatorLayerLoss(): '''Calculate the discriminator layer loss ''' data = mx.sym.Variable('data') label = mx.sym.Variable('label') data = mx.sym.Flatten(data) label = mx.sym.Flatten(label) label = mx.sym.BlockGrad(label) zeros = mx.sym.zeros_like(data) output = -Gaussi...
python
def DiscriminatorLayerLoss(): '''Calculate the discriminator layer loss ''' data = mx.sym.Variable('data') label = mx.sym.Variable('label') data = mx.sym.Flatten(data) label = mx.sym.Flatten(label) label = mx.sym.BlockGrad(label) zeros = mx.sym.zeros_like(data) output = -Gaussi...
[ "def", "DiscriminatorLayerLoss", "(", ")", ":", "data", "=", "mx", ".", "sym", ".", "Variable", "(", "'data'", ")", "label", "=", "mx", ".", "sym", ".", "Variable", "(", "'label'", ")", "data", "=", "mx", ".", "sym", ".", "Flatten", "(", "data", ")...
Calculate the discriminator layer loss
[ "Calculate", "the", "discriminator", "layer", "loss" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/vae-gan/vaegan_mxnet.py#L173-L192
24,134
apache/incubator-mxnet
example/vae-gan/vaegan_mxnet.py
get_data
def get_data(path, activation): '''Get the dataset ''' data = [] image_names = [] for filename in os.listdir(path): img = cv2.imread(os.path.join(path,filename), cv2.IMREAD_GRAYSCALE) image_names.append(filename) if img is not None: data.append(img) data = np...
python
def get_data(path, activation): '''Get the dataset ''' data = [] image_names = [] for filename in os.listdir(path): img = cv2.imread(os.path.join(path,filename), cv2.IMREAD_GRAYSCALE) image_names.append(filename) if img is not None: data.append(img) data = np...
[ "def", "get_data", "(", "path", ",", "activation", ")", ":", "data", "=", "[", "]", "image_names", "=", "[", "]", "for", "filename", "in", "os", ".", "listdir", "(", "path", ")", ":", "img", "=", "cv2", ".", "imread", "(", "os", ".", "path", ".",...
Get the dataset
[ "Get", "the", "dataset" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/vae-gan/vaegan_mxnet.py#L213-L237
24,135
apache/incubator-mxnet
example/gluon/house_prices/kaggle_k_fold_cross_validation.py
get_rmse_log
def get_rmse_log(net, X_train, y_train): """Gets root mse between the logarithms of the prediction and the truth.""" num_train = X_train.shape[0] clipped_preds = nd.clip(net(X_train), 1, float('inf')) return np.sqrt(2 * nd.sum(square_loss( nd.log(clipped_preds), nd.log(y_train))).asscalar() / nu...
python
def get_rmse_log(net, X_train, y_train): """Gets root mse between the logarithms of the prediction and the truth.""" num_train = X_train.shape[0] clipped_preds = nd.clip(net(X_train), 1, float('inf')) return np.sqrt(2 * nd.sum(square_loss( nd.log(clipped_preds), nd.log(y_train))).asscalar() / nu...
[ "def", "get_rmse_log", "(", "net", ",", "X_train", ",", "y_train", ")", ":", "num_train", "=", "X_train", ".", "shape", "[", "0", "]", "clipped_preds", "=", "nd", ".", "clip", "(", "net", "(", "X_train", ")", ",", "1", ",", "float", "(", "'inf'", "...
Gets root mse between the logarithms of the prediction and the truth.
[ "Gets", "root", "mse", "between", "the", "logarithms", "of", "the", "prediction", "and", "the", "truth", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/gluon/house_prices/kaggle_k_fold_cross_validation.py#L66-L71
24,136
apache/incubator-mxnet
example/gluon/house_prices/kaggle_k_fold_cross_validation.py
get_net
def get_net(): """Gets a neural network. Better results are obtained with modifications.""" net = gluon.nn.Sequential() with net.name_scope(): net.add(gluon.nn.Dense(50, activation="relu")) net.add(gluon.nn.Dense(1)) net.initialize() return net
python
def get_net(): """Gets a neural network. Better results are obtained with modifications.""" net = gluon.nn.Sequential() with net.name_scope(): net.add(gluon.nn.Dense(50, activation="relu")) net.add(gluon.nn.Dense(1)) net.initialize() return net
[ "def", "get_net", "(", ")", ":", "net", "=", "gluon", ".", "nn", ".", "Sequential", "(", ")", "with", "net", ".", "name_scope", "(", ")", ":", "net", ".", "add", "(", "gluon", ".", "nn", ".", "Dense", "(", "50", ",", "activation", "=", "\"relu\""...
Gets a neural network. Better results are obtained with modifications.
[ "Gets", "a", "neural", "network", ".", "Better", "results", "are", "obtained", "with", "modifications", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/gluon/house_prices/kaggle_k_fold_cross_validation.py#L73-L80
24,137
apache/incubator-mxnet
example/gluon/house_prices/kaggle_k_fold_cross_validation.py
train
def train(net, X_train, y_train, epochs, verbose_epoch, learning_rate, weight_decay, batch_size): """Trains the model.""" dataset_train = gluon.data.ArrayDataset(X_train, y_train) data_iter_train = gluon.data.DataLoader(dataset_train, batch_size, shuffle...
python
def train(net, X_train, y_train, epochs, verbose_epoch, learning_rate, weight_decay, batch_size): """Trains the model.""" dataset_train = gluon.data.ArrayDataset(X_train, y_train) data_iter_train = gluon.data.DataLoader(dataset_train, batch_size, shuffle...
[ "def", "train", "(", "net", ",", "X_train", ",", "y_train", ",", "epochs", ",", "verbose_epoch", ",", "learning_rate", ",", "weight_decay", ",", "batch_size", ")", ":", "dataset_train", "=", "gluon", ".", "data", ".", "ArrayDataset", "(", "X_train", ",", "...
Trains the model.
[ "Trains", "the", "model", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/gluon/house_prices/kaggle_k_fold_cross_validation.py#L82-L102
24,138
apache/incubator-mxnet
example/gluon/house_prices/kaggle_k_fold_cross_validation.py
k_fold_cross_valid
def k_fold_cross_valid(k, epochs, verbose_epoch, X_train, y_train, learning_rate, weight_decay, batch_size): """Conducts k-fold cross validation for the model.""" assert k > 1 fold_size = X_train.shape[0] // k train_loss_sum = 0.0 test_loss_sum = 0.0 for test_idx in range...
python
def k_fold_cross_valid(k, epochs, verbose_epoch, X_train, y_train, learning_rate, weight_decay, batch_size): """Conducts k-fold cross validation for the model.""" assert k > 1 fold_size = X_train.shape[0] // k train_loss_sum = 0.0 test_loss_sum = 0.0 for test_idx in range...
[ "def", "k_fold_cross_valid", "(", "k", ",", "epochs", ",", "verbose_epoch", ",", "X_train", ",", "y_train", ",", "learning_rate", ",", "weight_decay", ",", "batch_size", ")", ":", "assert", "k", ">", "1", "fold_size", "=", "X_train", ".", "shape", "[", "0"...
Conducts k-fold cross validation for the model.
[ "Conducts", "k", "-", "fold", "cross", "validation", "for", "the", "model", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/gluon/house_prices/kaggle_k_fold_cross_validation.py#L104-L135
24,139
apache/incubator-mxnet
example/gluon/house_prices/kaggle_k_fold_cross_validation.py
learn
def learn(epochs, verbose_epoch, X_train, y_train, test, learning_rate, weight_decay, batch_size): """Trains the model and predicts on the test data set.""" net = get_net() _ = train(net, X_train, y_train, epochs, verbose_epoch, learning_rate, weight_decay, batch_size) preds =...
python
def learn(epochs, verbose_epoch, X_train, y_train, test, learning_rate, weight_decay, batch_size): """Trains the model and predicts on the test data set.""" net = get_net() _ = train(net, X_train, y_train, epochs, verbose_epoch, learning_rate, weight_decay, batch_size) preds =...
[ "def", "learn", "(", "epochs", ",", "verbose_epoch", ",", "X_train", ",", "y_train", ",", "test", ",", "learning_rate", ",", "weight_decay", ",", "batch_size", ")", ":", "net", "=", "get_net", "(", ")", "_", "=", "train", "(", "net", ",", "X_train", ",...
Trains the model and predicts on the test data set.
[ "Trains", "the", "model", "and", "predicts", "on", "the", "test", "data", "set", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/gluon/house_prices/kaggle_k_fold_cross_validation.py#L152-L161
24,140
apache/incubator-mxnet
example/capsnet/capsulenet.py
do_training
def do_training(num_epoch, optimizer, kvstore, learning_rate, model_prefix, decay): """Perform CapsNet training""" summary_writer = SummaryWriter(args.tblog_dir) lr_scheduler = SimpleLRScheduler(learning_rate) optimizer_params = {'lr_scheduler': lr_scheduler} module.init_params() module.init_opt...
python
def do_training(num_epoch, optimizer, kvstore, learning_rate, model_prefix, decay): """Perform CapsNet training""" summary_writer = SummaryWriter(args.tblog_dir) lr_scheduler = SimpleLRScheduler(learning_rate) optimizer_params = {'lr_scheduler': lr_scheduler} module.init_params() module.init_opt...
[ "def", "do_training", "(", "num_epoch", ",", "optimizer", ",", "kvstore", ",", "learning_rate", ",", "model_prefix", ",", "decay", ")", ":", "summary_writer", "=", "SummaryWriter", "(", "args", ".", "tblog_dir", ")", "lr_scheduler", "=", "SimpleLRScheduler", "("...
Perform CapsNet training
[ "Perform", "CapsNet", "training" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/capsnet/capsulenet.py#L195-L238
24,141
apache/incubator-mxnet
example/capsnet/capsulenet.py
LossMetric.update
def update(self, labels, preds): """Update the hyper-parameters and loss of CapsNet""" batch_sum_metric = 0 batch_num_inst = 0 for label, pred_outcaps in zip(labels[0], preds[0]): label_np = int(label.asnumpy()) pred_label = int(np.argmax(pred_outcaps.asnumpy())) ...
python
def update(self, labels, preds): """Update the hyper-parameters and loss of CapsNet""" batch_sum_metric = 0 batch_num_inst = 0 for label, pred_outcaps in zip(labels[0], preds[0]): label_np = int(label.asnumpy()) pred_label = int(np.argmax(pred_outcaps.asnumpy())) ...
[ "def", "update", "(", "self", ",", "labels", ",", "preds", ")", ":", "batch_sum_metric", "=", "0", "batch_num_inst", "=", "0", "for", "label", ",", "pred_outcaps", "in", "zip", "(", "labels", "[", "0", "]", ",", "preds", "[", "0", "]", ")", ":", "l...
Update the hyper-parameters and loss of CapsNet
[ "Update", "the", "hyper", "-", "parameters", "and", "loss", "of", "CapsNet" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/capsnet/capsulenet.py#L140-L158
24,142
apache/incubator-mxnet
example/capsnet/capsulenet.py
MNISTCustomIter.next
def next(self): """Generate next of iterator""" if self.iter_next(): if self.is_train: data_raw_list = self.getdata() data_shifted = [] for data_raw in data_raw_list[0]: data_shifted.append(random_shift(data_raw.asnumpy(), 0...
python
def next(self): """Generate next of iterator""" if self.iter_next(): if self.is_train: data_raw_list = self.getdata() data_shifted = [] for data_raw in data_raw_list[0]: data_shifted.append(random_shift(data_raw.asnumpy(), 0...
[ "def", "next", "(", "self", ")", ":", "if", "self", ".", "iter_next", "(", ")", ":", "if", "self", ".", "is_train", ":", "data_raw_list", "=", "self", ".", "getdata", "(", ")", "data_shifted", "=", "[", "]", "for", "data_raw", "in", "data_raw_list", ...
Generate next of iterator
[ "Generate", "next", "of", "iterator" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/capsnet/capsulenet.py#L304-L318
24,143
apache/incubator-mxnet
python/mxnet/attribute.py
AttrScope.get
def get(self, attr): """ Get the attribute dict given the attribute set by the symbol. Parameters ---------- attr : dict of string to string The attribute passed in by user during symbol creation. Returns ------- attr : dict of string to stri...
python
def get(self, attr): """ Get the attribute dict given the attribute set by the symbol. Parameters ---------- attr : dict of string to string The attribute passed in by user during symbol creation. Returns ------- attr : dict of string to stri...
[ "def", "get", "(", "self", ",", "attr", ")", ":", "if", "self", ".", "_attr", ":", "ret", "=", "self", ".", "_attr", ".", "copy", "(", ")", "if", "attr", ":", "ret", ".", "update", "(", "attr", ")", "return", "ret", "else", ":", "return", "attr...
Get the attribute dict given the attribute set by the symbol. Parameters ---------- attr : dict of string to string The attribute passed in by user during symbol creation. Returns ------- attr : dict of string to string Updated attributes to add ...
[ "Get", "the", "attribute", "dict", "given", "the", "attribute", "set", "by", "the", "symbol", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/attribute.py#L47-L67
24,144
apache/incubator-mxnet
python/mxnet/model.py
_create_sparse_kvstore
def _create_sparse_kvstore(kvstore): """Create kvstore assuming some parameters' storage types are row_sparse. Parameters ---------- kvstore : KVStore or str The kvstore. Returns ------- kvstore : KVStore update_on_kvstore : bool. Always True. """ # always update on kvs...
python
def _create_sparse_kvstore(kvstore): """Create kvstore assuming some parameters' storage types are row_sparse. Parameters ---------- kvstore : KVStore or str The kvstore. Returns ------- kvstore : KVStore update_on_kvstore : bool. Always True. """ # always update on kvs...
[ "def", "_create_sparse_kvstore", "(", "kvstore", ")", ":", "# always update on kvstore", "update_on_kvstore", "=", "True", "if", "isinstance", "(", "kvstore", ",", "kvs", ".", "KVStore", ")", ":", "kv", "=", "kvstore", "elif", "isinstance", "(", "kvstore", ",", ...
Create kvstore assuming some parameters' storage types are row_sparse. Parameters ---------- kvstore : KVStore or str The kvstore. Returns ------- kvstore : KVStore update_on_kvstore : bool. Always True.
[ "Create", "kvstore", "assuming", "some", "parameters", "storage", "types", "are", "row_sparse", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/model.py#L58-L80
24,145
apache/incubator-mxnet
python/mxnet/model.py
_create_kvstore
def _create_kvstore(kvstore, num_device, arg_params): """Create kvstore This function select and create a proper kvstore if given the kvstore type. Parameters ---------- kvstore : KVStore or str The kvstore. num_device : int The number of devices arg_params : dict of str to ...
python
def _create_kvstore(kvstore, num_device, arg_params): """Create kvstore This function select and create a proper kvstore if given the kvstore type. Parameters ---------- kvstore : KVStore or str The kvstore. num_device : int The number of devices arg_params : dict of str to ...
[ "def", "_create_kvstore", "(", "kvstore", ",", "num_device", ",", "arg_params", ")", ":", "update_on_kvstore", "=", "bool", "(", "int", "(", "os", ".", "getenv", "(", "'MXNET_UPDATE_ON_KVSTORE'", ",", "\"1\"", ")", ")", ")", "if", "kvstore", "is", "None", ...
Create kvstore This function select and create a proper kvstore if given the kvstore type. Parameters ---------- kvstore : KVStore or str The kvstore. num_device : int The number of devices arg_params : dict of str to `NDArray`. Model parameter, dict of name to `NDArray`...
[ "Create", "kvstore", "This", "function", "select", "and", "create", "a", "proper", "kvstore", "if", "given", "the", "kvstore", "type", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/model.py#L82-L119
24,146
apache/incubator-mxnet
python/mxnet/model.py
_update_params_on_kvstore_nccl
def _update_params_on_kvstore_nccl(param_arrays, grad_arrays, kvstore, param_names): """Perform update of param_arrays from grad_arrays on NCCL kvstore.""" valid_indices = [index for index, grad_list in enumerate(grad_arrays) if grad_list[0] is not None] valid_grad_arrays = [grad_arrays...
python
def _update_params_on_kvstore_nccl(param_arrays, grad_arrays, kvstore, param_names): """Perform update of param_arrays from grad_arrays on NCCL kvstore.""" valid_indices = [index for index, grad_list in enumerate(grad_arrays) if grad_list[0] is not None] valid_grad_arrays = [grad_arrays...
[ "def", "_update_params_on_kvstore_nccl", "(", "param_arrays", ",", "grad_arrays", ",", "kvstore", ",", "param_names", ")", ":", "valid_indices", "=", "[", "index", "for", "index", ",", "grad_list", "in", "enumerate", "(", "grad_arrays", ")", "if", "grad_list", "...
Perform update of param_arrays from grad_arrays on NCCL kvstore.
[ "Perform", "update", "of", "param_arrays", "from", "grad_arrays", "on", "NCCL", "kvstore", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/model.py#L130-L148
24,147
apache/incubator-mxnet
python/mxnet/model.py
_update_params_on_kvstore
def _update_params_on_kvstore(param_arrays, grad_arrays, kvstore, param_names): """Perform update of param_arrays from grad_arrays on kvstore.""" for index, pair in enumerate(zip(param_arrays, grad_arrays)): arg_list, grad_list = pair if grad_list[0] is None: continue name = ...
python
def _update_params_on_kvstore(param_arrays, grad_arrays, kvstore, param_names): """Perform update of param_arrays from grad_arrays on kvstore.""" for index, pair in enumerate(zip(param_arrays, grad_arrays)): arg_list, grad_list = pair if grad_list[0] is None: continue name = ...
[ "def", "_update_params_on_kvstore", "(", "param_arrays", ",", "grad_arrays", ",", "kvstore", ",", "param_names", ")", ":", "for", "index", ",", "pair", "in", "enumerate", "(", "zip", "(", "param_arrays", ",", "grad_arrays", ")", ")", ":", "arg_list", ",", "g...
Perform update of param_arrays from grad_arrays on kvstore.
[ "Perform", "update", "of", "param_arrays", "from", "grad_arrays", "on", "kvstore", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/model.py#L150-L160
24,148
apache/incubator-mxnet
python/mxnet/model.py
_update_params
def _update_params(param_arrays, grad_arrays, updater, num_device, kvstore=None, param_names=None): """Perform update of param_arrays from grad_arrays not on kvstore.""" updates = [[] for _ in range(num_device)] for i, pair in enumerate(zip(param_arrays, grad_arrays)): arg_list, g...
python
def _update_params(param_arrays, grad_arrays, updater, num_device, kvstore=None, param_names=None): """Perform update of param_arrays from grad_arrays not on kvstore.""" updates = [[] for _ in range(num_device)] for i, pair in enumerate(zip(param_arrays, grad_arrays)): arg_list, g...
[ "def", "_update_params", "(", "param_arrays", ",", "grad_arrays", ",", "updater", ",", "num_device", ",", "kvstore", "=", "None", ",", "param_names", "=", "None", ")", ":", "updates", "=", "[", "[", "]", "for", "_", "in", "range", "(", "num_device", ")",...
Perform update of param_arrays from grad_arrays not on kvstore.
[ "Perform", "update", "of", "param_arrays", "from", "grad_arrays", "not", "on", "kvstore", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/model.py#L162-L187
24,149
apache/incubator-mxnet
python/mxnet/model.py
_multiple_callbacks
def _multiple_callbacks(callbacks, *args, **kwargs): """Sends args and kwargs to any configured callbacks. This handles the cases where the 'callbacks' variable is ``None``, a single function, or a list. """ if isinstance(callbacks, list): for cb in callbacks: cb(*args, **kwargs)...
python
def _multiple_callbacks(callbacks, *args, **kwargs): """Sends args and kwargs to any configured callbacks. This handles the cases where the 'callbacks' variable is ``None``, a single function, or a list. """ if isinstance(callbacks, list): for cb in callbacks: cb(*args, **kwargs)...
[ "def", "_multiple_callbacks", "(", "callbacks", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "isinstance", "(", "callbacks", ",", "list", ")", ":", "for", "cb", "in", "callbacks", ":", "cb", "(", "*", "args", ",", "*", "*", "kwargs", ...
Sends args and kwargs to any configured callbacks. This handles the cases where the 'callbacks' variable is ``None``, a single function, or a list.
[ "Sends", "args", "and", "kwargs", "to", "any", "configured", "callbacks", ".", "This", "handles", "the", "cases", "where", "the", "callbacks", "variable", "is", "None", "a", "single", "function", "or", "a", "list", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/model.py#L190-L200
24,150
apache/incubator-mxnet
python/mxnet/model.py
save_checkpoint
def save_checkpoint(prefix, epoch, symbol, arg_params, aux_params): """Checkpoint the model data into file. Parameters ---------- prefix : str Prefix of model name. epoch : int The epoch number of the model. symbol : Symbol The input Symbol. arg_params : dict of str ...
python
def save_checkpoint(prefix, epoch, symbol, arg_params, aux_params): """Checkpoint the model data into file. Parameters ---------- prefix : str Prefix of model name. epoch : int The epoch number of the model. symbol : Symbol The input Symbol. arg_params : dict of str ...
[ "def", "save_checkpoint", "(", "prefix", ",", "epoch", ",", "symbol", ",", "arg_params", ",", "aux_params", ")", ":", "if", "symbol", "is", "not", "None", ":", "symbol", ".", "save", "(", "'%s-symbol.json'", "%", "prefix", ")", "save_dict", "=", "{", "("...
Checkpoint the model data into file. Parameters ---------- prefix : str Prefix of model name. epoch : int The epoch number of the model. symbol : Symbol The input Symbol. arg_params : dict of str to NDArray Model parameter, dict of name to NDArray of net's weight...
[ "Checkpoint", "the", "model", "data", "into", "file", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/model.py#L394-L421
24,151
apache/incubator-mxnet
python/mxnet/model.py
FeedForward._check_arguments
def _check_arguments(self): """verify the argument of the default symbol and user provided parameters""" if self.argument_checked: return assert(self.symbol is not None) self.argument_checked = True # check if symbol contain duplicated names. _check_argument...
python
def _check_arguments(self): """verify the argument of the default symbol and user provided parameters""" if self.argument_checked: return assert(self.symbol is not None) self.argument_checked = True # check if symbol contain duplicated names. _check_argument...
[ "def", "_check_arguments", "(", "self", ")", ":", "if", "self", ".", "argument_checked", ":", "return", "assert", "(", "self", ".", "symbol", "is", "not", "None", ")", "self", ".", "argument_checked", "=", "True", "# check if symbol contain duplicated names.", "...
verify the argument of the default symbol and user provided parameters
[ "verify", "the", "argument", "of", "the", "default", "symbol", "and", "user", "provided", "parameters" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/model.py#L546-L565
24,152
apache/incubator-mxnet
python/mxnet/model.py
FeedForward._init_params
def _init_params(self, inputs, overwrite=False): """Initialize weight parameters and auxiliary states.""" inputs = [x if isinstance(x, DataDesc) else DataDesc(*x) for x in inputs] input_shapes = {item.name: item.shape for item in inputs} arg_shapes, _, aux_shapes = self.symbol.infer_shap...
python
def _init_params(self, inputs, overwrite=False): """Initialize weight parameters and auxiliary states.""" inputs = [x if isinstance(x, DataDesc) else DataDesc(*x) for x in inputs] input_shapes = {item.name: item.shape for item in inputs} arg_shapes, _, aux_shapes = self.symbol.infer_shap...
[ "def", "_init_params", "(", "self", ",", "inputs", ",", "overwrite", "=", "False", ")", ":", "inputs", "=", "[", "x", "if", "isinstance", "(", "x", ",", "DataDesc", ")", "else", "DataDesc", "(", "*", "x", ")", "for", "x", "in", "inputs", "]", "inpu...
Initialize weight parameters and auxiliary states.
[ "Initialize", "weight", "parameters", "and", "auxiliary", "states", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/model.py#L573-L611
24,153
apache/incubator-mxnet
python/mxnet/model.py
FeedForward._init_predictor
def _init_predictor(self, input_shapes, type_dict=None): """Initialize the predictor module for running prediction.""" shapes = {name: self.arg_params[name].shape for name in self.arg_params} shapes.update(dict(input_shapes)) if self._pred_exec is not None: arg_shapes, _, _ =...
python
def _init_predictor(self, input_shapes, type_dict=None): """Initialize the predictor module for running prediction.""" shapes = {name: self.arg_params[name].shape for name in self.arg_params} shapes.update(dict(input_shapes)) if self._pred_exec is not None: arg_shapes, _, _ =...
[ "def", "_init_predictor", "(", "self", ",", "input_shapes", ",", "type_dict", "=", "None", ")", ":", "shapes", "=", "{", "name", ":", "self", ".", "arg_params", "[", "name", "]", ".", "shape", "for", "name", "in", "self", ".", "arg_params", "}", "shape...
Initialize the predictor module for running prediction.
[ "Initialize", "the", "predictor", "module", "for", "running", "prediction", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/model.py#L621-L637
24,154
apache/incubator-mxnet
python/mxnet/model.py
FeedForward._init_iter
def _init_iter(self, X, y, is_train): """Initialize the iterator given input.""" if isinstance(X, (np.ndarray, nd.NDArray)): if y is None: if is_train: raise ValueError('y must be specified when X is numpy.ndarray') else: ...
python
def _init_iter(self, X, y, is_train): """Initialize the iterator given input.""" if isinstance(X, (np.ndarray, nd.NDArray)): if y is None: if is_train: raise ValueError('y must be specified when X is numpy.ndarray') else: ...
[ "def", "_init_iter", "(", "self", ",", "X", ",", "y", ",", "is_train", ")", ":", "if", "isinstance", "(", "X", ",", "(", "np", ".", "ndarray", ",", "nd", ".", "NDArray", ")", ")", ":", "if", "y", "is", "None", ":", "if", "is_train", ":", "raise...
Initialize the iterator given input.
[ "Initialize", "the", "iterator", "given", "input", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/model.py#L639-L662
24,155
apache/incubator-mxnet
python/mxnet/model.py
FeedForward._init_eval_iter
def _init_eval_iter(self, eval_data): """Initialize the iterator given eval_data.""" if eval_data is None: return eval_data if isinstance(eval_data, (tuple, list)) and len(eval_data) == 2: if eval_data[0] is not None: if eval_data[1] is None and isinstance...
python
def _init_eval_iter(self, eval_data): """Initialize the iterator given eval_data.""" if eval_data is None: return eval_data if isinstance(eval_data, (tuple, list)) and len(eval_data) == 2: if eval_data[0] is not None: if eval_data[1] is None and isinstance...
[ "def", "_init_eval_iter", "(", "self", ",", "eval_data", ")", ":", "if", "eval_data", "is", "None", ":", "return", "eval_data", "if", "isinstance", "(", "eval_data", ",", "(", "tuple", ",", "list", ")", ")", "and", "len", "(", "eval_data", ")", "==", "...
Initialize the iterator given eval_data.
[ "Initialize", "the", "iterator", "given", "eval_data", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/model.py#L664-L682
24,156
apache/incubator-mxnet
python/mxnet/model.py
FeedForward.predict
def predict(self, X, num_batch=None, return_data=False, reset=True): """Run the prediction, always only use one device. Parameters ---------- X : mxnet.DataIter num_batch : int or None The number of batch to run. Go though all batches if ``None``. Returns ...
python
def predict(self, X, num_batch=None, return_data=False, reset=True): """Run the prediction, always only use one device. Parameters ---------- X : mxnet.DataIter num_batch : int or None The number of batch to run. Go though all batches if ``None``. Returns ...
[ "def", "predict", "(", "self", ",", "X", ",", "num_batch", "=", "None", ",", "return_data", "=", "False", ",", "reset", "=", "True", ")", ":", "X", "=", "self", ".", "_init_iter", "(", "X", ",", "None", ",", "is_train", "=", "False", ")", "if", "...
Run the prediction, always only use one device. Parameters ---------- X : mxnet.DataIter num_batch : int or None The number of batch to run. Go though all batches if ``None``. Returns ------- y : numpy.ndarray or a list of numpy.ndarray if the network...
[ "Run", "the", "prediction", "always", "only", "use", "one", "device", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/model.py#L684-L751
24,157
apache/incubator-mxnet
python/mxnet/model.py
FeedForward.score
def score(self, X, eval_metric='acc', num_batch=None, batch_end_callback=None, reset=True): """Run the model given an input and calculate the score as assessed by an evaluation metric. Parameters ---------- X : mxnet.DataIter eval_metric : metric.metric The m...
python
def score(self, X, eval_metric='acc', num_batch=None, batch_end_callback=None, reset=True): """Run the model given an input and calculate the score as assessed by an evaluation metric. Parameters ---------- X : mxnet.DataIter eval_metric : metric.metric The m...
[ "def", "score", "(", "self", ",", "X", ",", "eval_metric", "=", "'acc'", ",", "num_batch", "=", "None", ",", "batch_end_callback", "=", "None", ",", "reset", "=", "True", ")", ":", "# setup metric", "if", "not", "isinstance", "(", "eval_metric", ",", "me...
Run the model given an input and calculate the score as assessed by an evaluation metric. Parameters ---------- X : mxnet.DataIter eval_metric : metric.metric The metric for calculating score. num_batch : int or None The number of batches to run. ...
[ "Run", "the", "model", "given", "an", "input", "and", "calculate", "the", "score", "as", "assessed", "by", "an", "evaluation", "metric", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/model.py#L753-L802
24,158
apache/incubator-mxnet
python/mxnet/model.py
FeedForward.create
def create(symbol, X, y=None, ctx=None, num_epoch=None, epoch_size=None, optimizer='sgd', initializer=Uniform(0.01), eval_data=None, eval_metric='acc', epoch_end_callback=None, batch_end_callback=None, kvstore='local', logger=None, work_load_list=None, ...
python
def create(symbol, X, y=None, ctx=None, num_epoch=None, epoch_size=None, optimizer='sgd', initializer=Uniform(0.01), eval_data=None, eval_metric='acc', epoch_end_callback=None, batch_end_callback=None, kvstore='local', logger=None, work_load_list=None, ...
[ "def", "create", "(", "symbol", ",", "X", ",", "y", "=", "None", ",", "ctx", "=", "None", ",", "num_epoch", "=", "None", ",", "epoch_size", "=", "None", ",", "optimizer", "=", "'sgd'", ",", "initializer", "=", "Uniform", "(", "0.01", ")", ",", "eva...
Functional style to create a model. This function is more consistent with functional languages such as R, where mutation is not allowed. Parameters ---------- symbol : Symbol The symbol configuration of a computation network. X : DataIter Training...
[ "Functional", "style", "to", "create", "a", "model", ".", "This", "function", "is", "more", "consistent", "with", "functional", "languages", "such", "as", "R", "where", "mutation", "is", "not", "allowed", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/model.py#L962-L1025
24,159
apache/incubator-mxnet
example/cnn_chinese_text_classification/data_helpers.py
get_chinese_text
def get_chinese_text(): """Download the chinese_text dataset and unzip it""" if not os.path.isdir("data/"): os.system("mkdir data/") if (not os.path.exists('data/pos.txt')) or \ (not os.path.exists('data/neg')): os.system("wget -q https://raw.githubusercontent.com/dmlc/web-data/master...
python
def get_chinese_text(): """Download the chinese_text dataset and unzip it""" if not os.path.isdir("data/"): os.system("mkdir data/") if (not os.path.exists('data/pos.txt')) or \ (not os.path.exists('data/neg')): os.system("wget -q https://raw.githubusercontent.com/dmlc/web-data/master...
[ "def", "get_chinese_text", "(", ")", ":", "if", "not", "os", ".", "path", ".", "isdir", "(", "\"data/\"", ")", ":", "os", ".", "system", "(", "\"mkdir data/\"", ")", "if", "(", "not", "os", ".", "path", ".", "exists", "(", "'data/pos.txt'", ")", ")",...
Download the chinese_text dataset and unzip it
[ "Download", "the", "chinese_text", "dataset", "and", "unzip", "it" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/cnn_chinese_text_classification/data_helpers.py#L51-L61
24,160
apache/incubator-mxnet
example/ssd/train/metric.py
MultiBoxMetric.update
def update(self, labels, preds): """ Implementation of updating metrics """ # get generated multi label from network cls_prob = preds[0].asnumpy() loc_loss = preds[1].asnumpy() cls_label = preds[2].asnumpy() valid_count = np.sum(cls_label >= 0) # o...
python
def update(self, labels, preds): """ Implementation of updating metrics """ # get generated multi label from network cls_prob = preds[0].asnumpy() loc_loss = preds[1].asnumpy() cls_label = preds[2].asnumpy() valid_count = np.sum(cls_label >= 0) # o...
[ "def", "update", "(", "self", ",", "labels", ",", "preds", ")", ":", "# get generated multi label from network", "cls_prob", "=", "preds", "[", "0", "]", ".", "asnumpy", "(", ")", "loc_loss", "=", "preds", "[", "1", "]", ".", "asnumpy", "(", ")", "cls_la...
Implementation of updating metrics
[ "Implementation", "of", "updating", "metrics" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/ssd/train/metric.py#L53-L72
24,161
apache/incubator-mxnet
example/ssd/train/metric.py
MultiBoxMetric.get
def get(self): """Get the current evaluation result. Override the default behavior Returns ------- name : str Name of the metric. value : float Value of the evaluation. """ if self.num is None: if self.num_inst == 0: ...
python
def get(self): """Get the current evaluation result. Override the default behavior Returns ------- name : str Name of the metric. value : float Value of the evaluation. """ if self.num is None: if self.num_inst == 0: ...
[ "def", "get", "(", "self", ")", ":", "if", "self", ".", "num", "is", "None", ":", "if", "self", ".", "num_inst", "==", "0", ":", "return", "(", "self", ".", "name", ",", "float", "(", "'nan'", ")", ")", "else", ":", "return", "(", "self", ".", ...
Get the current evaluation result. Override the default behavior Returns ------- name : str Name of the metric. value : float Value of the evaluation.
[ "Get", "the", "current", "evaluation", "result", ".", "Override", "the", "default", "behavior" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/ssd/train/metric.py#L74-L94
24,162
apache/incubator-mxnet
python/mxnet/executor.py
Executor._get_dict
def _get_dict(names, ndarrays): """Get the dictionary given name and ndarray pairs.""" nset = set() for nm in names: if nm in nset: raise ValueError('Duplicate names detected, %s' % str(names)) nset.add(nm) return dict(zip(names, ndarrays))
python
def _get_dict(names, ndarrays): """Get the dictionary given name and ndarray pairs.""" nset = set() for nm in names: if nm in nset: raise ValueError('Duplicate names detected, %s' % str(names)) nset.add(nm) return dict(zip(names, ndarrays))
[ "def", "_get_dict", "(", "names", ",", "ndarrays", ")", ":", "nset", "=", "set", "(", ")", "for", "nm", "in", "names", ":", "if", "nm", "in", "nset", ":", "raise", "ValueError", "(", "'Duplicate names detected, %s'", "%", "str", "(", "names", ")", ")",...
Get the dictionary given name and ndarray pairs.
[ "Get", "the", "dictionary", "given", "name", "and", "ndarray", "pairs", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/executor.py#L90-L97
24,163
apache/incubator-mxnet
python/mxnet/executor.py
Executor._get_outputs
def _get_outputs(self): """List all the output NDArray. Returns ------- A list of ndarray bound to the heads of executor. """ out_size = mx_uint() handles = ctypes.POINTER(NDArrayHandle)() check_call(_LIB.MXExecutorOutputs(self.handle, ...
python
def _get_outputs(self): """List all the output NDArray. Returns ------- A list of ndarray bound to the heads of executor. """ out_size = mx_uint() handles = ctypes.POINTER(NDArrayHandle)() check_call(_LIB.MXExecutorOutputs(self.handle, ...
[ "def", "_get_outputs", "(", "self", ")", ":", "out_size", "=", "mx_uint", "(", ")", "handles", "=", "ctypes", ".", "POINTER", "(", "NDArrayHandle", ")", "(", ")", "check_call", "(", "_LIB", ".", "MXExecutorOutputs", "(", "self", ".", "handle", ",", "ctyp...
List all the output NDArray. Returns ------- A list of ndarray bound to the heads of executor.
[ "List", "all", "the", "output", "NDArray", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/executor.py#L99-L112
24,164
apache/incubator-mxnet
python/mxnet/executor.py
Executor.forward
def forward(self, is_train=False, **kwargs): """Calculate the outputs specified by the bound symbol. Parameters ---------- is_train: bool, optional Whether this forward is for evaluation purpose. If True, a backward call is expected to follow. **kwargs ...
python
def forward(self, is_train=False, **kwargs): """Calculate the outputs specified by the bound symbol. Parameters ---------- is_train: bool, optional Whether this forward is for evaluation purpose. If True, a backward call is expected to follow. **kwargs ...
[ "def", "forward", "(", "self", ",", "is_train", "=", "False", ",", "*", "*", "kwargs", ")", ":", "if", "len", "(", "kwargs", ")", "!=", "0", ":", "arg_dict", "=", "self", ".", "arg_dict", "for", "name", ",", "array", "in", "kwargs", ".", "items", ...
Calculate the outputs specified by the bound symbol. Parameters ---------- is_train: bool, optional Whether this forward is for evaluation purpose. If True, a backward call is expected to follow. **kwargs Additional specification of input arguments. ...
[ "Calculate", "the", "outputs", "specified", "by", "the", "bound", "symbol", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/executor.py#L114-L153
24,165
apache/incubator-mxnet
python/mxnet/executor.py
Executor.backward
def backward(self, out_grads=None, is_train=True): """Do backward pass to get the gradient of arguments. Parameters ---------- out_grads : NDArray or list of NDArray or dict of str to NDArray, optional Gradient on the outputs to be propagated back. This parameter...
python
def backward(self, out_grads=None, is_train=True): """Do backward pass to get the gradient of arguments. Parameters ---------- out_grads : NDArray or list of NDArray or dict of str to NDArray, optional Gradient on the outputs to be propagated back. This parameter...
[ "def", "backward", "(", "self", ",", "out_grads", "=", "None", ",", "is_train", "=", "True", ")", ":", "if", "out_grads", "is", "None", ":", "out_grads", "=", "[", "]", "elif", "isinstance", "(", "out_grads", ",", "NDArray", ")", ":", "out_grads", "=",...
Do backward pass to get the gradient of arguments. Parameters ---------- out_grads : NDArray or list of NDArray or dict of str to NDArray, optional Gradient on the outputs to be propagated back. This parameter is only needed when bind is called on outputs tha...
[ "Do", "backward", "pass", "to", "get", "the", "gradient", "of", "arguments", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/executor.py#L155-L235
24,166
apache/incubator-mxnet
python/mxnet/executor.py
Executor.set_monitor_callback
def set_monitor_callback(self, callback, monitor_all=False): """Install callback for monitor. Parameters ---------- callback : function Takes a string and an NDArrayHandle. monitor_all : bool, default False If true, monitor both input and output, otherwis...
python
def set_monitor_callback(self, callback, monitor_all=False): """Install callback for monitor. Parameters ---------- callback : function Takes a string and an NDArrayHandle. monitor_all : bool, default False If true, monitor both input and output, otherwis...
[ "def", "set_monitor_callback", "(", "self", ",", "callback", ",", "monitor_all", "=", "False", ")", ":", "cb_type", "=", "ctypes", ".", "CFUNCTYPE", "(", "None", ",", "ctypes", ".", "c_char_p", ",", "NDArrayHandle", ",", "ctypes", ".", "c_void_p", ")", "se...
Install callback for monitor. Parameters ---------- callback : function Takes a string and an NDArrayHandle. monitor_all : bool, default False If true, monitor both input and output, otherwise monitor output only. Examples -------- >>> de...
[ "Install", "callback", "for", "monitor", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/executor.py#L237-L260
24,167
apache/incubator-mxnet
python/mxnet/executor.py
Executor.arg_dict
def arg_dict(self): """Get dictionary representation of argument arrrays. Returns ------- arg_dict : dict of str to NDArray The dictionary that maps the names of arguments to NDArrays. Raises ------ ValueError : if there are duplicated names in the a...
python
def arg_dict(self): """Get dictionary representation of argument arrrays. Returns ------- arg_dict : dict of str to NDArray The dictionary that maps the names of arguments to NDArrays. Raises ------ ValueError : if there are duplicated names in the a...
[ "def", "arg_dict", "(", "self", ")", ":", "if", "self", ".", "_arg_dict", "is", "None", ":", "self", ".", "_arg_dict", "=", "Executor", ".", "_get_dict", "(", "self", ".", "_symbol", ".", "list_arguments", "(", ")", ",", "self", ".", "arg_arrays", ")",...
Get dictionary representation of argument arrrays. Returns ------- arg_dict : dict of str to NDArray The dictionary that maps the names of arguments to NDArrays. Raises ------ ValueError : if there are duplicated names in the arguments.
[ "Get", "dictionary", "representation", "of", "argument", "arrrays", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/executor.py#L263-L278
24,168
apache/incubator-mxnet
python/mxnet/executor.py
Executor.grad_dict
def grad_dict(self): """Get dictionary representation of gradient arrays. Returns ------- grad_dict : dict of str to NDArray The dictionary that maps name of arguments to gradient arrays. """ if self._grad_dict is None: self._grad_dict = Executor....
python
def grad_dict(self): """Get dictionary representation of gradient arrays. Returns ------- grad_dict : dict of str to NDArray The dictionary that maps name of arguments to gradient arrays. """ if self._grad_dict is None: self._grad_dict = Executor....
[ "def", "grad_dict", "(", "self", ")", ":", "if", "self", ".", "_grad_dict", "is", "None", ":", "self", ".", "_grad_dict", "=", "Executor", ".", "_get_dict", "(", "self", ".", "_symbol", ".", "list_arguments", "(", ")", ",", "self", ".", "grad_arrays", ...
Get dictionary representation of gradient arrays. Returns ------- grad_dict : dict of str to NDArray The dictionary that maps name of arguments to gradient arrays.
[ "Get", "dictionary", "representation", "of", "gradient", "arrays", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/executor.py#L281-L292
24,169
apache/incubator-mxnet
python/mxnet/executor.py
Executor.aux_dict
def aux_dict(self): """Get dictionary representation of auxiliary states arrays. Returns ------- aux_dict : dict of str to NDArray The dictionary that maps name of auxiliary states to NDArrays. Raises ------ ValueError : if there are duplicated names...
python
def aux_dict(self): """Get dictionary representation of auxiliary states arrays. Returns ------- aux_dict : dict of str to NDArray The dictionary that maps name of auxiliary states to NDArrays. Raises ------ ValueError : if there are duplicated names...
[ "def", "aux_dict", "(", "self", ")", ":", "if", "self", ".", "_aux_dict", "is", "None", ":", "self", ".", "_aux_dict", "=", "Executor", ".", "_get_dict", "(", "self", ".", "_symbol", ".", "list_auxiliary_states", "(", ")", ",", "self", ".", "aux_arrays",...
Get dictionary representation of auxiliary states arrays. Returns ------- aux_dict : dict of str to NDArray The dictionary that maps name of auxiliary states to NDArrays. Raises ------ ValueError : if there are duplicated names in the auxiliary states.
[ "Get", "dictionary", "representation", "of", "auxiliary", "states", "arrays", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/executor.py#L295-L310
24,170
apache/incubator-mxnet
python/mxnet/executor.py
Executor.output_dict
def output_dict(self): """Get dictionary representation of output arrays. Returns ------- output_dict : dict of str to NDArray The dictionary that maps name of output names to NDArrays. Raises ------ ValueError : if there are duplicated names in the ...
python
def output_dict(self): """Get dictionary representation of output arrays. Returns ------- output_dict : dict of str to NDArray The dictionary that maps name of output names to NDArrays. Raises ------ ValueError : if there are duplicated names in the ...
[ "def", "output_dict", "(", "self", ")", ":", "if", "self", ".", "_output_dict", "is", "None", ":", "self", ".", "_output_dict", "=", "Executor", ".", "_get_dict", "(", "self", ".", "_symbol", ".", "list_outputs", "(", ")", ",", "self", ".", "outputs", ...
Get dictionary representation of output arrays. Returns ------- output_dict : dict of str to NDArray The dictionary that maps name of output names to NDArrays. Raises ------ ValueError : if there are duplicated names in the outputs.
[ "Get", "dictionary", "representation", "of", "output", "arrays", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/executor.py#L313-L328
24,171
apache/incubator-mxnet
python/mxnet/executor.py
Executor.copy_params_from
def copy_params_from(self, arg_params, aux_params=None, allow_extra_params=False): """Copy parameters from arg_params, aux_params into executor's internal array. Parameters ---------- arg_params : dict of str to NDArray Parameters, dict of name to NDArray of arguments. ...
python
def copy_params_from(self, arg_params, aux_params=None, allow_extra_params=False): """Copy parameters from arg_params, aux_params into executor's internal array. Parameters ---------- arg_params : dict of str to NDArray Parameters, dict of name to NDArray of arguments. ...
[ "def", "copy_params_from", "(", "self", ",", "arg_params", ",", "aux_params", "=", "None", ",", "allow_extra_params", "=", "False", ")", ":", "for", "name", ",", "array", "in", "arg_params", ".", "items", "(", ")", ":", "if", "name", "in", "self", ".", ...
Copy parameters from arg_params, aux_params into executor's internal array. Parameters ---------- arg_params : dict of str to NDArray Parameters, dict of name to NDArray of arguments. aux_params : dict of str to NDArray, optional Parameters, dict of name to NDAr...
[ "Copy", "parameters", "from", "arg_params", "aux_params", "into", "executor", "s", "internal", "array", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/executor.py#L330-L373
24,172
apache/incubator-mxnet
python/mxnet/executor.py
Executor.debug_str
def debug_str(self): """Get a debug string about internal execution plan. Returns ------- debug_str : string Debug string of the executor. Examples -------- >>> a = mx.sym.Variable('a') >>> b = mx.sym.sin(a) >>> c = 2 * a + b ...
python
def debug_str(self): """Get a debug string about internal execution plan. Returns ------- debug_str : string Debug string of the executor. Examples -------- >>> a = mx.sym.Variable('a') >>> b = mx.sym.sin(a) >>> c = 2 * a + b ...
[ "def", "debug_str", "(", "self", ")", ":", "debug_str", "=", "ctypes", ".", "c_char_p", "(", ")", "check_call", "(", "_LIB", ".", "MXExecutorPrint", "(", "self", ".", "handle", ",", "ctypes", ".", "byref", "(", "debug_str", ")", ")", ")", "return", "py...
Get a debug string about internal execution plan. Returns ------- debug_str : string Debug string of the executor. Examples -------- >>> a = mx.sym.Variable('a') >>> b = mx.sym.sin(a) >>> c = 2 * a + b >>> texec = c.bind(mx.cpu(), {'a...
[ "Get", "a", "debug", "string", "about", "internal", "execution", "plan", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/executor.py#L474-L513
24,173
apache/incubator-mxnet
python/mxnet/contrib/onnx/mx2onnx/export_onnx.py
MXNetGraph.convert_layer
def convert_layer(node, **kwargs): """Convert MXNet layer to ONNX""" op = str(node["op"]) if op not in MXNetGraph.registry_: raise AttributeError("No conversion function registered for op type %s yet." % op) convert_func = MXNetGraph.registry_[op] return convert_func(...
python
def convert_layer(node, **kwargs): """Convert MXNet layer to ONNX""" op = str(node["op"]) if op not in MXNetGraph.registry_: raise AttributeError("No conversion function registered for op type %s yet." % op) convert_func = MXNetGraph.registry_[op] return convert_func(...
[ "def", "convert_layer", "(", "node", ",", "*", "*", "kwargs", ")", ":", "op", "=", "str", "(", "node", "[", "\"op\"", "]", ")", "if", "op", "not", "in", "MXNetGraph", ".", "registry_", ":", "raise", "AttributeError", "(", "\"No conversion function register...
Convert MXNet layer to ONNX
[ "Convert", "MXNet", "layer", "to", "ONNX" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/contrib/onnx/mx2onnx/export_onnx.py#L86-L92
24,174
apache/incubator-mxnet
python/mxnet/contrib/onnx/mx2onnx/export_onnx.py
MXNetGraph.split_params
def split_params(sym, params): """Helper function to split params dictionary into args and aux params Parameters ---------- sym : :class:`~mxnet.symbol.Symbol` MXNet symbol object params : dict of ``str`` to :class:`~mxnet.ndarray.NDArray` Dict of convert...
python
def split_params(sym, params): """Helper function to split params dictionary into args and aux params Parameters ---------- sym : :class:`~mxnet.symbol.Symbol` MXNet symbol object params : dict of ``str`` to :class:`~mxnet.ndarray.NDArray` Dict of convert...
[ "def", "split_params", "(", "sym", ",", "params", ")", ":", "arg_params", "=", "{", "}", "aux_params", "=", "{", "}", "for", "args", "in", "sym", ".", "list_arguments", "(", ")", ":", "if", "args", "in", "params", ":", "arg_params", ".", "update", "(...
Helper function to split params dictionary into args and aux params Parameters ---------- sym : :class:`~mxnet.symbol.Symbol` MXNet symbol object params : dict of ``str`` to :class:`~mxnet.ndarray.NDArray` Dict of converted parameters stored in ``mxnet.ndarray.ND...
[ "Helper", "function", "to", "split", "params", "dictionary", "into", "args", "and", "aux", "params" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/contrib/onnx/mx2onnx/export_onnx.py#L95-L120
24,175
apache/incubator-mxnet
python/mxnet/contrib/onnx/mx2onnx/export_onnx.py
MXNetGraph.get_outputs
def get_outputs(sym, params, in_shape, in_label): """ Infer output shapes and return dictionary of output name to shape :param :class:`~mxnet.symbol.Symbol` sym: symbol to perform infer shape on :param dic of (str, nd.NDArray) params: :param list of tuple(int, ...) in_shape: list of all...
python
def get_outputs(sym, params, in_shape, in_label): """ Infer output shapes and return dictionary of output name to shape :param :class:`~mxnet.symbol.Symbol` sym: symbol to perform infer shape on :param dic of (str, nd.NDArray) params: :param list of tuple(int, ...) in_shape: list of all...
[ "def", "get_outputs", "(", "sym", ",", "params", ",", "in_shape", ",", "in_label", ")", ":", "# remove any input listed in params from sym.list_inputs() and bind them to the input shapes provided", "# by user. Also remove in_label, which is the name of the label symbol that may have been u...
Infer output shapes and return dictionary of output name to shape :param :class:`~mxnet.symbol.Symbol` sym: symbol to perform infer shape on :param dic of (str, nd.NDArray) params: :param list of tuple(int, ...) in_shape: list of all input shapes :param in_label: name of label typicall...
[ "Infer", "output", "shapes", "and", "return", "dictionary", "of", "output", "name", "to", "shape" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/contrib/onnx/mx2onnx/export_onnx.py#L123-L156
24,176
apache/incubator-mxnet
python/mxnet/contrib/onnx/mx2onnx/export_onnx.py
MXNetGraph.convert_weights_to_numpy
def convert_weights_to_numpy(weights_dict): """Convert weights to numpy""" return dict([(k.replace("arg:", "").replace("aux:", ""), v.asnumpy()) for k, v in weights_dict.items()])
python
def convert_weights_to_numpy(weights_dict): """Convert weights to numpy""" return dict([(k.replace("arg:", "").replace("aux:", ""), v.asnumpy()) for k, v in weights_dict.items()])
[ "def", "convert_weights_to_numpy", "(", "weights_dict", ")", ":", "return", "dict", "(", "[", "(", "k", ".", "replace", "(", "\"arg:\"", ",", "\"\"", ")", ".", "replace", "(", "\"aux:\"", ",", "\"\"", ")", ",", "v", ".", "asnumpy", "(", ")", ")", "fo...
Convert weights to numpy
[ "Convert", "weights", "to", "numpy" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/contrib/onnx/mx2onnx/export_onnx.py#L159-L162
24,177
apache/incubator-mxnet
example/ssd/train/train_net.py
get_lr_scheduler
def get_lr_scheduler(learning_rate, lr_refactor_step, lr_refactor_ratio, num_example, batch_size, begin_epoch): """ Compute learning rate and refactor scheduler Parameters: --------- learning_rate : float original learning rate lr_refactor_step : comma separated str...
python
def get_lr_scheduler(learning_rate, lr_refactor_step, lr_refactor_ratio, num_example, batch_size, begin_epoch): """ Compute learning rate and refactor scheduler Parameters: --------- learning_rate : float original learning rate lr_refactor_step : comma separated str...
[ "def", "get_lr_scheduler", "(", "learning_rate", ",", "lr_refactor_step", ",", "lr_refactor_ratio", ",", "num_example", ",", "batch_size", ",", "begin_epoch", ")", ":", "assert", "lr_refactor_ratio", ">", "0", "iter_refactor", "=", "[", "int", "(", "r", ")", "fo...
Compute learning rate and refactor scheduler Parameters: --------- learning_rate : float original learning rate lr_refactor_step : comma separated str epochs to change learning rate lr_refactor_ratio : float lr *= ratio at certain steps num_example : int number o...
[ "Compute", "learning", "rate", "and", "refactor", "scheduler" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/ssd/train/train_net.py#L48-L88
24,178
slundberg/shap
shap/datasets.py
imagenet50
def imagenet50(display=False, resolution=224): """ This is a set of 50 images representative of ImageNet images. This dataset was collected by randomly finding a working ImageNet link and then pasting the original ImageNet image into Google image search restricted to images licensed for reuse. A simila...
python
def imagenet50(display=False, resolution=224): """ This is a set of 50 images representative of ImageNet images. This dataset was collected by randomly finding a working ImageNet link and then pasting the original ImageNet image into Google image search restricted to images licensed for reuse. A simila...
[ "def", "imagenet50", "(", "display", "=", "False", ",", "resolution", "=", "224", ")", ":", "prefix", "=", "github_data_url", "+", "\"imagenet50_\"", "X", "=", "np", ".", "load", "(", "cache", "(", "prefix", "+", "\"%sx%s.npy\"", "%", "(", "resolution", ...
This is a set of 50 images representative of ImageNet images. This dataset was collected by randomly finding a working ImageNet link and then pasting the original ImageNet image into Google image search restricted to images licensed for reuse. A similar image (now with rights to reuse) was downloaded as a ...
[ "This", "is", "a", "set", "of", "50", "images", "representative", "of", "ImageNet", "images", "." ]
b280cb81d498b9d98565cad8dd16fc88ae52649f
https://github.com/slundberg/shap/blob/b280cb81d498b9d98565cad8dd16fc88ae52649f/shap/datasets.py#L13-L28
24,179
slundberg/shap
shap/datasets.py
boston
def boston(display=False): """ Return the boston housing data in a nice package. """ d = sklearn.datasets.load_boston() df = pd.DataFrame(data=d.data, columns=d.feature_names) # pylint: disable=E1101 return df, d.target
python
def boston(display=False): """ Return the boston housing data in a nice package. """ d = sklearn.datasets.load_boston() df = pd.DataFrame(data=d.data, columns=d.feature_names) # pylint: disable=E1101 return df, d.target
[ "def", "boston", "(", "display", "=", "False", ")", ":", "d", "=", "sklearn", ".", "datasets", ".", "load_boston", "(", ")", "df", "=", "pd", ".", "DataFrame", "(", "data", "=", "d", ".", "data", ",", "columns", "=", "d", ".", "feature_names", ")",...
Return the boston housing data in a nice package.
[ "Return", "the", "boston", "housing", "data", "in", "a", "nice", "package", "." ]
b280cb81d498b9d98565cad8dd16fc88ae52649f
https://github.com/slundberg/shap/blob/b280cb81d498b9d98565cad8dd16fc88ae52649f/shap/datasets.py#L30-L35
24,180
slundberg/shap
shap/datasets.py
imdb
def imdb(display=False): """ Return the clssic IMDB sentiment analysis training data in a nice package. Full data is at: http://ai.stanford.edu/~amaas/data/sentiment/aclImdb_v1.tar.gz Paper to cite when using the data is: http://www.aclweb.org/anthology/P11-1015 """ with open(cache(github_data_url...
python
def imdb(display=False): """ Return the clssic IMDB sentiment analysis training data in a nice package. Full data is at: http://ai.stanford.edu/~amaas/data/sentiment/aclImdb_v1.tar.gz Paper to cite when using the data is: http://www.aclweb.org/anthology/P11-1015 """ with open(cache(github_data_url...
[ "def", "imdb", "(", "display", "=", "False", ")", ":", "with", "open", "(", "cache", "(", "github_data_url", "+", "\"imdb_train.txt\"", ")", ")", "as", "f", ":", "data", "=", "f", ".", "readlines", "(", ")", "y", "=", "np", ".", "ones", "(", "25000...
Return the clssic IMDB sentiment analysis training data in a nice package. Full data is at: http://ai.stanford.edu/~amaas/data/sentiment/aclImdb_v1.tar.gz Paper to cite when using the data is: http://www.aclweb.org/anthology/P11-1015
[ "Return", "the", "clssic", "IMDB", "sentiment", "analysis", "training", "data", "in", "a", "nice", "package", "." ]
b280cb81d498b9d98565cad8dd16fc88ae52649f
https://github.com/slundberg/shap/blob/b280cb81d498b9d98565cad8dd16fc88ae52649f/shap/datasets.py#L37-L48
24,181
slundberg/shap
shap/datasets.py
communitiesandcrime
def communitiesandcrime(display=False): """ Predict total number of non-violent crimes per 100K popuation. This dataset is from the classic UCI Machine Learning repository: https://archive.ics.uci.edu/ml/datasets/Communities+and+Crime+Unnormalized """ raw_data = pd.read_csv( cache(github_d...
python
def communitiesandcrime(display=False): """ Predict total number of non-violent crimes per 100K popuation. This dataset is from the classic UCI Machine Learning repository: https://archive.ics.uci.edu/ml/datasets/Communities+and+Crime+Unnormalized """ raw_data = pd.read_csv( cache(github_d...
[ "def", "communitiesandcrime", "(", "display", "=", "False", ")", ":", "raw_data", "=", "pd", ".", "read_csv", "(", "cache", "(", "github_data_url", "+", "\"CommViolPredUnnormalizedData.txt\"", ")", ",", "na_values", "=", "\"?\"", ")", "# find the indices where the t...
Predict total number of non-violent crimes per 100K popuation. This dataset is from the classic UCI Machine Learning repository: https://archive.ics.uci.edu/ml/datasets/Communities+and+Crime+Unnormalized
[ "Predict", "total", "number", "of", "non", "-", "violent", "crimes", "per", "100K", "popuation", "." ]
b280cb81d498b9d98565cad8dd16fc88ae52649f
https://github.com/slundberg/shap/blob/b280cb81d498b9d98565cad8dd16fc88ae52649f/shap/datasets.py#L50-L71
24,182
slundberg/shap
shap/datasets.py
diabetes
def diabetes(display=False): """ Return the diabetes data in a nice package. """ d = sklearn.datasets.load_diabetes() df = pd.DataFrame(data=d.data, columns=d.feature_names) # pylint: disable=E1101 return df, d.target
python
def diabetes(display=False): """ Return the diabetes data in a nice package. """ d = sklearn.datasets.load_diabetes() df = pd.DataFrame(data=d.data, columns=d.feature_names) # pylint: disable=E1101 return df, d.target
[ "def", "diabetes", "(", "display", "=", "False", ")", ":", "d", "=", "sklearn", ".", "datasets", ".", "load_diabetes", "(", ")", "df", "=", "pd", ".", "DataFrame", "(", "data", "=", "d", ".", "data", ",", "columns", "=", "d", ".", "feature_names", ...
Return the diabetes data in a nice package.
[ "Return", "the", "diabetes", "data", "in", "a", "nice", "package", "." ]
b280cb81d498b9d98565cad8dd16fc88ae52649f
https://github.com/slundberg/shap/blob/b280cb81d498b9d98565cad8dd16fc88ae52649f/shap/datasets.py#L73-L78
24,183
slundberg/shap
shap/datasets.py
iris
def iris(display=False): """ Return the classic iris data in a nice package. """ d = sklearn.datasets.load_iris() df = pd.DataFrame(data=d.data, columns=d.feature_names) # pylint: disable=E1101 if display: return df, [d.target_names[v] for v in d.target] # pylint: disable=E1101 else: ...
python
def iris(display=False): """ Return the classic iris data in a nice package. """ d = sklearn.datasets.load_iris() df = pd.DataFrame(data=d.data, columns=d.feature_names) # pylint: disable=E1101 if display: return df, [d.target_names[v] for v in d.target] # pylint: disable=E1101 else: ...
[ "def", "iris", "(", "display", "=", "False", ")", ":", "d", "=", "sklearn", ".", "datasets", ".", "load_iris", "(", ")", "df", "=", "pd", ".", "DataFrame", "(", "data", "=", "d", ".", "data", ",", "columns", "=", "d", ".", "feature_names", ")", "...
Return the classic iris data in a nice package.
[ "Return", "the", "classic", "iris", "data", "in", "a", "nice", "package", "." ]
b280cb81d498b9d98565cad8dd16fc88ae52649f
https://github.com/slundberg/shap/blob/b280cb81d498b9d98565cad8dd16fc88ae52649f/shap/datasets.py#L81-L89
24,184
slundberg/shap
shap/datasets.py
adult
def adult(display=False): """ Return the Adult census data in a nice package. """ dtypes = [ ("Age", "float32"), ("Workclass", "category"), ("fnlwgt", "float32"), ("Education", "category"), ("Education-Num", "float32"), ("Marital Status", "category"), ("Occupation", "category"), ("Relati...
python
def adult(display=False): """ Return the Adult census data in a nice package. """ dtypes = [ ("Age", "float32"), ("Workclass", "category"), ("fnlwgt", "float32"), ("Education", "category"), ("Education-Num", "float32"), ("Marital Status", "category"), ("Occupation", "category"), ("Relati...
[ "def", "adult", "(", "display", "=", "False", ")", ":", "dtypes", "=", "[", "(", "\"Age\"", ",", "\"float32\"", ")", ",", "(", "\"Workclass\"", ",", "\"category\"", ")", ",", "(", "\"fnlwgt\"", ",", "\"float32\"", ")", ",", "(", "\"Education\"", ",", "...
Return the Adult census data in a nice package.
[ "Return", "the", "Adult", "census", "data", "in", "a", "nice", "package", "." ]
b280cb81d498b9d98565cad8dd16fc88ae52649f
https://github.com/slundberg/shap/blob/b280cb81d498b9d98565cad8dd16fc88ae52649f/shap/datasets.py#L92-L128
24,185
slundberg/shap
shap/datasets.py
nhanesi
def nhanesi(display=False): """ A nicely packaged version of NHANES I data with surivival times as labels. """ X = pd.read_csv(cache(github_data_url + "NHANESI_subset_X.csv")) y = pd.read_csv(cache(github_data_url + "NHANESI_subset_y.csv"))["y"] if display: X_display = X.copy() X_dis...
python
def nhanesi(display=False): """ A nicely packaged version of NHANES I data with surivival times as labels. """ X = pd.read_csv(cache(github_data_url + "NHANESI_subset_X.csv")) y = pd.read_csv(cache(github_data_url + "NHANESI_subset_y.csv"))["y"] if display: X_display = X.copy() X_dis...
[ "def", "nhanesi", "(", "display", "=", "False", ")", ":", "X", "=", "pd", ".", "read_csv", "(", "cache", "(", "github_data_url", "+", "\"NHANESI_subset_X.csv\"", ")", ")", "y", "=", "pd", ".", "read_csv", "(", "cache", "(", "github_data_url", "+", "\"NHA...
A nicely packaged version of NHANES I data with surivival times as labels.
[ "A", "nicely", "packaged", "version", "of", "NHANES", "I", "data", "with", "surivival", "times", "as", "labels", "." ]
b280cb81d498b9d98565cad8dd16fc88ae52649f
https://github.com/slundberg/shap/blob/b280cb81d498b9d98565cad8dd16fc88ae52649f/shap/datasets.py#L131-L141
24,186
slundberg/shap
shap/datasets.py
cric
def cric(display=False): """ A nicely packaged version of CRIC data with progression to ESRD within 4 years as the label. """ X = pd.read_csv(cache(github_data_url + "CRIC_time_4yearESRD_X.csv")) y = np.loadtxt(cache(github_data_url + "CRIC_time_4yearESRD_y.csv")) if display: X_display = X.c...
python
def cric(display=False): """ A nicely packaged version of CRIC data with progression to ESRD within 4 years as the label. """ X = pd.read_csv(cache(github_data_url + "CRIC_time_4yearESRD_X.csv")) y = np.loadtxt(cache(github_data_url + "CRIC_time_4yearESRD_y.csv")) if display: X_display = X.c...
[ "def", "cric", "(", "display", "=", "False", ")", ":", "X", "=", "pd", ".", "read_csv", "(", "cache", "(", "github_data_url", "+", "\"CRIC_time_4yearESRD_X.csv\"", ")", ")", "y", "=", "np", ".", "loadtxt", "(", "cache", "(", "github_data_url", "+", "\"CR...
A nicely packaged version of CRIC data with progression to ESRD within 4 years as the label.
[ "A", "nicely", "packaged", "version", "of", "CRIC", "data", "with", "progression", "to", "ESRD", "within", "4", "years", "as", "the", "label", "." ]
b280cb81d498b9d98565cad8dd16fc88ae52649f
https://github.com/slundberg/shap/blob/b280cb81d498b9d98565cad8dd16fc88ae52649f/shap/datasets.py#L143-L152
24,187
slundberg/shap
shap/datasets.py
corrgroups60
def corrgroups60(display=False): """ Correlated Groups 60 A simulated dataset with tight correlations among distinct groups of features. """ # set a constant seed old_seed = np.random.seed() np.random.seed(0) # generate dataset with known correlation N = 1000 M = 60 # set...
python
def corrgroups60(display=False): """ Correlated Groups 60 A simulated dataset with tight correlations among distinct groups of features. """ # set a constant seed old_seed = np.random.seed() np.random.seed(0) # generate dataset with known correlation N = 1000 M = 60 # set...
[ "def", "corrgroups60", "(", "display", "=", "False", ")", ":", "# set a constant seed", "old_seed", "=", "np", ".", "random", ".", "seed", "(", ")", "np", ".", "random", ".", "seed", "(", "0", ")", "# generate dataset with known correlation", "N", "=", "1000...
Correlated Groups 60 A simulated dataset with tight correlations among distinct groups of features.
[ "Correlated", "Groups", "60", "A", "simulated", "dataset", "with", "tight", "correlations", "among", "distinct", "groups", "of", "features", "." ]
b280cb81d498b9d98565cad8dd16fc88ae52649f
https://github.com/slundberg/shap/blob/b280cb81d498b9d98565cad8dd16fc88ae52649f/shap/datasets.py#L155-L197
24,188
slundberg/shap
shap/datasets.py
independentlinear60
def independentlinear60(display=False): """ A simulated dataset with tight correlations among distinct groups of features. """ # set a constant seed old_seed = np.random.seed() np.random.seed(0) # generate dataset with known correlation N = 1000 M = 60 # set one coefficent from ea...
python
def independentlinear60(display=False): """ A simulated dataset with tight correlations among distinct groups of features. """ # set a constant seed old_seed = np.random.seed() np.random.seed(0) # generate dataset with known correlation N = 1000 M = 60 # set one coefficent from ea...
[ "def", "independentlinear60", "(", "display", "=", "False", ")", ":", "# set a constant seed", "old_seed", "=", "np", ".", "random", ".", "seed", "(", ")", "np", ".", "random", ".", "seed", "(", "0", ")", "# generate dataset with known correlation", "N", "=", ...
A simulated dataset with tight correlations among distinct groups of features.
[ "A", "simulated", "dataset", "with", "tight", "correlations", "among", "distinct", "groups", "of", "features", "." ]
b280cb81d498b9d98565cad8dd16fc88ae52649f
https://github.com/slundberg/shap/blob/b280cb81d498b9d98565cad8dd16fc88ae52649f/shap/datasets.py#L200-L225
24,189
slundberg/shap
shap/datasets.py
rank
def rank(): """ Ranking datasets from lightgbm repository. """ rank_data_url = 'https://raw.githubusercontent.com/Microsoft/LightGBM/master/examples/lambdarank/' x_train, y_train = sklearn.datasets.load_svmlight_file(cache(rank_data_url + 'rank.train')) x_test, y_test = sklearn.datasets.load_svmligh...
python
def rank(): """ Ranking datasets from lightgbm repository. """ rank_data_url = 'https://raw.githubusercontent.com/Microsoft/LightGBM/master/examples/lambdarank/' x_train, y_train = sklearn.datasets.load_svmlight_file(cache(rank_data_url + 'rank.train')) x_test, y_test = sklearn.datasets.load_svmligh...
[ "def", "rank", "(", ")", ":", "rank_data_url", "=", "'https://raw.githubusercontent.com/Microsoft/LightGBM/master/examples/lambdarank/'", "x_train", ",", "y_train", "=", "sklearn", ".", "datasets", ".", "load_svmlight_file", "(", "cache", "(", "rank_data_url", "+", "'rank...
Ranking datasets from lightgbm repository.
[ "Ranking", "datasets", "from", "lightgbm", "repository", "." ]
b280cb81d498b9d98565cad8dd16fc88ae52649f
https://github.com/slundberg/shap/blob/b280cb81d498b9d98565cad8dd16fc88ae52649f/shap/datasets.py#L234-L242
24,190
slundberg/shap
shap/benchmark/measures.py
batch_remove_retrain
def batch_remove_retrain(nmask_train, nmask_test, X_train, y_train, X_test, y_test, attr_train, attr_test, model_generator, metric): """ An approximation of holdout that only retraines the model once. This is alse called ROAR (RemOve And Retrain) in work by Google. It is much more computationally efficient...
python
def batch_remove_retrain(nmask_train, nmask_test, X_train, y_train, X_test, y_test, attr_train, attr_test, model_generator, metric): """ An approximation of holdout that only retraines the model once. This is alse called ROAR (RemOve And Retrain) in work by Google. It is much more computationally efficient...
[ "def", "batch_remove_retrain", "(", "nmask_train", ",", "nmask_test", ",", "X_train", ",", "y_train", ",", "X_test", ",", "y_test", ",", "attr_train", ",", "attr_test", ",", "model_generator", ",", "metric", ")", ":", "warnings", ".", "warn", "(", "\"The retra...
An approximation of holdout that only retraines the model once. This is alse called ROAR (RemOve And Retrain) in work by Google. It is much more computationally efficient that the holdout method because it masks the most important features in every sample and then retrains the model once, instead of retrai...
[ "An", "approximation", "of", "holdout", "that", "only", "retraines", "the", "model", "once", "." ]
b280cb81d498b9d98565cad8dd16fc88ae52649f
https://github.com/slundberg/shap/blob/b280cb81d498b9d98565cad8dd16fc88ae52649f/shap/benchmark/measures.py#L158-L193
24,191
slundberg/shap
shap/benchmark/measures.py
keep_retrain
def keep_retrain(nkeep, X_train, y_train, X_test, y_test, attr_test, model_generator, metric, trained_model, random_state): """ The model is retrained for each test sample with the non-important features set to a constant. If you want to know how important a set of features is you can ask how the model would b...
python
def keep_retrain(nkeep, X_train, y_train, X_test, y_test, attr_test, model_generator, metric, trained_model, random_state): """ The model is retrained for each test sample with the non-important features set to a constant. If you want to know how important a set of features is you can ask how the model would b...
[ "def", "keep_retrain", "(", "nkeep", ",", "X_train", ",", "y_train", ",", "X_test", ",", "y_test", ",", "attr_test", ",", "model_generator", ",", "metric", ",", "trained_model", ",", "random_state", ")", ":", "warnings", ".", "warn", "(", "\"The retrain based ...
The model is retrained for each test sample with the non-important features set to a constant. If you want to know how important a set of features is you can ask how the model would be different if only those features had existed. To determine this we can mask the other features across the entire training ...
[ "The", "model", "is", "retrained", "for", "each", "test", "sample", "with", "the", "non", "-", "important", "features", "set", "to", "a", "constant", "." ]
b280cb81d498b9d98565cad8dd16fc88ae52649f
https://github.com/slundberg/shap/blob/b280cb81d498b9d98565cad8dd16fc88ae52649f/shap/benchmark/measures.py#L196-L258
24,192
slundberg/shap
shap/benchmark/measures.py
keep_mask
def keep_mask(nkeep, X_train, y_train, X_test, y_test, attr_test, model_generator, metric, trained_model, random_state): """ The model is revaluated for each test sample with the non-important features set to their mean. """ X_train, X_test = to_array(X_train, X_test) # how many features to mask a...
python
def keep_mask(nkeep, X_train, y_train, X_test, y_test, attr_test, model_generator, metric, trained_model, random_state): """ The model is revaluated for each test sample with the non-important features set to their mean. """ X_train, X_test = to_array(X_train, X_test) # how many features to mask a...
[ "def", "keep_mask", "(", "nkeep", ",", "X_train", ",", "y_train", ",", "X_test", ",", "y_test", ",", "attr_test", ",", "model_generator", ",", "metric", ",", "trained_model", ",", "random_state", ")", ":", "X_train", ",", "X_test", "=", "to_array", "(", "X...
The model is revaluated for each test sample with the non-important features set to their mean.
[ "The", "model", "is", "revaluated", "for", "each", "test", "sample", "with", "the", "non", "-", "important", "features", "set", "to", "their", "mean", "." ]
b280cb81d498b9d98565cad8dd16fc88ae52649f
https://github.com/slundberg/shap/blob/b280cb81d498b9d98565cad8dd16fc88ae52649f/shap/benchmark/measures.py#L260-L281
24,193
slundberg/shap
shap/benchmark/measures.py
keep_impute
def keep_impute(nkeep, X_train, y_train, X_test, y_test, attr_test, model_generator, metric, trained_model, random_state): """ The model is revaluated for each test sample with the non-important features set to an imputed value. Note that the imputation is done using a multivariate normality assumption on the ...
python
def keep_impute(nkeep, X_train, y_train, X_test, y_test, attr_test, model_generator, metric, trained_model, random_state): """ The model is revaluated for each test sample with the non-important features set to an imputed value. Note that the imputation is done using a multivariate normality assumption on the ...
[ "def", "keep_impute", "(", "nkeep", ",", "X_train", ",", "y_train", ",", "X_test", ",", "y_test", ",", "attr_test", ",", "model_generator", ",", "metric", ",", "trained_model", ",", "random_state", ")", ":", "X_train", ",", "X_test", "=", "to_array", "(", ...
The model is revaluated for each test sample with the non-important features set to an imputed value. Note that the imputation is done using a multivariate normality assumption on the dataset. This depends on being able to estimate the full data covariance matrix (and inverse) accuractly. So X_train.shape[0] s...
[ "The", "model", "is", "revaluated", "for", "each", "test", "sample", "with", "the", "non", "-", "important", "features", "set", "to", "an", "imputed", "value", "." ]
b280cb81d498b9d98565cad8dd16fc88ae52649f
https://github.com/slundberg/shap/blob/b280cb81d498b9d98565cad8dd16fc88ae52649f/shap/benchmark/measures.py#L283-L318
24,194
slundberg/shap
shap/benchmark/measures.py
keep_resample
def keep_resample(nkeep, X_train, y_train, X_test, y_test, attr_test, model_generator, metric, trained_model, random_state): """ The model is revaluated for each test sample with the non-important features set to resample background values. """ # why broken? overwriting? X_train, X_test = to_array(X_train,...
python
def keep_resample(nkeep, X_train, y_train, X_test, y_test, attr_test, model_generator, metric, trained_model, random_state): """ The model is revaluated for each test sample with the non-important features set to resample background values. """ # why broken? overwriting? X_train, X_test = to_array(X_train,...
[ "def", "keep_resample", "(", "nkeep", ",", "X_train", ",", "y_train", ",", "X_test", ",", "y_test", ",", "attr_test", ",", "model_generator", ",", "metric", ",", "trained_model", ",", "random_state", ")", ":", "# why broken? overwriting?", "X_train", ",", "X_tes...
The model is revaluated for each test sample with the non-important features set to resample background values.
[ "The", "model", "is", "revaluated", "for", "each", "test", "sample", "with", "the", "non", "-", "important", "features", "set", "to", "resample", "background", "values", "." ]
b280cb81d498b9d98565cad8dd16fc88ae52649f
https://github.com/slundberg/shap/blob/b280cb81d498b9d98565cad8dd16fc88ae52649f/shap/benchmark/measures.py#L320-L345
24,195
slundberg/shap
shap/benchmark/measures.py
local_accuracy
def local_accuracy(X_train, y_train, X_test, y_test, attr_test, model_generator, metric, trained_model): """ The how well do the features plus a constant base rate sum up to the model output. """ X_train, X_test = to_array(X_train, X_test) # how many features to mask assert X_train.shape[1] == X_t...
python
def local_accuracy(X_train, y_train, X_test, y_test, attr_test, model_generator, metric, trained_model): """ The how well do the features plus a constant base rate sum up to the model output. """ X_train, X_test = to_array(X_train, X_test) # how many features to mask assert X_train.shape[1] == X_t...
[ "def", "local_accuracy", "(", "X_train", ",", "y_train", ",", "X_test", ",", "y_test", ",", "attr_test", ",", "model_generator", ",", "metric", ",", "trained_model", ")", ":", "X_train", ",", "X_test", "=", "to_array", "(", "X_train", ",", "X_test", ")", "...
The how well do the features plus a constant base rate sum up to the model output.
[ "The", "how", "well", "do", "the", "features", "plus", "a", "constant", "base", "rate", "sum", "up", "to", "the", "model", "output", "." ]
b280cb81d498b9d98565cad8dd16fc88ae52649f
https://github.com/slundberg/shap/blob/b280cb81d498b9d98565cad8dd16fc88ae52649f/shap/benchmark/measures.py#L384-L396
24,196
slundberg/shap
shap/benchmark/measures.py
const_rand
def const_rand(size, seed=23980): """ Generate a random array with a fixed seed. """ old_seed = np.random.seed() np.random.seed(seed) out = np.random.rand(size) np.random.seed(old_seed) return out
python
def const_rand(size, seed=23980): """ Generate a random array with a fixed seed. """ old_seed = np.random.seed() np.random.seed(seed) out = np.random.rand(size) np.random.seed(old_seed) return out
[ "def", "const_rand", "(", "size", ",", "seed", "=", "23980", ")", ":", "old_seed", "=", "np", ".", "random", ".", "seed", "(", ")", "np", ".", "random", ".", "seed", "(", "seed", ")", "out", "=", "np", ".", "random", ".", "rand", "(", "size", "...
Generate a random array with a fixed seed.
[ "Generate", "a", "random", "array", "with", "a", "fixed", "seed", "." ]
b280cb81d498b9d98565cad8dd16fc88ae52649f
https://github.com/slundberg/shap/blob/b280cb81d498b9d98565cad8dd16fc88ae52649f/shap/benchmark/measures.py#L401-L408
24,197
slundberg/shap
shap/benchmark/measures.py
const_shuffle
def const_shuffle(arr, seed=23980): """ Shuffle an array in-place with a fixed seed. """ old_seed = np.random.seed() np.random.seed(seed) np.random.shuffle(arr) np.random.seed(old_seed)
python
def const_shuffle(arr, seed=23980): """ Shuffle an array in-place with a fixed seed. """ old_seed = np.random.seed() np.random.seed(seed) np.random.shuffle(arr) np.random.seed(old_seed)
[ "def", "const_shuffle", "(", "arr", ",", "seed", "=", "23980", ")", ":", "old_seed", "=", "np", ".", "random", ".", "seed", "(", ")", "np", ".", "random", ".", "seed", "(", "seed", ")", "np", ".", "random", ".", "shuffle", "(", "arr", ")", "np", ...
Shuffle an array in-place with a fixed seed.
[ "Shuffle", "an", "array", "in", "-", "place", "with", "a", "fixed", "seed", "." ]
b280cb81d498b9d98565cad8dd16fc88ae52649f
https://github.com/slundberg/shap/blob/b280cb81d498b9d98565cad8dd16fc88ae52649f/shap/benchmark/measures.py#L410-L416
24,198
slundberg/shap
shap/common.py
hclust_ordering
def hclust_ordering(X, metric="sqeuclidean"): """ A leaf ordering is under-defined, this picks the ordering that keeps nearby samples similar. """ # compute a hierarchical clustering D = sp.spatial.distance.pdist(X, metric) cluster_matrix = sp.cluster.hierarchy.complete(D) # merge clus...
python
def hclust_ordering(X, metric="sqeuclidean"): """ A leaf ordering is under-defined, this picks the ordering that keeps nearby samples similar. """ # compute a hierarchical clustering D = sp.spatial.distance.pdist(X, metric) cluster_matrix = sp.cluster.hierarchy.complete(D) # merge clus...
[ "def", "hclust_ordering", "(", "X", ",", "metric", "=", "\"sqeuclidean\"", ")", ":", "# compute a hierarchical clustering", "D", "=", "sp", ".", "spatial", ".", "distance", ".", "pdist", "(", "X", ",", "metric", ")", "cluster_matrix", "=", "sp", ".", "cluste...
A leaf ordering is under-defined, this picks the ordering that keeps nearby samples similar.
[ "A", "leaf", "ordering", "is", "under", "-", "defined", "this", "picks", "the", "ordering", "that", "keeps", "nearby", "samples", "similar", "." ]
b280cb81d498b9d98565cad8dd16fc88ae52649f
https://github.com/slundberg/shap/blob/b280cb81d498b9d98565cad8dd16fc88ae52649f/shap/common.py#L215-L247
24,199
slundberg/shap
shap/common.py
approximate_interactions
def approximate_interactions(index, shap_values, X, feature_names=None): """ Order other features by how much interaction they seem to have with the feature at the given index. This just bins the SHAP values for a feature along that feature's value. For true Shapley interaction index values for SHAP see th...
python
def approximate_interactions(index, shap_values, X, feature_names=None): """ Order other features by how much interaction they seem to have with the feature at the given index. This just bins the SHAP values for a feature along that feature's value. For true Shapley interaction index values for SHAP see th...
[ "def", "approximate_interactions", "(", "index", ",", "shap_values", ",", "X", ",", "feature_names", "=", "None", ")", ":", "# convert from DataFrames if we got any", "if", "str", "(", "type", "(", "X", ")", ")", ".", "endswith", "(", "\"'pandas.core.frame.DataFra...
Order other features by how much interaction they seem to have with the feature at the given index. This just bins the SHAP values for a feature along that feature's value. For true Shapley interaction index values for SHAP see the interaction_contribs option implemented in XGBoost.
[ "Order", "other", "features", "by", "how", "much", "interaction", "they", "seem", "to", "have", "with", "the", "feature", "at", "the", "given", "index", "." ]
b280cb81d498b9d98565cad8dd16fc88ae52649f
https://github.com/slundberg/shap/blob/b280cb81d498b9d98565cad8dd16fc88ae52649f/shap/common.py#L271-L318