Code
stringlengths
103
85.9k
Summary
listlengths
0
94
Please provide a description of the function:def get_symbol_train(num_classes=20, nms_thresh=0.5, force_suppress=False, nms_topk=400, **kwargs): data = mx.symbol.Variable(name="data") label = mx.symbol.Variable(name="label") # group 1 conv1_1 = mx.symbol.Convolution( d...
[ "\n Single-shot multi-box detection with VGG 16 layers ConvNet\n This is a modified version, with fc6/fc7 layers replaced by conv layers\n And the network is slightly smaller than original VGG 16 network\n This is a training network with losses\n\n Parameters:\n ----------\n num_classes: int\n ...
Please provide a description of the function:def get_symbol(num_classes=20, nms_thresh=0.5, force_suppress=False, nms_topk=400, **kwargs): net = get_symbol_train(num_classes) cls_preds = net.get_internals()["multibox_cls_pred_output"] loc_preds = net.get_internals()["multibox_loc_pred_ou...
[ "\n Single-shot multi-box detection with VGG 16 layers ConvNet\n This is a modified version, with fc6/fc7 layers replaced by conv layers\n And the network is slightly smaller than original VGG 16 network\n This is the detection network\n\n Parameters:\n ----------\n num_classes: int\n nu...
Please provide a description of the function:def load(prefix, epoch, load_optimizer_states=False, **kwargs): sym, args, auxs = load_checkpoint(prefix, epoch) mod = Module(symbol=sym, **kwargs) mod._arg_params = args mod._aux_params = auxs mod.params_initialized = True ...
[ "Creates a model from previously saved checkpoint.\n\n Parameters\n ----------\n prefix : str\n path prefix of saved model files. You should have\n \"prefix-symbol.json\", \"prefix-xxxx.params\", and\n optionally \"prefix-xxxx.states\", where xxxx is the\n ...
Please provide a description of the function:def save_checkpoint(self, prefix, epoch, save_optimizer_states=False): self._symbol.save('%s-symbol.json'%prefix) param_name = '%s-%04d.params' % (prefix, epoch) self.save_params(param_name) logging.info('Saved checkpoint to \"%s\"', ...
[ "Saves current progress to checkpoint.\n Use `mx.callback.module_checkpoint` as `epoch_end_callback` to save during training.\n\n Parameters\n ----------\n prefix : str\n The file prefix to checkpoint to.\n epoch : int\n The current epoch number.\n sav...
Please provide a description of the function:def _reset_bind(self): self.binded = False self._exec_group = None self._data_shapes = None self._label_shapes = None
[ "Internal function to reset binded state." ]
Please provide a description of the function:def get_params(self): assert self.binded and self.params_initialized if self._params_dirty: self._sync_params_from_devices() return (self._arg_params, self._aux_params)
[ "Gets current parameters.\n\n Returns\n -------\n `(arg_params, aux_params)`\n A pair of dictionaries each mapping parameter names to NDArray values.\n " ]
Please provide a description of the function:def init_params(self, initializer=Uniform(0.01), arg_params=None, aux_params=None, allow_missing=False, force_init=False, allow_extra=False): if self.params_initialized and not force_init: warnings.warn("Parameters already ini...
[ "Initializes the parameters and auxiliary states.\n\n Parameters\n ----------\n initializer : Initializer\n Called to initialize parameters if needed.\n arg_params : dict\n If not ``None``, should be a dictionary of existing arg_params. Initialization\n w...
Please provide a description of the function:def set_params(self, arg_params, aux_params, allow_missing=False, force_init=True, allow_extra=False): if not allow_missing: self.init_params(initializer=None, arg_params=arg_params, aux_params=aux_params, ...
[ "Assigns parameter and aux state values.\n\n Parameters\n ----------\n arg_params : dict\n Dictionary of name to `NDArray`.\n aux_params : dict\n Dictionary of name to `NDArray`.\n allow_missing : bool\n If ``True``, params could contain missing va...
Please provide a description of the function:def bind(self, data_shapes, label_shapes=None, for_training=True, inputs_need_grad=False, force_rebind=False, shared_module=None, grad_req='write'): # force rebinding is typically used when one want to switch from # training...
[ "Binds the symbols to construct executors. This is necessary before one\n can perform computation with the module.\n\n Parameters\n ----------\n data_shapes : list of (str, tuple)\n Typically is ``data_iter.provide_data``.\n label_shapes : list of (str, tuple)\n ...
Please provide a description of the function:def reshape(self, data_shapes, label_shapes=None): assert self.binded self._data_shapes, self._label_shapes = _parse_data_desc( self.data_names, self.label_names, data_shapes, label_shapes) self._exec_group.reshape(self._data_sha...
[ "Reshapes the module for new input shapes.\n\n Parameters\n ----------\n data_shapes : list of (str, tuple)\n Typically is ``data_iter.provide_data``.\n label_shapes : list of (str, tuple)\n Typically is ``data_iter.provide_label``.\n " ]
Please provide a description of the function:def init_optimizer(self, kvstore='local', optimizer='sgd', optimizer_params=(('learning_rate', 0.01),), force_init=False): assert self.binded and self.params_initialized if self.optimizer_initialized and not force_init: ...
[ "Installs and initializes optimizers.\n\n Parameters\n ----------\n kvstore : str or KVStore\n Default `'local'`.\n optimizer : str or Optimizer\n Default `'sgd'`\n optimizer_params : dict\n Default `(('learning_rate', 0.01),)`. The default value i...
Please provide a description of the function:def borrow_optimizer(self, shared_module): assert shared_module.optimizer_initialized self._optimizer = shared_module._optimizer self._kvstore = shared_module._kvstore self._update_on_kvstore = shared_module._update_on_kvstore ...
[ "Borrows optimizer from a shared module. Used in bucketing, where exactly the same\n optimizer (esp. kvstore) is used.\n\n Parameters\n ----------\n shared_module : Module\n " ]
Please provide a description of the function:def forward(self, data_batch, is_train=None): assert self.binded and self.params_initialized curr_data_shapes = tuple(i.shape for i in self._data_shapes) if isinstance(data_batch, list): assert data_batch is not None, "Encountere...
[ "Forward computation. It supports data batches with different shapes, such as\n different batch sizes or different image sizes.\n If reshaping of data batch relates to modification of symbol or module, such as\n changing image layout ordering or switching from training to predicting, module\n ...
Please provide a description of the function:def backward(self, out_grads=None): assert self.binded and self.params_initialized self._exec_group.backward(out_grads=out_grads)
[ "Backward computation.\n\n See Also\n ----------\n :meth:`BaseModule.backward`.\n\n Parameters\n ----------\n out_grads : NDArray or list of NDArray, optional\n Gradient on the outputs to be propagated back.\n This parameter is only needed when bind is...
Please provide a description of the function:def update(self): assert self.binded and self.params_initialized and self.optimizer_initialized self._params_dirty = True if self._update_on_kvstore: _update_params_on_kvstore(self._exec_group.param_arrays, ...
[ "Updates parameters according to the installed optimizer and the gradients computed\n in the previous forward-backward batch.\n\n When KVStore is used to update parameters for multi-device or multi-machine training,\n a copy of the parameters are stored in KVStore. Note that for `row_sparse` pa...
Please provide a description of the function:def get_outputs(self, merge_multi_context=True): assert self.binded and self.params_initialized return self._exec_group.get_outputs(merge_multi_context=merge_multi_context)
[ "Gets outputs of the previous forward computation.\n\n If ``merge_multi_context`` is ``True``, it is like ``[out1, out2]``. Otherwise, it\n is like ``[[out1_dev1, out1_dev2], [out2_dev1, out2_dev2]]``. All the output\n elements are `NDArray`. When `merge_multi_context` is `False`, those `NDArra...
Please provide a description of the function:def get_input_grads(self, merge_multi_context=True): assert self.binded and self.params_initialized and self.inputs_need_grad return self._exec_group.get_input_grads(merge_multi_context=merge_multi_context)
[ "Gets the gradients with respect to the inputs of the module.\n\n If ``merge_multi_context`` is ``True``, it is like ``[grad1, grad2]``. Otherwise, it\n is like ``[[grad1_dev1, grad1_dev2], [grad2_dev1, grad2_dev2]]``. All the output\n elements are `NDArray`.\n\n Parameters\n ----...
Please provide a description of the function:def get_states(self, merge_multi_context=True): assert self.binded and self.params_initialized return self._exec_group.get_states(merge_multi_context=merge_multi_context)
[ "Gets states from all devices.\n\n If `merge_multi_context` is ``True``, it is like ``[out1, out2]``. Otherwise, it\n is like ``[[out1_dev1, out1_dev2], [out2_dev1, out2_dev2]]``. All the output\n elements are `NDArray`.\n\n Parameters\n ----------\n merge_multi_context : b...
Please provide a description of the function:def update_metric(self, eval_metric, labels, pre_sliced=False): self._exec_group.update_metric(eval_metric, labels, pre_sliced)
[ "Evaluates and accumulates evaluation metric on outputs of the last forward computation.\n\n See Also\n ----------\n :meth:`BaseModule.update_metric`.\n\n Parameters\n ----------\n eval_metric : EvalMetric\n Evaluation metric to use.\n labels : list of NDA...
Please provide a description of the function:def _sync_params_from_devices(self): self._exec_group.get_params(self._arg_params, self._aux_params) if self._kvstore and self._update_on_kvstore: for param_name, param_val in sorted(self._arg_params.items()): if param_val...
[ "Synchronizes parameters from devices to CPU. This function should be called after\n calling `update` that updates the parameters on the devices, before one can read the\n latest parameters from ``self._arg_params`` and ``self._aux_params``.\n\n For row_sparse parameters on devices, ther are pu...
Please provide a description of the function:def save_optimizer_states(self, fname): assert self.optimizer_initialized if self._update_on_kvstore: self._kvstore.save_optimizer_states(fname) else: with open(fname, 'wb') as fout: fout.write(self._u...
[ "Saves optimizer (updater) state to a file.\n\n Parameters\n ----------\n fname : str\n Path to output states file.\n " ]
Please provide a description of the function:def load_optimizer_states(self, fname): assert self.optimizer_initialized if self._update_on_kvstore: self._kvstore.load_optimizer_states(fname) else: self._updater.set_states(open(fname, 'rb').read())
[ "Loads optimizer (updater) state from a file.\n\n Parameters\n ----------\n fname : str\n Path to input states file.\n " ]
Please provide a description of the function:def prepare(self, data_batch, sparse_row_id_fn=None): '''Prepares the module for processing a data batch. Usually involves switching bucket and reshaping. For modules that contain `row_sparse` parameters in KVStore, it prepares the `row_spars...
[]
Please provide a description of the function:def _random_helper(random, sampler, params, shape, dtype, ctx, out, kwargs): if isinstance(params[0], NDArray): for i in params[1:]: assert isinstance(i, NDArray), \ "Distribution parameters must all have the same type, but got " ...
[ "Helper function for random generators." ]
Please provide a description of the function:def uniform(low=0, high=1, shape=_Null, dtype=_Null, ctx=None, out=None, **kwargs): return _random_helper(_internal._random_uniform, _internal._sample_uniform, [low, high], shape, dtype, ctx, out, kwargs)
[ "Draw random samples from a uniform distribution.\n\n Samples are uniformly distributed over the half-open interval *[low, high)*\n (includes *low*, but excludes *high*).\n\n Parameters\n ----------\n low : float or NDArray, optional\n Lower boundary of the output interval. All values generate...
Please provide a description of the function:def normal(loc=0, scale=1, shape=_Null, dtype=_Null, ctx=None, out=None, **kwargs): return _random_helper(_internal._random_normal, _internal._sample_normal, [loc, scale], shape, dtype, ctx, out, kwargs)
[ "Draw random samples from a normal (Gaussian) distribution.\n\n Samples are distributed according to a normal distribution parametrized\n by *loc* (mean) and *scale* (standard deviation).\n\n\n Parameters\n ----------\n loc : float or NDArray, optional\n Mean (centre) of the distribution.\n ...
Please provide a description of the function:def randn(*shape, **kwargs): loc = kwargs.pop('loc', 0) scale = kwargs.pop('scale', 1) dtype = kwargs.pop('dtype', _Null) ctx = kwargs.pop('ctx', None) out = kwargs.pop('out', None) assert isinstance(loc, (int, float)) assert isinstance(scale...
[ "Draw random samples from a normal (Gaussian) distribution.\n\n Samples are distributed according to a normal distribution parametrized\n by *loc* (mean) and *scale* (standard deviation).\n\n\n Parameters\n ----------\n loc : float or NDArray\n Mean (centre) of the distribution.\n scale : f...
Please provide a description of the function:def exponential(scale=1, shape=_Null, dtype=_Null, ctx=None, out=None, **kwargs): r return _random_helper(_internal._random_exponential, _internal._sample_exponential, [1.0/scale], shape, dtype, ctx, out, kwargs)
[ "Draw samples from an exponential distribution.\n\n Its probability density function is\n\n .. math:: f(x; \\frac{1}{\\beta}) = \\frac{1}{\\beta} \\exp(-\\frac{x}{\\beta}),\n\n for x > 0 and 0 elsewhere. \\beta is the scale parameter, which is the\n inverse of the rate parameter \\lambda = 1/\\beta.\n\n...
Please provide a description of the function:def gamma(alpha=1, beta=1, shape=_Null, dtype=_Null, ctx=None, out=None, **kwargs): return _random_helper(_internal._random_gamma, _internal._sample_gamma, [alpha, beta], shape, dtype, ctx, out, kwargs)
[ "Draw random samples from a gamma distribution.\n\n Samples are distributed according to a gamma distribution parametrized\n by *alpha* (shape) and *beta* (scale).\n\n Parameters\n ----------\n alpha : float or NDArray, optional\n The shape of the gamma distribution. Should be greater than zer...
Please provide a description of the function:def negative_binomial(k=1, p=1, shape=_Null, dtype=_Null, ctx=None, out=None, **kwargs): return _random_helper(_internal._random_negative_binomial, _internal._sample_negative_binomial, [k, p],...
[ "Draw random samples from a negative binomial distribution.\n\n Samples are distributed according to a negative binomial distribution\n parametrized by *k* (limit of unsuccessful experiments) and *p* (failure\n probability in each experiment). Samples will always be returned as a\n floating point data t...
Please provide a description of the function:def multinomial(data, shape=_Null, get_prob=False, out=None, dtype='int32', **kwargs): return _internal._sample_multinomial(data, shape, get_prob, out=out, dtype=dtype, **kwargs)
[ "Concurrent sampling from multiple multinomial distributions.\n\n .. note:: The input distribution must be normalized, i.e. `data` must sum to\n 1 along its last dimension.\n\n Parameters\n ----------\n data : NDArray\n An *n* dimensional array whose last dimension has length `k`, wh...
Please provide a description of the function:def randint(low, high, shape=_Null, dtype=_Null, ctx=None, out=None, **kwargs): return _random_helper(_internal._random_randint, None, [low, high], shape, dtype, ctx, out, kwargs)
[ "Draw random samples from a discrete uniform distribution.\n\n Samples are uniformly distributed over the half-open interval *[low, high)*\n (includes *low*, but excludes *high*).\n\n Parameters\n ----------\n low : int, required\n Lower boundary of the output interval. All values generated wi...
Please provide a description of the function:def preprocess_uci_adult(data_name): csv_columns = [ "age", "workclass", "fnlwgt", "education", "education_num", "marital_status", "occupation", "relationship", "race", "gender", "capital_gain", "capital_loss", "hours_per_week", "native_count...
[ "Some tricks of feature engineering are adapted\n from tensorflow's wide and deep tutorial.\n " ]
Please provide a description of the function:def _init_params(self): assert self._kv_initialized, "Cannot initialize parameters in KVStore " \ "when KVStore is not initialized." params_to_init = [] if self._kvstore: for param in self._par...
[ "Initialize parameters in the KVStore.\n\n Parameters with incomplete initialization are ignored.\n\n " ]
Please provide a description of the function:def _reset_kvstore(self): if self._kvstore and 'dist' in self._kvstore.type: raise RuntimeError("Cannot reset distributed KVStore.") self._kv_initialized = False self._kvstore = None self._distributed = None self._...
[ "Reset kvstore." ]
Please provide a description of the function:def _init_kvstore(self): config = self._kvstore_params # configure kvstore, update_on_kvstore and self._distributed on three cases: if self._contains_sparse_weight: # If weight is sparse, kvstore must be present and the weight mus...
[ "Create kvstore." ]
Please provide a description of the function:def set_learning_rate(self, lr): if not isinstance(self._optimizer, opt.Optimizer): raise UserWarning("Optimizer has to be defined before its learning " "rate is mutated.") else: self._optimizer.s...
[ "Sets a new learning rate of the optimizer.\n\n Parameters\n ----------\n lr : float\n The new learning rate of the optimizer.\n " ]
Please provide a description of the function:def _row_sparse_pull(self, parameter, out, row_id, full_idx=False): # initialize kv and params if not already if not self._kv_initialized: self._init_kvstore() if self._params_to_init: self._init_params() idx =...
[ "Internal method to invoke pull operations on KVStore. If `full_idx` is set to True,\n `kv.pull` is preferred instead of `kv.row_sparse_pull`.\n " ]
Please provide a description of the function:def step(self, batch_size, ignore_stale_grad=False): rescale_grad = self._scale / batch_size self._check_and_rescale_grad(rescale_grad) if not self._kv_initialized: self._init_kvstore() if self._params_to_init: ...
[ "Makes one step of parameter update. Should be called after\n `autograd.backward()` and outside of `record()` scope.\n\n For normal parameter updates, `step()` should be used, which internally calls\n `allreduce_grads()` and then `update()`. However, if you need to get the reduced\n grad...
Please provide a description of the function:def allreduce_grads(self): if not self._kv_initialized: self._init_kvstore() if self._params_to_init: self._init_params() assert not (self._kvstore and self._update_on_kvstore), \ 'allreduce_grads() whe...
[ "For each parameter, reduce the gradients from different contexts.\n\n Should be called after `autograd.backward()`, outside of `record()` scope,\n and before `trainer.update()`.\n\n For normal parameter updates, `step()` should be used, which internally calls\n `allreduce_grads()` and t...
Please provide a description of the function:def update(self, batch_size, ignore_stale_grad=False): if not self._kv_initialized: self._init_kvstore() if self._params_to_init: self._init_params() assert not (self._kvstore and self._update_on_kvstore), \ ...
[ "Makes one step of parameter update.\n\n Should be called after `autograd.backward()` and outside of `record()` scope,\n and after `trainer.update()`.\n\n\n For normal parameter updates, `step()` should be used, which internally calls\n `allreduce_grads()` and then `update()`. However, i...
Please provide a description of the function:def save_states(self, fname): assert self._optimizer is not None if not self._kv_initialized: self._init_kvstore() if self._params_to_init: self._init_params() if self._update_on_kvstore: assert n...
[ "Saves trainer states (e.g. optimizer, momentum) to a file.\n\n\n Parameters\n ----------\n fname : str\n Path to output states file.\n\n Note\n ----\n `optimizer.param_dict`, which contains Parameter information (such as\n `lr_mult` and `wd_mult`) will no...
Please provide a description of the function:def load_states(self, fname): if not self._kv_initialized: self._init_kvstore() if self._params_to_init: self._init_params() if self._update_on_kvstore: self._kvstore.load_optimizer_states(fname) ...
[ "Loads trainer states (e.g. optimizer, momentum) from a file.\n\n Parameters\n ----------\n fname : str\n Path to input states file.\n\n Note\n ----\n `optimizer.param_dict`, which contains Parameter information (such as\n `lr_mult` and `wd_mult`) will not...
Please provide a description of the function:def estimate_density(DATA_PATH, feature_size): if not os.path.exists(DATA_PATH): raise Exception("Data is not there!") density = [] P = 0.01 for _ in range(10): num_non_zero = 0 num_sample = 0 with open(DATA_PATH) as f: ...
[ "sample 10 times of a size of 1000 for estimating the density of the sparse dataset" ]
Please provide a description of the function:def exec_cmd(cmd, role, taskid, pass_env): if cmd[0].find('/') == -1 and os.path.exists(cmd[0]) and os.name != 'nt': cmd[0] = './' + cmd[0] cmd = ' '.join(cmd) env = os.environ.copy() for k, v in pass_env.items(): env[k] = str(v) env...
[ "Execute the command line command." ]
Please provide a description of the function:def submit(args): gpus = args.gpus.strip().split(',') def mthread_submit(nworker, nserver, envs): procs = {} for i, gpu in enumerate(gpus): for j in range(args.num_threads): procs[i] = Thread(target=exec_cmd, ...
[ "Submit function of local jobs.", "\n customized submit script, that submit nslave jobs, each must contain args as parameter\n note this can be a lambda function containing additional parameters in input\n\n Parameters\n ----------\n nworker: number of slave process to start up\...
Please provide a description of the function:def ctc_label(p): ret = [] p1 = [0] + p for i, _ in enumerate(p): c1 = p1[i] c2 = p1[i+1] if c2 in (0, c1): continue ret.append(c2) return ret
[ "Iterates through p, identifying non-zero and non-repeating values, and returns them in a list Parameters\n ----------\n p: list of int\n\n Returns\n -------\n list of int\n " ]
Please provide a description of the function:def _remove_blank(l): ret = [] for i, _ in enumerate(l): if l[i] == 0: break ret.append(l[i]) return ret
[ " Removes trailing zeros in the list of integers and returns a new list of integers" ]
Please provide a description of the function:def _lcs(p, l): # Dynamic Programming Finding LCS if len(p) == 0: return 0 P = np.array(list(p)).reshape((1, len(p))) L = np.array(list(l)).reshape((len(l), 1)) M = np.ndarray(shape=(len(P), len(L)), dtype=np.int32...
[ " Calculates the Longest Common Subsequence between p and l (both list of int) and returns its length" ]
Please provide a description of the function:def accuracy(self, label, pred): hit = 0. total = 0. batch_size = label.shape[0] for i in range(batch_size): l = self._remove_blank(label[i]) p = [] for k in range(self.seq_len): p.a...
[ " Simple accuracy measure: number of 100% accurate predictions divided by total number " ]
Please provide a description of the function:def accuracy_lcs(self, label, pred): hit = 0. total = 0. batch_size = label.shape[0] for i in range(batch_size): l = self._remove_blank(label[i]) p = [] for k in range(self.seq_len): ...
[ " Longest Common Subsequence accuracy measure: calculate accuracy of each prediction as LCS/length" ]
Please provide a description of the function:def get_movielens_iter(filename, batch_size): logging.info("Preparing data iterators for " + filename + " ... ") user = [] item = [] score = [] with open(filename, 'r') as f: num_samples = 0 for line in f: tks = line.strip...
[ "Not particularly fast code to parse the text file and load into NDArrays.\n return two data iters, one for train, the other for validation.\n " ]
Please provide a description of the function:def imdecode(str_img, flag=1): hdl = NDArrayHandle() check_call(_LIB.MXCVImdecode(ctypes.c_char_p(str_img), mx_uint(len(str_img)), flag, ctypes.byref(hdl))) return mx.nd.NDArray(hdl)
[ "Decode image from str buffer.\n Wrapper for cv2.imdecode that uses mx.nd.NDArray\n\n Parameters\n ----------\n str_img : str\n str buffer read from image file\n flag : int\n same as flag for cv2.imdecode\n Returns\n -------\n img : NDArray\n decoded image in (width, hei...
Please provide a description of the function:def resize(src, size, interpolation=cv2.INTER_LINEAR): hdl = NDArrayHandle() check_call(_LIB.MXCVResize(src.handle, mx_uint(size[0]), mx_uint(size[1]), interpolation, ctypes.byref(hdl))) return mx.nd.NDArray(hdl)
[ "Decode image from str buffer.\n Wrapper for cv2.imresize that uses mx.nd.NDArray\n\n Parameters\n ----------\n src : NDArray\n image in (width, height, channels)\n size : tuple\n target size in (width, height)\n interpolation : int\n same as interpolation for cv2.imresize\n\n...
Please provide a description of the function:def copyMakeBorder(src, top, bot, left, right, border_type=cv2.BORDER_CONSTANT, value=0): hdl = NDArrayHandle() check_call(_LIB.MXCVcopyMakeBorder(src.handle, ctypes.c_int(top), ctypes.c_int(bot), ctypes.c_int(left), ctypes...
[ "Pad image border\n Wrapper for cv2.copyMakeBorder that uses mx.nd.NDArray\n\n Parameters\n ----------\n src : NDArray\n Image in (width, height, channels).\n Others are the same with cv2.copyMakeBorder\n\n Returns\n -------\n img : NDArray\n padded image\n " ]
Please provide a description of the function:def fixed_crop(src, x0, y0, w, h, size=None, interpolation=cv2.INTER_CUBIC): out = mx.nd.crop(src, begin=(y0, x0, 0), end=(y0+h, x0+w, int(src.shape[2]))) if size is not None and (w, h) != size: out = resize(out, size, interpolation=interpolation) re...
[ "Crop src at fixed location, and (optionally) resize it to size" ]
Please provide a description of the function:def random_crop(src, size): h, w, _ = src.shape new_w, new_h = scale_down((w, h), size) x0 = random.randint(0, w - new_w) y0 = random.randint(0, h - new_h) out = fixed_crop(src, x0, y0, new_w, new_h, size) return out, (x0, y0, new_w, new_h)
[ "Randomly crop src with size. Upsample result if src is smaller than size" ]
Please provide a description of the function:def random_size_crop(src, size, min_area=0.25, ratio=(3.0/4.0, 4.0/3.0)): h, w, _ = src.shape area = w*h for _ in range(10): new_area = random.uniform(min_area, 1.0) * area new_ratio = random.uniform(*ratio) new_w = int(new_area*new_r...
[ "Randomly crop src with size. Randomize area and aspect ratio" ]
Please provide a description of the function:def next(self): batch = mx.nd.zeros((self.batch_size, self.size[1], self.size[0], 3)) i = self.cur for i in range(self.cur, min(len(self.list), self.cur+self.batch_size)): str_img = open(self.root+self.list[i]+'.jpg').read() ...
[ "Move iterator position forward" ]
Please provide a description of the function:def check_label_shapes(labels, preds, shape=0): if shape == 0: label_shape, pred_shape = len(labels), len(preds) else: label_shape, pred_shape = labels.shape, preds.shape if label_shape != pred_shape: raise ValueError("Shape of labe...
[ "Check to see if the two arrays are the same size." ]
Please provide a description of the function:def import_to_gluon(model_file, ctx): graph = GraphProto() try: import onnx except ImportError: raise ImportError("Onnx and protobuf need to be installed. Instructions to" + " install - https://github.com/onnx/onnx#i...
[ "\n Imports the ONNX model files, passed as a parameter, into Gluon SymbolBlock object.\n\n Parameters\n ----------\n model_file : str\n ONNX model file name\n ctx : Context or list of Context\n Loads the model into one or many context(s).\n\n Returns\n -------\n sym_block : :c...
Please provide a description of the function:def get_model(model, ctx, opt): kwargs = {'ctx': ctx, 'pretrained': opt.use_pretrained, 'classes': classes} if model.startswith('resnet'): kwargs['thumbnail'] = opt.use_thumbnail elif model.startswith('vgg'): kwargs['batch_norm'] = opt.batch_...
[ "Model initialization." ]
Please provide a description of the function:def get_data_iters(dataset, batch_size, opt): if dataset == 'mnist': train_data, val_data = get_mnist_iterator(batch_size, (1, 28, 28), num_parts=kv.num_workers, part_index=kv.rank) elif dataset == 'cifar...
[ "get dataset iterators" ]
Please provide a description of the function:def update_learning_rate(lr, trainer, epoch, ratio, steps): new_lr = lr * (ratio ** int(np.sum(np.array(steps) < epoch))) trainer.set_learning_rate(new_lr) return trainer
[ "Set the learning rate to the initial value decayed by ratio every N epochs." ]
Please provide a description of the function:def seed(seed_state, ctx="all"): if not isinstance(seed_state, integer_types): raise ValueError('seed_state must be int') seed_state = ctypes.c_int(int(seed_state)) if ctx == "all": check_call(_LIB.MXRandomSeed(seed_state)) else: ...
[ "Seeds the random number generators in MXNet.\n\n This affects the behavior of modules in MXNet that uses random number generators,\n like the dropout operator and `NDArray`'s random sampling operators.\n\n Parameters\n ----------\n seed_state : int\n The random number seed.\n\n ctx : Conte...
Please provide a description of the function:def random_uniform(attrs, inputs, proto_obj): try: from onnx.mapping import TENSOR_TYPE_TO_NP_TYPE except ImportError: raise ImportError("Onnx and protobuf need to be installed. " "Instructions to install - https://githu...
[ "Draw random samples from a uniform distribtuion." ]
Please provide a description of the function:def random_normal(attrs, inputs, proto_obj): try: from onnx.mapping import TENSOR_TYPE_TO_NP_TYPE except ImportError: raise ImportError("Onnx and protobuf need to be installed. " "Instructions to install - https://github...
[ "Draw random samples from a Gaussian distribution." ]
Please provide a description of the function:def add(attrs, inputs, proto_obj): new_attr = {} if 'broadcast' in attrs and attrs['broadcast'] == 1: broadcast_axis = attrs['axis'] op_value = translation_utils._fix_broadcast('broadcast_add', inputs, ...
[ "Adding two tensors" ]
Please provide a description of the function:def mean(attrs, inputs, proto_obj): concat_input = [symbol.expand_dims(op_input, axis=0) for op_input in inputs] concat_sym = symbol.concat(*concat_input, dim=0) mean_sym = symbol.mean(concat_sym, axis=0) return mean_sym, attrs, inputs
[ "Mean of all the input tensors." ]
Please provide a description of the function:def argmax(attrs, inputs, proto_obj): axis = attrs.get('axis', 0) keepdims = attrs.get('keepdims', 1) argmax_op = symbol.argmax(inputs[0], axis=axis, keepdims=keepdims) # onnx argmax operator always expects int64 as output type cast_attrs = {'dtype':...
[ "Returns indices of the maximum values along an axis" ]
Please provide a description of the function:def argmin(attrs, inputs, proto_obj): axis = attrs.get('axis', 0) keepdims = attrs.get('keepdims', 1) argmin_op = symbol.argmin(inputs[0], axis=axis, keepdims=keepdims) # onnx argmax operator always expects int64 as output type cast_attrs = {'dtype':...
[ "Returns indices of the minimum values along an axis." ]
Please provide a description of the function:def maximum(attrs, inputs, proto_obj): if len(inputs) > 1: mxnet_op = symbol.maximum(inputs[0], inputs[1]) for op_input in inputs[2:]: mxnet_op = symbol.maximum(mxnet_op, op_input) else: mxnet_op = symbol.maximum(inputs[0], in...
[ "\n Elementwise maximum of arrays.\n MXNet maximum compares only two symbols at a time.\n ONNX can send more than two to compare.\n Breaking into multiple mxnet ops to compare two symbols at a time\n " ]
Please provide a description of the function:def minimum(attrs, inputs, proto_obj): # MXNet minimum compares only two symbols at a time. # ONNX can send more than two to compare. # Breaking into multiple mxnet ops to compare two symbols at a time if len(inputs) > 1: mxnet_op = symbol.minimu...
[ "Elementwise minimum of arrays." ]
Please provide a description of the function:def concat(attrs, inputs, proto_obj): new_attrs = translation_utils._fix_attribute_names(attrs, {'axis': 'dim'}) return 'concat', new_attrs, inputs
[ " Joins input arrays along a given axis. " ]
Please provide a description of the function:def pad(attrs, inputs, proto_obj): new_attrs = translation_utils._fix_attribute_names(attrs, {'pads' : 'pad_width', 'value' : 'constant_value' ...
[ " Add padding to input tensor" ]
Please provide a description of the function:def batch_norm(attrs, inputs, proto_obj): new_attrs = translation_utils._fix_attribute_names(attrs, {'epsilon': 'eps', 'is_test': 'fix_gamma'}) new_attrs = translation_utils._remove_attributes(new_at...
[ "Batch normalization." ]
Please provide a description of the function:def instance_norm(attrs, inputs, proto_obj): new_attrs = translation_utils._fix_attribute_names(attrs, {'epsilon' : 'eps'}) new_attrs['eps'] = attrs.get('epsilon', 1e-5) return 'InstanceNorm', new_attrs, inputs
[ "Instance Normalization." ]
Please provide a description of the function:def leaky_relu(attrs, inputs, proto_obj): if 'alpha' in attrs: new_attrs = translation_utils._fix_attribute_names(attrs, {'alpha' : 'slope'}) else: new_attrs = translation_utils._add_extra_attributes(attrs, {'slope': 0.01}) return 'LeakyReLU'...
[ "Leaky Relu function" ]
Please provide a description of the function:def _elu(attrs, inputs, proto_obj): if 'alpha' in attrs: new_attrs = translation_utils._fix_attribute_names(attrs, {'alpha' : 'slope'}) else: new_attrs = translation_utils._add_extra_attributes(attrs, {'slope': 1.0}) new_attrs = translation_u...
[ "Elu function" ]
Please provide a description of the function:def _prelu(attrs, inputs, proto_obj): new_attrs = translation_utils._add_extra_attributes(attrs, {'act_type': 'prelu'}) return 'LeakyReLU', new_attrs, inputs
[ "PRelu function" ]
Please provide a description of the function:def _selu(attrs, inputs, proto_obj): new_attrs = translation_utils._add_extra_attributes(attrs, {'act_type': 'selu'}) return 'LeakyReLU', new_attrs, inputs
[ "Selu function" ]
Please provide a description of the function:def softmax(attrs, inputs, proto_obj): if 'axis' not in attrs: attrs = translation_utils._add_extra_attributes(attrs, {'axis': 1}) return 'softmax', attrs, inputs
[ "Softmax function." ]
Please provide a description of the function:def softplus(attrs, inputs, proto_obj): new_attrs = translation_utils._add_extra_attributes(attrs, {'act_type' : 'softrelu'}) return 'Activation', new_attrs, inputs
[ "Applies the sofplus activation function element-wise to the input." ]
Please provide a description of the function:def conv(attrs, inputs, proto_obj): new_attrs = translation_utils._fix_attribute_names(attrs, {'kernel_shape' : 'kernel', 'strides' : 'stride', ...
[ "Compute N-D convolution on (N+2)-D input." ]
Please provide a description of the function:def deconv(attrs, inputs, proto_obj): new_attrs = translation_utils._fix_attribute_names(attrs, {'kernel_shape' : 'kernel', 'strides' : 'stride', ...
[ "Computes transposed convolution of the input tensor." ]
Please provide a description of the function:def fully_connected(attrs, inputs, proto_obj): new_attrs = translation_utils._remove_attributes(attrs, ['axis']) new_attrs = translation_utils._fix_bias('FullyConnected', new_attrs, len(inputs)) new_attrs = translation_utils._fix_channels('FullyConnected',...
[ "Applies a linear transformation: Y=XWT+b." ]
Please provide a description of the function:def global_maxpooling(attrs, inputs, proto_obj): new_attrs = translation_utils._add_extra_attributes(attrs, {'global_pool': True, 'kernel': (1, 1), ...
[ "Performs max pooling on the input." ]
Please provide a description of the function:def global_avgpooling(attrs, inputs, proto_obj): new_attrs = translation_utils._add_extra_attributes(attrs, {'global_pool': True, 'kernel': (1, 1), ...
[ "Performs avg pooling on the input." ]
Please provide a description of the function:def global_lppooling(attrs, inputs, proto_obj): p_value = attrs.get('p', 2) new_attrs = translation_utils._add_extra_attributes(attrs, {'global_pool': True, 'kernel': (1, 1), ...
[ "Performs global lp pooling on the input." ]
Please provide a description of the function:def linalg_gemm(attrs, inputs, proto_obj): trans_a = 0 trans_b = 0 alpha = 1 beta = 1 if 'transA' in attrs: trans_a = attrs['transA'] if 'transB' in attrs: trans_b = attrs['transB'] if 'alpha' in attrs: alpha = attrs['...
[ "Performs general matrix multiplication and accumulation" ]
Please provide a description of the function:def local_response_norm(attrs, inputs, proto_obj): new_attrs = translation_utils._fix_attribute_names(attrs, {'bias': 'knorm', 'size' : 'nsize'}) retur...
[ "Local Response Normalization." ]
Please provide a description of the function:def dropout(attrs, inputs, proto_obj): mode = 'training' if 'is_test' in attrs and attrs['is_test'] == 0: mode = 'always' new_attrs = translation_utils._fix_attribute_names(attrs, {'ratio': 'p'})...
[ "Dropout Regularization." ]
Please provide a description of the function:def reshape(attrs, inputs, proto_obj): if len(inputs) == 1: return 'reshape', attrs, inputs[0] reshape_shape = list(proto_obj._params[inputs[1].name].asnumpy()) reshape_shape = [int(i) for i in reshape_shape] new_attrs = {'shape': reshape_shape} ...
[ "Reshape the given array by the shape attribute." ]
Please provide a description of the function:def cast(attrs, inputs, proto_obj): try: from onnx.mapping import TENSOR_TYPE_TO_NP_TYPE except ImportError: raise ImportError("Onnx and protobuf need to be installed. " + "Instructions to install - https://github.com/on...
[ " Cast input to a given dtype" ]
Please provide a description of the function:def split(attrs, inputs, proto_obj): split_list = attrs.get('split') if 'split' in attrs else [] new_attrs = translation_utils._fix_attribute_names(attrs, {'split' : 'num_outputs'}) if 'axis' not in attr...
[ "Splits an array along a particular axis into multiple sub-arrays." ]
Please provide a description of the function:def _slice(attrs, inputs, proto_obj): new_attrs = translation_utils._fix_attribute_names(attrs, {'axes' : 'axis', 'ends' : 'end', ...
[ "Returns a slice of the input tensor along multiple axes." ]
Please provide a description of the function:def transpose(attrs, inputs, proto_obj): new_attrs = translation_utils._fix_attribute_names(attrs, {'perm' : 'axes'}) return 'transpose', new_attrs, inputs
[ "Transpose the input array." ]
Please provide a description of the function:def squeeze(attrs, inputs, proto_obj): new_attrs = translation_utils._fix_attribute_names(attrs, {'axes' : 'axis'}) return 'squeeze', new_attrs, inputs
[ "Remove single-dimensional entries from the shape of a tensor." ]
Please provide a description of the function:def unsqueeze(attrs, inputs, cls): # MXNet can only add one axis at a time. mxnet_op = inputs[0] for axis in attrs["axes"]: mxnet_op = symbol.expand_dims(mxnet_op, axis=axis) return mxnet_op, attrs, inputs
[ "Inserts a new axis of size 1 into the array shape" ]
Please provide a description of the function:def flatten(attrs, inputs, proto_obj): #Mxnet does not have axis support. By default uses axis=1 if 'axis' in attrs and attrs['axis'] != 1: raise RuntimeError("Flatten operator only supports axis=1") new_attrs = translation_utils._remove_attributes(a...
[ "Flattens the input array into a 2-D array by collapsing the higher dimensions." ]