Code
stringlengths
103
85.9k
Summary
listlengths
0
94
Please provide a description of the function:def tokenize(self, path): assert os.path.exists(path) # Add words to the dictionary with open(path, 'r') as f: tokens = 0 for line in f: words = line.split() + ['<eos>'] tokens += len(wo...
[ "Tokenizes a text file." ]
Please provide a description of the function:def _build_doc(func_name, desc, arg_names, arg_types, arg_desc, key_var_num_args=None, ret_type=None): param_str = _build_param_doc(arg_names, arg_types, arg_desc) if key_v...
[ "Build docstring for symbolic functions." ]
Please provide a description of the function:def get_output_shape(sym, **input_shapes): _, s_outputs, _ = sym.infer_shape(**input_shapes) return dict(zip(sym.list_outputs(), s_outputs))
[ "Get user friendly information of the output shapes." ]
Please provide a description of the function:def num_gpus(): count = ctypes.c_int() check_call(_LIB.MXGetGPUCount(ctypes.byref(count))) return count.value
[ "Query CUDA for the number of GPUs present.\n\n Raises\n ------\n Will raise an exception on any CUDA error.\n\n Returns\n -------\n count : int\n The number of GPUs.\n\n " ]
Please provide a description of the function:def gpu_memory_info(device_id=0): free = ctypes.c_uint64() total = ctypes.c_uint64() dev_id = ctypes.c_int(device_id) check_call(_LIB.MXGetGPUMemoryInformation64(dev_id, ctypes.byref(free), ctypes.byref(total))) return (free.value, total.value)
[ "Query CUDA for the free and total bytes of GPU global memory.\n\n Parameters\n ----------\n device_id : int, optional\n The device id of the GPU device.\n\n Raises\n ------\n Will raise an exception on any CUDA error.\n\n Returns\n -------\n (free, total) : (int, int)\n The...
Please provide a description of the function:def current_context(): if not hasattr(Context._default_ctx, "value"): Context._default_ctx.value = Context('cpu', 0) return Context._default_ctx.value
[ "Returns the current context.\n\n By default, `mx.cpu()` is used for all the computations\n and it can be overridden by using `with mx.Context(x)` statement where\n x can be cpu(device_id) or gpu(device_id).\n\n Examples\n -------\n >>> mx.current_context()\n cpu(0)\n >>> with mx.Context('gp...
Please provide a description of the function:def _list_audio_files(self, root, skip_rows=0): self.synsets = [] self.items = [] if not self._train_csv: # The audio files are organized in folder structure with # directory name as label and audios in them ...
[ "Populates synsets - a map of index to label for the data items.\n Populates the data in the dataset, making tuples of (data, label)\n " ]
Please provide a description of the function:def transform_first(self, fn, lazy=False): return super(AudioFolderDataset, self).transform_first(fn, lazy=lazy)
[ "Returns a new dataset with the first element of each sample\n transformed by the transformer function `fn`.\n\n This is useful, for example, when you only want to transform data\n while keeping label as is.\n lazy=False is passed to transform_first for dataset so that all tramsforms cou...
Please provide a description of the function:def config_cython(): if not with_cython: return [] # pylint: disable=unreachable if os.name == 'nt': print("WARNING: Cython is not supported on Windows, will compile without cython module") return [] try: from Cython.Buil...
[ "Try to configure cython and return cython configuration" ]
Please provide a description of the function:def _compose(self, *args, **kwargs): name = kwargs.pop('name', None) if name: name = c_str(name) if len(args) != 0 and len(kwargs) != 0: raise TypeError('compose only accept input Symbols \ either as p...
[ "Compose symbol on inputs.\n\n This call mutates the current symbol.\n\n Parameters\n ----------\n args:\n provide positional arguments\n\n kwargs:\n provide keyword arguments\n\n Returns\n -------\n the resulting symbol\n " ]
Please provide a description of the function:def _set_attr(self, **kwargs): keys = c_str_array(kwargs.keys()) vals = c_str_array([str(s) for s in kwargs.values()]) num_args = mx_uint(len(kwargs)) check_call(_LIB.MXSymbolSetAttrs( self.handle, num_args, keys, vals))
[ "Set the attribute of the symbol.\n\n Parameters\n ----------\n **kwargs\n The attributes to set\n " ]
Please provide a description of the function:def get_config(network, data_shape, **kwargs): if network == 'vgg16_reduced': if data_shape >= 448: from_layers = ['relu4_3', 'relu7', '', '', '', '', ''] num_filters = [512, -1, 512, 256, 256, 256, 256] strides = [-1, -1,...
[ "Configuration factory for various networks\n\n Parameters\n ----------\n network : str\n base network name, such as vgg_reduced, inceptionv3, resnet...\n data_shape : int\n input data dimension\n kwargs : dict\n extra arguments\n " ]
Please provide a description of the function:def get_symbol_train(network, data_shape, **kwargs): if network.startswith('legacy'): logging.warn('Using legacy model.') return symbol_builder.import_module(network).get_symbol_train(**kwargs) config = get_config(network, data_shape, **kwargs).c...
[ "Wrapper for get symbol for train\n\n Parameters\n ----------\n network : str\n name for the base network symbol\n data_shape : int\n input shape\n kwargs : dict\n see symbol_builder.get_symbol_train for more details\n " ]
Please provide a description of the function:def _set_trainer(self, trainer): # trainer cannot be replaced for sparse params if self._stype != 'default' and self._trainer and trainer and self._trainer is not trainer: raise RuntimeError( "Failed to set the trainer for...
[ " Set the trainer this parameter is associated with. " ]
Please provide a description of the function:def _get_row_sparse(self, arr_list, ctx, row_id): # get row sparse params based on row ids if not isinstance(row_id, ndarray.NDArray): raise TypeError("row_id must have NDArray type, but %s is given"%(type(row_id))) if not self._t...
[ " Get row_sparse data from row_sparse parameters based on row_id. " ]
Please provide a description of the function:def _load_init(self, data, ctx): if self.shape: for self_dim, data_dim in zip(self.shape, data.shape): assert self_dim in (0, data_dim), \ "Failed loading Parameter '%s' from saved params: " \ ...
[ "(Re)initializes by loading from data." ]
Please provide a description of the function:def _finish_deferred_init(self): if not self._deferred_init: return init, ctx, default_init, data = self._deferred_init self._deferred_init = () assert self.shape is not None and np.prod(self.shape) > 0, \ "Can...
[ "Finishes deferred initialization." ]
Please provide a description of the function:def _init_impl(self, data, ctx_list): self._ctx_list = list(ctx_list) self._ctx_map = [[], []] for i, ctx in enumerate(self._ctx_list): dev_list = self._ctx_map[ctx.device_typeid&1] while len(dev_list) <= ctx.device_id...
[ "Sets data and grad." ]
Please provide a description of the function:def _init_grad(self): if self.grad_req == 'null': self._grad = None return self._grad = [ndarray.zeros(shape=i.shape, dtype=i.dtype, ctx=i.context, stype=self._grad_stype) for i in self._da...
[ "Initialize grad buffers." ]
Please provide a description of the function:def _reduce(self): ctx = context.cpu() if self._stype == 'default': block = self.list_data() data = ndarray.add_n(*(w.copyto(ctx) for w in block)) / len(block) else: # fetch all rows for 'row_sparse' param ...
[ "Reduce data from multiple context to cpu." ]
Please provide a description of the function:def initialize(self, init=None, ctx=None, default_init=initializer.Uniform(), force_reinit=False): if self._data is not None and not force_reinit: warnings.warn("Parameter '%s' is already initialized, ignoring. " \ ...
[ "Initializes parameter and gradient arrays. Only used for :py:class:`NDArray` API.\n\n Parameters\n ----------\n init : Initializer\n The initializer to use. Overrides :py:meth:`Parameter.init` and default_init.\n ctx : Context or list of Context, defaults to :py:meth:`context...
Please provide a description of the function:def reset_ctx(self, ctx): if ctx is None: ctx = [context.current_context()] if isinstance(ctx, Context): ctx = [ctx] if self._data: data = self._reduce() with autograd.pause(): s...
[ "Re-assign Parameter to other contexts.\n\n Parameters\n ----------\n ctx : Context or list of Context, default ``context.current_context()``.\n Assign Parameter to given context. If ctx is a list of Context, a\n copy will be made for each context.\n " ]
Please provide a description of the function:def set_data(self, data): self.shape = data.shape if self._data is None: assert self._deferred_init, \ "Parameter '%s' has not been initialized"%self.name self._deferred_init = self._deferred_init[:3] + (data,...
[ "Sets this parameter's value on all contexts." ]
Please provide a description of the function:def row_sparse_data(self, row_id): if self._stype != 'row_sparse': raise RuntimeError("Cannot return a copy of Parameter %s via row_sparse_data() " \ "because its storage type is %s. Please use data() instead." \ ...
[ "Returns a copy of the 'row_sparse' parameter on the same context as row_id's.\n The copy only retains rows whose ids occur in provided row ids.\n The parameter must have been initialized on this context before.\n\n Parameters\n ----------\n row_id: NDArray\n Row ids to...
Please provide a description of the function:def list_row_sparse_data(self, row_id): if self._stype != 'row_sparse': raise RuntimeError("Cannot return copies of Parameter '%s' on all contexts via " \ "list_row_sparse_data() because its storage type is %s. Plea...
[ "Returns copies of the 'row_sparse' parameter on all contexts, in the same order\n as creation. The copy only retains rows whose ids occur in provided row ids.\n The parameter must have been initialized before.\n\n Parameters\n ----------\n row_id: NDArray\n Row ids to ...
Please provide a description of the function:def data(self, ctx=None): if self._stype != 'default': raise RuntimeError("Cannot return a copy of Parameter '%s' on ctx %s via data() " \ "because its storage type is %s. Please use row_sparse_data() " \ ...
[ "Returns a copy of this parameter on one context. Must have been\n initialized on this context before. For sparse parameters, use\n :py:meth:`Parameter.row_sparse_data` instead.\n\n Parameters\n ----------\n ctx : Context\n Desired context.\n\n Returns\n -...
Please provide a description of the function:def list_data(self): if self._stype != 'default': raise RuntimeError("Cannot return copies of Parameter '%s' on all contexts via " \ "list_data() because its storage type is %s. Please use " \ ...
[ "Returns copies of this parameter on all contexts, in the same order\n as creation. For sparse parameters, use :py:meth:`Parameter.list_row_sparse_data`\n instead.\n\n Returns\n -------\n list of NDArrays\n " ]
Please provide a description of the function:def grad(self, ctx=None): if self._data is not None and self._grad is None: raise RuntimeError( "Cannot get gradient array for Parameter '%s' " \ "because grad_req='null'"%(self.name)) return self._check_an...
[ "Returns a gradient buffer for this parameter on one context.\n\n Parameters\n ----------\n ctx : Context\n Desired context.\n " ]
Please provide a description of the function:def list_grad(self): if self._data is not None and self._grad is None: raise RuntimeError( "Cannot get gradient array for Parameter '%s' " \ "because grad_req='null'"%(self.name)) return self._check_and_get...
[ "Returns gradient buffers on all contexts, in the same order\n as :py:meth:`values`." ]
Please provide a description of the function:def list_ctx(self): if self._data is None: if self._deferred_init: return self._deferred_init[1] raise RuntimeError("Parameter '%s' has not been initialized"%self.name) return self._ctx_list
[ "Returns a list of contexts this parameter is initialized on." ]
Please provide a description of the function:def zero_grad(self): if self._grad is None: return for i in self._grad: ndarray.zeros_like(i, out=i)
[ "Sets gradient buffer on all contexts to 0. No action is taken if\n parameter is uninitialized or doesn't require gradient." ]
Please provide a description of the function:def var(self): if self._var is None: self._var = symbol.var(self.name, shape=self.shape, dtype=self.dtype, lr_mult=self.lr_mult, wd_mult=self.wd_mult, init=self.init, stype=sel...
[ "Returns a symbol representing this parameter." ]
Please provide a description of the function:def cast(self, dtype): self.dtype = dtype if self._data is None: return with autograd.pause(): self._data = [i.astype(dtype) for i in self._data] if self._grad is None: return se...
[ "Cast data and gradient of this Parameter to a new data type.\n\n Parameters\n ----------\n dtype : str or numpy.dtype\n The new data type.\n " ]
Please provide a description of the function:def get(self, name, **kwargs): name = self.prefix + name param = self._get_impl(name) if param is None: # pylint: disable=too-many-nested-blocks param = Parameter(name, **kwargs) self._params[name] = param else...
[ "Retrieves a :py:class:`Parameter` with name ``self.prefix+name``. If not found,\n :py:func:`get` will first try to retrieve it from \"shared\" dict. If still not\n found, :py:func:`get` will create a new :py:class:`Parameter` with key-word arguments and\n insert it to self.\n\n Paramete...
Please provide a description of the function:def get_constant(self, name, value=None): name = self.prefix + name param = self._get_impl(name) if param is None: if value is None: raise KeyError("No constant named '{}'. Please specify value " \ ...
[ "Retrieves a :py:class:`.Constant` with name ``self.prefix+name``. If not found,\n :py:func:`get` will first try to retrieve it from \"shared\" dict. If still not\n found, :py:func:`get` will create a new :py:class:`.Constant` with key-word\n arguments and insert it to self.\n\n Paramete...
Please provide a description of the function:def update(self, other): for k, v in other.items(): if k in self._params: assert self._params[k] is v, \ "Cannot update self with other because they have different " \ "Parameters with the s...
[ "Copies all Parameters in ``other`` to self." ]
Please provide a description of the function:def initialize(self, init=initializer.Uniform(), ctx=None, verbose=False, force_reinit=False): if verbose: init.set_verbosity(verbose=verbose) for _, v in self.items(): v.initialize(None, ctx, init, force_re...
[ "Initializes all Parameters managed by this dictionary to be used for :py:class:`NDArray`\n API. It has no effect when using :py:class:`Symbol` API.\n\n Parameters\n ----------\n init : Initializer\n Global default Initializer to be used when :py:meth:`Parameter.init` is ``Non...
Please provide a description of the function:def save(self, filename, strip_prefix=''): arg_dict = {} for param in self.values(): weight = param._reduce() if not param.name.startswith(strip_prefix): raise ValueError( "Prefix '%s' is to...
[ "Save parameters to file.\n\n Parameters\n ----------\n filename : str\n Path to parameter file.\n strip_prefix : str, default ''\n Strip prefix from parameter names before saving.\n " ]
Please provide a description of the function:def load(self, filename, ctx=None, allow_missing=False, ignore_extra=False, restore_prefix=''): if restore_prefix: for name in self.keys(): assert name.startswith(restore_prefix), \ "restore_prefix...
[ "Load parameters from file.\n\n Parameters\n ----------\n filename : str\n Path to parameter file.\n ctx : Context or list of Context\n Context(s) initialize loaded parameters on.\n allow_missing : bool, default False\n Whether to silently skip loa...
Please provide a description of the function:def _make_torch_function(handle): # Get the property of function n_used_vars = mx_uint() n_scalars = mx_uint() n_mutate_vars = mx_uint() type_mask = ctypes.c_int() check_call(_LIB.MXFuncDescribe( handle, ctypes.byref(n_used_vars),...
[ "Create a Torch function from the FunctionHandle.", "Invoke this function by passing in parameters.\n\n Parameters\n ----------\n *args\n Positional arguments of inputs (both scalar and `NDArray`).\n\n Returns\n -------\n out : NDArray\n The result N...
Please provide a description of the function:def _init_torch_module(): plist = ctypes.POINTER(FunctionHandle)() size = ctypes.c_uint() check_call(_LIB.MXListFunctions(ctypes.byref(size), ctypes.byref(plist))) module_obj = sys.modules[__name__] for i in range...
[ "List and add all the torch backed ndarray functions to current module." ]
Please provide a description of the function:def inception_v3(pretrained=False, ctx=cpu(), root=os.path.join(base.data_dir(), 'models'), **kwargs): r net = Inception3(**kwargs) if pretrained: from ..model_store import get_model_file net.load_parameters(get_model_file('incept...
[ "Inception v3 model from\n `\"Rethinking the Inception Architecture for Computer Vision\"\n <http://arxiv.org/abs/1512.00567>`_ paper.\n\n Parameters\n ----------\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n ctx : Context, default CPU\n The...
Please provide a description of the function:def pack(header, s): header = IRHeader(*header) if isinstance(header.label, numbers.Number): header = header._replace(flag=0) else: label = np.asarray(header.label, dtype=np.float32) header = header._replace(flag=label.size, label=0) ...
[ "Pack a string into MXImageRecord.\n\n Parameters\n ----------\n header : IRHeader\n Header of the image record.\n ``header.label`` can be a number or an array. See more detail in ``IRHeader``.\n s : str\n Raw image string to be packed.\n\n Returns\n -------\n s : str\n ...
Please provide a description of the function:def unpack(s): header = IRHeader(*struct.unpack(_IR_FORMAT, s[:_IR_SIZE])) s = s[_IR_SIZE:] if header.flag > 0: header = header._replace(label=np.frombuffer(s, np.float32, header.flag)) s = s[header.flag*4:] return header, s
[ "Unpack a MXImageRecord to string.\n\n Parameters\n ----------\n s : str\n String buffer from ``MXRecordIO.read``.\n\n Returns\n -------\n header : IRHeader\n Header of the image record.\n s : str\n Unpacked string.\n\n Examples\n --------\n >>> record = mx.recordi...
Please provide a description of the function:def unpack_img(s, iscolor=-1): header, s = unpack(s) img = np.frombuffer(s, dtype=np.uint8) assert cv2 is not None img = cv2.imdecode(img, iscolor) return header, img
[ "Unpack a MXImageRecord to image.\n\n Parameters\n ----------\n s : str\n String buffer from ``MXRecordIO.read``.\n iscolor : int\n Image format option for ``cv2.imdecode``.\n\n Returns\n -------\n header : IRHeader\n Header of the image record.\n img : numpy.ndarray\n ...
Please provide a description of the function:def pack_img(header, img, quality=95, img_fmt='.jpg'): assert cv2 is not None jpg_formats = ['.JPG', '.JPEG'] png_formats = ['.PNG'] encode_params = None if img_fmt.upper() in jpg_formats: encode_params = [cv2.IMWRITE_JPEG_QUALITY, quality] ...
[ "Pack an image into ``MXImageRecord``.\n\n Parameters\n ----------\n header : IRHeader\n Header of the image record.\n ``header.label`` can be a number or an array. See more detail in ``IRHeader``.\n img : numpy.ndarray\n Image to be packed.\n quality : int\n Quality for J...
Please provide a description of the function:def open(self): if self.flag == "w": check_call(_LIB.MXRecordIOWriterCreate(self.uri, ctypes.byref(self.handle))) self.writable = True elif self.flag == "r": check_call(_LIB.MXRecordIOReaderCreate(self.uri, ctypes....
[ "Opens the record file." ]
Please provide a description of the function:def _check_pid(self, allow_reset=False): if not self.pid == current_process().pid: if allow_reset: self.reset() else: raise RuntimeError("Forbidden operation in multiple processes")
[ "Check process id to ensure integrity, reset if in new process." ]
Please provide a description of the function:def close(self): if not self.is_open: return if self.writable: check_call(_LIB.MXRecordIOWriterFree(self.handle)) else: check_call(_LIB.MXRecordIOReaderFree(self.handle)) self.is_open = False ...
[ "Closes the record file." ]
Please provide a description of the function:def write(self, buf): assert self.writable self._check_pid(allow_reset=False) check_call(_LIB.MXRecordIOWriterWriteRecord(self.handle, ctypes.c_char_p(buf), ...
[ "Inserts a string buffer as a record.\n\n Examples\n ---------\n >>> record = mx.recordio.MXRecordIO('tmp.rec', 'w')\n >>> for i in range(5):\n ... record.write('record_%d'%i)\n >>> record.close()\n\n Parameters\n ----------\n buf : string (python2),...
Please provide a description of the function:def read(self): assert not self.writable # trying to implicitly read from multiple processes is forbidden, # there's no elegant way to handle unless lock is introduced self._check_pid(allow_reset=False) buf = ctypes.c_char_p()...
[ "Returns record as a string.\n\n Examples\n ---------\n >>> record = mx.recordio.MXRecordIO('tmp.rec', 'r')\n >>> for i in range(5):\n ... item = record.read()\n ... print(item)\n record_0\n record_1\n record_2\n record_3\n record_4\...
Please provide a description of the function:def close(self): if not self.is_open: return super(MXIndexedRecordIO, self).close() self.fidx.close()
[ "Closes the record file." ]
Please provide a description of the function:def seek(self, idx): assert not self.writable self._check_pid(allow_reset=True) pos = ctypes.c_size_t(self.idx[idx]) check_call(_LIB.MXRecordIOReaderSeek(self.handle, pos))
[ "Sets the current read pointer position.\n\n This function is internally called by `read_idx(idx)` to find the current\n reader pointer position. It doesn't return anything." ]
Please provide a description of the function:def tell(self): assert self.writable pos = ctypes.c_size_t() check_call(_LIB.MXRecordIOWriterTell(self.handle, ctypes.byref(pos))) return pos.value
[ "Returns the current position of write head.\n\n Examples\n ---------\n >>> record = mx.recordio.MXIndexedRecordIO('tmp.idx', 'tmp.rec', 'w')\n >>> print(record.tell())\n 0\n >>> for i in range(5):\n ... record.write_idx(i, 'record_%d'%i)\n ... print(r...
Please provide a description of the function:def write_idx(self, idx, buf): key = self.key_type(idx) pos = self.tell() self.write(buf) self.fidx.write('%s\t%d\n'%(str(key), pos)) self.idx[key] = pos self.keys.append(key)
[ "Inserts input record at given index.\n\n Examples\n ---------\n >>> for i in range(5):\n ... record.write_idx(i, 'record_%d'%i)\n >>> record.close()\n\n Parameters\n ----------\n idx : int\n Index of a file.\n buf :\n Record t...
Please provide a description of the function: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) for col in new_columns: dataframe[col] = None
[ "Add new metrics as new columns to selected pandas dataframe.\n\n Parameters\n ----------\n dataframe : pandas.DataFrame\n Selected dataframe needs to be modified.\n metrics : metric.EvalMetric\n New metrics to be added.\n " ]
Please provide a description of the function:def args_wrapper(*args): out = defaultdict(list) for callback in args: callback_args = callback.callback_args() for k, v in callback_args.items(): out[k].append(v) return dict(out)
[ "Generates callback arguments for model.fit()\n for a set of callback objects.\n Callback objects like PandasLogger(), LiveLearningCurve()\n get passed in. This assembles all their callback arguments.\n " ]
Please provide a description of the function:def append_metrics(self, metrics, df_name): dataframe = self._dataframes[df_name] _add_new_columns(dataframe, metrics) dataframe.loc[len(dataframe)] = metrics
[ "Append new metrics to selected dataframes.\n\n Parameters\n ----------\n metrics : metric.EvalMetric\n New metrics to be added.\n df_name : str\n Name of the dataframe to be modified.\n " ]
Please provide a description of the function:def train_cb(self, param): if param.nbatch % self.frequent == 0: self._process_batch(param, 'train')
[ "Callback funtion for training.\n " ]
Please provide a description of the function:def _process_batch(self, param, dataframe): now = time.time() if param.eval_metric is not None: metrics = dict(param.eval_metric.get_name_value()) param.eval_metric.reset() else: metrics = {} # #115...
[ "Update parameters for selected dataframe after a completed batch\n Parameters\n ----------\n dataframe : pandas.DataFrame\n Selected dataframe needs to be modified.\n " ]
Please provide a description of the function:def epoch_cb(self): metrics = {} metrics['elapsed'] = self.elapsed() now = datetime.datetime.now() metrics['epoch_time'] = now - self.last_epoch_time self.append_metrics(metrics, 'epoch') self.last_epoch_time = now
[ "Callback function after each epoch. Now it records each epoch time\n and append it to epoch dataframe.\n " ]
Please provide a description of the function: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.\n " ]
Please provide a description of the function:def _process_batch(self, param, df_name): if param.eval_metric is not None: metrics = dict(param.eval_metric.get_name_value()) param.eval_metric.reset() else: metrics = {} metrics['elapsed'] = datetime.date...
[ "Update selected dataframe after a completed batch\n Parameters\n ----------\n df_name : str\n Selected dataframe name needs to be modified.\n " ]
Please provide a description of the function:def build_vocab(nested_list): # Build vocabulary word_counts = Counter(itertools.chain(*nested_list)) # Mapping from index to label vocabulary_inv = [x[0] for x in word_counts.most_common()] # Mapping from label to index vocabulary = {x: i for ...
[ "\n :param nested_list: list of list of string\n :return: dictionary mapping from string to int, inverse of that dictionary\n " ]
Please provide a description of the function:def build_iters(data_dir, max_records, train_fraction, batch_size, buckets=None): # Read in data as numpy array df = pd.read_pickle(os.path.join(data_dir, "ner_data.pkl"))[:max_records] # Get feature lists entities=[list(array) for array in df["BILOU_ta...
[ "\n Reads a csv of sentences/tag sequences into a pandas dataframe.\n Converts into X = array(list(int)) & Y = array(list(int))\n Splits into training and test sets\n Builds dictionaries mapping from index labels to labels/ indexed features to features\n :param data_dir: directory to read in csv data...
Please provide a description of the function:def sym_gen(seq_len): sentence_shape = train_iter.provide_data[0][1] char_sentence_shape = train_iter.provide_data[1][1] entities_shape = train_iter.provide_label[0][1] X_sent = mx.symbol.Variable(train_iter.provide_data[0].name) X_char_sent = mx.sy...
[ "\n Build NN symbol depending on the length of the input sequence\n " ]
Please provide a description of the function:def rand_zipfian(true_classes, num_sampled, range_max): assert(isinstance(true_classes, Symbol)), "unexpected type %s" % type(true_classes) log_range = math.log(range_max + 1) rand = uniform(0, log_range, shape=(num_sampled,), dtype='float64') # make sur...
[ "Draw random samples from an approximately log-uniform or Zipfian distribution.\n\n This operation randomly samples *num_sampled* candidates the range of integers [0, range_max).\n The elements of sampled_candidates are drawn with replacement from the base distribution.\n\n The base distribution for this o...
Please provide a description of the function:def while_loop(cond, func, loop_vars, max_iterations=None, name="while_loop"): def _to_python_scalar(inputs, type_, name): if hasattr(inputs, "asscalar"): inputs = inputs.asscalar() try: inputs = type_(inputs) ...
[ "Run a while loop with user-defined computation and loop condition.\n\n This operator simulates a while loop which iterately does customized computation\n as long as the condition is satisfied.\n\n `loop_vars` is a Symbol or nested lists of Symbols on which the computation uses.\n\n `cond` is a user-def...
Please provide a description of the function:def cond(pred, then_func, else_func, name="cond"): def _create_subgraph(graph_vars, graph_func, subgraph_name): subgraph_name = _get_unique_subgraph_name(subgraph_name) with AttrScope(__subgraph_name__=subgraph_name): # create new variab...
[ "Run an if-then-else using user-defined condition and computation\n\n This operator simulates a if-like branch which chooses to do one of\n the two customized computations according to the specified condition.\n\n `pred` is a scalar MXNet Symbol,\n indicating which branch of computation should be used.\...
Please provide a description of the function:def _index_unknown_and_reserved_tokens(self, unknown_token, reserved_tokens): self._unknown_token = unknown_token # Thus, constants.UNKNOWN_IDX must be 0. self._idx_to_token = [unknown_token] if reserved_tokens is None: ...
[ "Indexes unknown and reserved tokens." ]
Please provide a description of the function:def _index_counter_keys(self, counter, unknown_token, reserved_tokens, most_freq_count, min_freq): assert isinstance(counter, collections.Counter), \ '`counter` must be an instance of collections.Counter.' un...
[ "Indexes keys of `counter`.\n\n\n Indexes keys of `counter` according to frequency thresholds such as `most_freq_count` and\n `min_freq`.\n " ]
Please provide a description of the function:def to_indices(self, tokens): to_reduce = False if not isinstance(tokens, list): tokens = [tokens] to_reduce = True indices = [self.token_to_idx[token] if token in self.token_to_idx else C.UNKNOWN_...
[ "Converts tokens to indices according to the vocabulary.\n\n\n Parameters\n ----------\n tokens : str or list of strs\n A source token or tokens to be converted.\n\n\n Returns\n -------\n int or list of ints\n A token index or a list of token indices a...
Please provide a description of the function:def to_tokens(self, indices): to_reduce = False if not isinstance(indices, list): indices = [indices] to_reduce = True max_idx = len(self.idx_to_token) - 1 tokens = [] for idx in indices: ...
[ "Converts token indices to tokens according to the vocabulary.\n\n\n Parameters\n ----------\n indices : int or list of ints\n A source token index or token indices to be converted.\n\n\n Returns\n -------\n str or list of strs\n A token or a list of t...
Please provide a description of the function:def _make_io_iterator(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)() c...
[ "Create an io iterator by handle.", "Create an iterator.\n The parameters listed below can be passed in as keyword arguments.\n\n Parameters\n ----------\n name : string, required.\n Name of the resulting data iterator.\n\n Returns\n -------\n dataiter: ...
Please provide a description of the function:def _init_io_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): hdl = ctypes.c_vo...
[ "List and add all the data iterators to current module." ]
Please provide a description of the function:def get_list(shapes, types): if types is not None: type_dict = dict(types) return [DataDesc(x[0], x[1], type_dict[x[0]]) for x in shapes] else: return [DataDesc(x[0], x[1]) for x in shapes]
[ "Get DataDesc list from attribute lists.\n\n Parameters\n ----------\n shapes : a tuple of (name_, shape_)\n types : a tuple of (name_, np.dtype)\n " ]
Please provide a description of the function:def next(self): if self.iter_next(): return DataBatch(data=self.getdata(), label=self.getlabel(), \ pad=self.getpad(), index=self.getindex()) else: raise StopIteration
[ "Get next data batch from iterator.\n\n Returns\n -------\n DataBatch\n The data of next batch.\n\n Raises\n ------\n StopIteration\n If the end of the data is reached.\n " ]
Please provide a description of the function:def hard_reset(self): if self.shuffle: self._shuffle_data() self.cursor = -self.batch_size self._cache_data = None self._cache_label = None
[ "Ignore roll over data and set to start." ]
Please provide a description of the function:def reset(self): if self.shuffle: self._shuffle_data() # the range below indicate the last batch if self.last_batch_handle == 'roll_over' and \ self.num_data - self.batch_size < self.cursor < self.num_data: ...
[ "Resets the iterator to the beginning of the data." ]
Please provide a description of the function:def iter_next(self): self.cursor += self.batch_size return self.cursor < self.num_data
[ "Increments the coursor by batch_size for next batch\n and check current cursor if it exceed the number of data points." ]
Please provide a description of the function:def next(self): if not self.iter_next(): raise StopIteration data = self.getdata() label = self.getlabel() # iter should stop when last batch is not complete if data[0].shape[0] != self.batch_size: # in thi...
[ "Returns the next batch of data." ]
Please provide a description of the function: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 if start is not None else 0 if end is None: end = data_source[0][1].shape[0] ...
[ "Load data from underlying arrays." ]
Please provide a description of the function: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: return [ concat( first_data...
[ "Helper function to concat two NDArrays." ]
Please provide a description of the function: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' and \ -self.batch_size < self.cursor < 0: ...
[ "Load data from underlying arrays, internal use only." ]
Please provide a description of the function:def getpad(self): 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...
[ "Get pad value of DataBatch." ]
Please provide a description of the function:def _shuffle_data(self): # shuffle index np.random.shuffle(self.idx) # get the data by corresponding index self.data = _getdata_by_idx(self.data, self.idx) self.label = _getdata_by_idx(self.label, self.idx)
[ "Shuffle the data." ]
Please provide a description of the function:def _quantize_params(qsym, params, th_dict): inputs_name = qsym.list_arguments() quantized_params = {} for name in inputs_name: if name.endswith(('weight_quantize', 'bias_quantize')): original_name = name[:-len('_quantize')] p...
[ "Given a quantized symbol and a dict of params that have not been quantized,\n generate quantized params. Currently only supports quantizing the arg_params\n with names of `weight` or `bias`, not aux_params. If `qsym` contains symbols\n that are excluded from being quantized, their corresponding params wil...
Please provide a description of the function:def _quantize_symbol(sym, excluded_symbols=None, offline_params=None, quantized_dtype='int8'): num_excluded_symbols = 0 if excluded_symbols is not None: assert isinstance(excluded_symbols, list) num_excluded_symbols = len(excluded_symbols) el...
[ "Given a symbol object representing a neural network of data type FP32,\n quantize it into a INT8 network.\n\n Parameters\n ----------\n sym : Symbol\n FP32 neural network symbol.\n excluded_sym_names : list of strings\n A list of strings representing the names of the symbols that users...
Please provide a description of the function: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 = [] min_vals = [] max_vals = [] for k, v in th_dict.items(): layer_output_names...
[ "Given a dictionary containing the thresholds for quantizing the layers,\n set the thresholds into the quantized symbol as the params of requantize operators.\n " ]
Please provide a description of the function:def _collect_layer_output_min_max(mod, data, include_layer=None, max_num_examples=None, logger=None): collector = _LayerOutputMinMaxCollector(include_layer=include_layer, logger=logger) num_examples = _collect_layer_statistics(m...
[ "Collect min and max values from layer outputs and save them in\n a dictionary mapped by layer names.\n " ]
Please provide a description of the function:def _collect_layer_outputs(mod, data, include_layer=None, max_num_examples=None, logger=None): collector = _LayerOutputCollector(include_layer=include_layer, logger=logger) num_examples = _collect_layer_statistics(mod, data, collector, max_num_examples, logger) ...
[ "Collect layer outputs and save them in a dictionary mapped by layer names." ]
Please provide a description of the function:def _smooth_distribution(p, eps=0.0001): is_zeros = (p == 0).astype(np.float32) is_nonzeros = (p != 0).astype(np.float32) n_zeros = is_zeros.sum() n_nonzeros = p.size - n_zeros if not n_nonzeros: raise ValueError('The discrete probability dis...
[ "Given a discrete distribution (may have not been normalized to 1),\n smooth it by replacing zeros with eps multiplied by a scaling factor and taking the\n corresponding amount off the non-zero values.\n Ref: http://web.engr.illinois.edu/~hanj/cs412/bk3/KL-divergence.pdf\n " ]
Please provide a description of the function:def _get_optimal_threshold(arr, quantized_dtype, num_bins=8001, num_quantized_bins=255): if isinstance(arr, NDArray): arr = arr.asnumpy() elif isinstance(arr, list): assert len(arr) != 0 for i, nd in enumerate(arr): if isinsta...
[ "Given a dataset, find the optimal threshold for quantizing it.\n The reference distribution is `q`, and the candidate distribution is `p`.\n `q` is a truncated version of the original distribution.\n\n Ref: http://on-demand.gputechconf.com/gtc/2017/presentation/s7310-8-bit-inference-with-tensorrt.pdf\n ...
Please provide a description of the function: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 required for running entropy mode of calculating' ' the optimal threshold...
[ "Given a ndarray dict, find the optimal threshold for quantizing each value of the key." ]
Please provide a description of the function:def _load_sym(sym, logger=logging): 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.info('Loading symbol from file %s' % symbol...
[ "Given a str as a path the symbol .json file or a symbol, returns a Symbol object." ]
Please provide a description of the function:def _load_params(params, logger=logging): if isinstance(params, str): cur_path = os.path.dirname(os.path.realpath(__file__)) param_file_path = os.path.join(cur_path, params) logger.info('Loading params from file %s' % param_file_path) ...
[ "Given a str as a path to the .params file or a pair of params,\n returns two dictionaries representing arg_params and aux_params.\n " ]
Please provide a description of the function:def quantize_model(sym, arg_params, aux_params, data_names=('data',), label_names=('softmax_label',), ctx=cpu(), excluded_sym_names=None, calib_mode='entropy', calib_data=None, num_calib_examples=None, calib_layer=None...
[ "User-level API for generating a quantized model from a FP32 model w/ or w/o calibration.\n The backend quantized operators are only enabled for Linux systems. Please do not run\n inference using the quantized models on Windows for now.\n The quantization implementation adopts the TensorFlow's approach:\n ...
Please provide a description of the function:def collect(self, name, arr): 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).copyto(cpu()) ...
[ "Callback function for collecting layer output NDArrays." ]
Please provide a description of the function:def collect(self, name, arr): 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) min_range ...
[ "Callback function for collecting min and max values from an NDArray." ]
Please provide a description of the function: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.Batch...
[]