Code
stringlengths
103
85.9k
Summary
listlengths
0
94
Please provide a description of the function:def setting_ctx(num_gpus): if num_gpus > 0: ctx = [mx.gpu(i) for i in range(num_gpus)] else: ctx = [mx.cpu()] return ctx
[ "\n Description : set gpu module\n " ]
Please provide a description of the function:def char_beam_search(out): out_conv = list() for idx in range(out.shape[0]): probs = out[idx] prob = probs.softmax().asnumpy() line_string_proposals = ctcBeamSearch(prob, ALPHABET, None, k=4, beamWidth=25) out_conv.append(line_str...
[ "\n Description : apply beam search for prediction result\n " ]
Please provide a description of the function:def build_model(self, dr_rate=0, path=None): #set network self.net = LipNet(dr_rate) self.net.hybridize() self.net.initialize(ctx=self.ctx) if path is not None: self.load_model(path) #set optimizer ...
[ "\n Description : build network\n " ]
Please provide a description of the function:def save_model(self, epoch, loss): prefix = 'checkpoint/epoches' file_name = "{prefix}_{epoch}_loss_{l:.4f}".format(prefix=prefix, epoch=str(epoch), ...
[ "\n Description : save parameter of network weight\n " ]
Please provide a description of the function:def load_dataloader(self): input_transform = transforms.Compose([transforms.ToTensor(), \ transforms.Normalize((0.7136, 0.4906, 0.3283), \ (0.1138...
[ "\n Description : Setup the dataloader\n " ]
Please provide a description of the function:def train(self, data, label, batch_size): # pylint: disable=no-member sum_losses = 0 len_losses = 0 with autograd.record(): losses = [self.loss_fn(self.net(X), Y) for X, Y in zip(data, label)] for loss in losses: ...
[ "\n Description : training for LipNet\n " ]
Please provide a description of the function:def infer(self, input_data, input_label): sum_losses = 0 len_losses = 0 for data, label in zip(input_data, input_label): pred = self.net(data) sum_losses += mx.nd.array(self.loss_fn(pred, label)).sum().asscalar() ...
[ "\n Description : Print sentence for prediction result\n " ]
Please provide a description of the function:def train_batch(self, dataloader): sum_losses = 0 len_losses = 0 for input_data, input_label in tqdm(dataloader): data = gluon.utils.split_and_load(input_data, self.ctx, even_split=False) label = gluon.utils.split_and_...
[ "\n Description : training for LipNet\n " ]
Please provide a description of the function:def infer_batch(self, dataloader): sum_losses = 0 len_losses = 0 for input_data, input_label in dataloader: data = gluon.utils.split_and_load(input_data, self.ctx, even_split=False) label = gluon.utils.split_and_load(i...
[ "\n Description : inference for LipNet\n " ]
Please provide a description of the function:def run(self, epochs): best_loss = sys.maxsize for epoch in trange(epochs): iter_no = 0 ## train sum_losses, len_losses = self.train_batch(self.train_dataloader) if iter_no % 20 == 0: ...
[ "\n Description : Run training for LipNet\n " ]
Please provide a description of the function:def sample_categorical(prob, rng): ret = numpy.empty(prob.shape[0], dtype=numpy.float32) for ind in range(prob.shape[0]): ret[ind] = numpy.searchsorted(numpy.cumsum(prob[ind]), rng.rand()).clip(min=0.0, ...
[ "Sample from independent categorical distributions\n\n Each batch is an independent categorical distribution.\n\n Parameters\n ----------\n prob : numpy.ndarray\n Probability of the categorical distribution. Shape --> (batch_num, category_num)\n rng : numpy.random.RandomState\n\n Returns\n ...
Please provide a description of the function:def sample_normal(mean, var, rng): ret = numpy.sqrt(var) * rng.randn(*mean.shape) + mean return ret
[ "Sample from independent normal distributions\n\n Each element is an independent normal distribution.\n\n Parameters\n ----------\n mean : numpy.ndarray\n Means of the normal distribution. Shape --> (batch_num, sample_dim)\n var : numpy.ndarray\n Variance of the normal distribution. Shape -...
Please provide a description of the function:def sample_mog(prob, mean, var, rng): gaussian_inds = sample_categorical(prob, rng).astype(numpy.int32) mean = mean[numpy.arange(mean.shape[0]), gaussian_inds, :] var = var[numpy.arange(mean.shape[0]), gaussian_inds, :] ret = sample_normal(mean=mean, var...
[ "Sample from independent mixture of gaussian (MoG) distributions\n\n Each batch is an independent MoG distribution.\n\n Parameters\n ----------\n prob : numpy.ndarray\n mixture probability of each gaussian. Shape --> (batch_num, center_num)\n mean : numpy.ndarray\n mean of each gaussian. Sh...
Please provide a description of the function:def nce_loss_subwords( data, label, label_mask, label_weight, embed_weight, vocab_size, num_hidden): # get subword-units embedding. label_units_embed = mx.sym.Embedding(data=label, input_dim=vocab_size, ...
[ "NCE-Loss layer under subword-units input.\n " ]
Please provide a description of the function:def get_dataset(prefetch=False): if path.exists(data_dir): print( "Directory {} already exists, skipping.\n" "To force download and extraction, delete the directory and re-run." "".format(data_dir), file=sys.s...
[ "Download the BSDS500 dataset and return train and test iters." ]
Please provide a description of the function:def evaluate(mod, data_iter, epoch, log_interval): start = time.time() total_L = 0.0 nbatch = 0 density = 0 mod.set_states(value=0) for batch in data_iter: mod.forward(batch, is_train=False) outputs = mod.get_outputs(merge_multi_c...
[ " Run evaluation on cpu. " ]
Please provide a description of the function:def _read(self): _, data_img_name, label_img_name = self.f.readline().strip('\n').split("\t") data = {} label = {} data[self.data_name], label[self.label_name] = self._read_img(data_img_name, label_img_name) return list(data.i...
[ "get two list, each list contains two elements: name and nd.array value" ]
Please provide a description of the function:def next(self): if self.iter_next(): self.data, self.label = self._read() return {self.data_name : self.data[0][1], self.label_name : self.label[0][1]} else: raise StopIteration
[ "return one dict which contains \"data\" and \"label\" " ]
Please provide a description of the function:def _convert_operator(self, node_name, op_name, attrs, inputs): if op_name in convert_map: op_name, new_attrs, inputs = convert_map[op_name](attrs, inputs, self) else: raise NotImplementedError("Operator {} not implemented.".f...
[ "Convert from onnx operator to mxnet operator.\n The converter must specify conversions explicitly for incompatible name, and\n apply handlers to operator attributes.\n\n Parameters\n ----------\n :param node_name : str\n name of the node to be translated.\n :par...
Please provide a description of the function:def from_onnx(self, graph): # get input, output shapes self.model_metadata = self.get_graph_metadata(graph) # parse network inputs, aka parameters for init_tensor in graph.initializer: if not init_tensor.name.strip(): ...
[ "Construct symbol from onnx graph.\n\n Parameters\n ----------\n graph : onnx protobuf object\n The loaded onnx graph\n\n Returns\n -------\n sym :symbol.Symbol\n The returned mxnet symbol\n params : dict\n A dict of name: nd.array pa...
Please provide a description of the function:def get_graph_metadata(self, graph): _params = set() for tensor_vals in graph.initializer: _params.add(tensor_vals.name) input_data = [] for graph_input in graph.input: if graph_input.name not in _params: ...
[ "\n Get the model metadata from a given onnx graph.\n " ]
Please provide a description of the function:def graph_to_gluon(self, graph, ctx): sym, arg_params, aux_params = self.from_onnx(graph) metadata = self.get_graph_metadata(graph) data_names = [input_tensor[0] for input_tensor in metadata['input_tensor_data']] data_inputs = [symbol...
[ "Construct SymbolBlock from onnx graph.\n\n Parameters\n ----------\n graph : onnx protobuf object\n The loaded onnx graph\n ctx : Context or list of Context\n Loads the model into one or many context(s).\n\n Returns\n -------\n sym_block :gluon...
Please provide a description of the function:def _parse_array(self, tensor_proto): try: from onnx.numpy_helper import to_array except ImportError: raise ImportError("Onnx and protobuf need to be installed. " + "Instructions to install - http...
[ "Grab data in TensorProto and convert to numpy array." ]
Please provide a description of the function:def _parse_attr(self, attr_proto): attrs = {} for a in attr_proto: for f in ['f', 'i', 's']: if a.HasField(f): attrs[a.name] = getattr(a, f) # Needed for supporting python version >...
[ "Convert a list of AttributeProto to a dict, with names as keys." ]
Please provide a description of the function:def reshape(self, data_shapes, label_shapes=None): super(SVRGModule, self).reshape(data_shapes, label_shapes=label_shapes) self._mod_aux.reshape(data_shapes, label_shapes=label_shapes)
[ "Reshapes both modules 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): # Init dict for storing average of full gradients for each device self._param_dict = [{key: mx.nd.zeros...
[ "Installs and initializes SVRGOptimizer. The SVRGOptimizer is a wrapper class for a regular optimizer that is\n passed in and a special AssignmentOptimizer to accumulate the full gradients. If KVStore is 'local' or None,\n the full gradients will be accumulated locally without pushing to the KVStore....
Please provide a description of the function:def _create_optimizer(self, optimizer, default_opt, kvstore, optimizer_params): # code partially copied from mxnet module.init_optimizer() to accomodate svrg_optimizer batch_size = self._exec_group.batch_size (kv_store, update_on_kvstore) =...
[ "Helper function to create a svrg optimizer. SVRG optimizer encapsulates two optimizers and\n will redirect update() to the correct optimizer based on the key.\n\n Parameters\n ----------\n kvstore : str or KVStore\n Default `'local'`.\n optimizer: str\n Name...
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 to predictio...
[ "Binds the symbols to construct executors for both two modules. This is necessary before one\n can perform computation with the SVRGModule.\n\n Parameters\n ----------\n data_shapes : list of (str, tuple)\n Typically is ``data_iter.provide_data``.\n label_shapes : list ...
Please provide a description of the function:def forward(self, data_batch, is_train=None): super(SVRGModule, self).forward(data_batch, is_train) if is_train: self._mod_aux.forward(data_batch, is_train)
[ "Forward computation for both two modules. 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 p...
Please provide a description of the function:def backward(self, out_grads=None): super(SVRGModule, self).backward(out_grads) if self._mod_aux.binded: self._mod_aux.backward(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_full_grads(self, train_data): param_names = self._exec_group.param_names arg, aux = self.get_params() self._mod_aux.set_params(arg_params=arg, aux_params=aux) train_data.reset() nbatch = 0 padding = 0 ...
[ "Computes the gradients over all data w.r.t weights of past\n m epochs. For distributed env, it will accumulate full grads in the kvstore.\n\n Parameters\n ----------\n train_data: DataIter\n Train data iterator\n " ]
Please provide a description of the function:def _accumulate_kvstore(self, key, value): # Accumulate full gradients for current epochs self._kvstore.push(key + "_full", value) self._kvstore._barrier() self._kvstore.pull(key + "_full", value) self._allocate_gradients(key...
[ "Accumulate gradients over all data in the KVStore. In distributed setting, each worker sees a portion of\n data. The full gradients will be aggregated from each worker in the KVStore.\n\n Parameters\n ----------\n\n key: int or str\n Key in the KVStore.\n value: NDArra...
Please provide a description of the function:def _allocate_gradients(self, key, value): for i in range(self._ctx_len): self._param_dict[i][key] = value[i] / self._ctx_len
[ "Allocate average of full gradients accumulated in the KVStore to each device.\n\n Parameters\n ----------\n\n key: int or str\n Key in the kvstore.\n value: List of NDArray, List of RowSparseNDArray\n A list of average of the full gradients in the KVStore.\n ...
Please provide a description of the function:def _svrg_grads_update_rule(self, g_curr_batch_curr_weight, g_curr_batch_special_weight, g_special_weight_all_batch): for index, grad in enumerate(g_curr_batch_curr_weight): grad -= g_curr_batch_special_weight[inde...
[ "Calculates the gradient based on the SVRG update rule.\n Parameters\n ----------\n g_curr_batch_curr_weight : NDArray\n gradients of current weight of self.mod w.r.t current batch of data\n g_curr_batch_special_weight: NDArray\n gradients of the weight of past m ep...
Please provide a description of the function:def _update_svrg_gradients(self): param_names = self._exec_group.param_names for ctx in range(self._ctx_len): for index, name in enumerate(param_names): g_curr_batch_reg = self._exec_group.grad_arrays[index][ctx] ...
[ "Calculates gradients based on the SVRG update rule.\n " ]
Please provide a description of the function:def fit(self, train_data, eval_data=None, eval_metric='acc', epoch_end_callback=None, batch_end_callback=None, kvstore='local', optimizer='sgd', optimizer_params=(('learning_rate', 0.01),), eval_end_callback=None, eval_batch_en...
[ "Trains the module parameters.\n\n Parameters\n ----------\n train_data : DataIter\n Train DataIter.\n eval_data : DataIter\n If not ``None``, will be used as validation set and the performance\n after each epoch will be evaluated.\n eval_metric : ...
Please provide a description of the function:def prepare(self, data_batch, sparse_row_id_fn=None): super(SVRGModule, self).prepare(data_batch, sparse_row_id_fn=sparse_row_id_fn) self._mod_aux.prepare(data_batch, sparse_row_id_fn=sparse_row_id_fn)
[ "Prepares two modules for processing a data batch.\n\n Usually involves switching bucket and reshaping.\n For modules that contain `row_sparse` parameters in KVStore,\n it prepares the `row_sparse` parameters based on the sparse_row_id_fn.\n\n When KVStore is used to update parameters fo...
Please provide a description of the function:def _load_image_set_index(self, shuffle): assert os.path.exists(self.list_file), 'Path does not exists: {}'.format(self.list_file) with open(self.list_file, 'r') as f: image_set_index = [x.strip() for x in f.readlines()] if shuffl...
[ "\n find out which indexes correspond to given image set (train or val)\n\n Parameters:\n ----------\n shuffle : boolean\n whether to shuffle the image list\n Returns:\n ----------\n entire list of images specified in the setting\n " ]
Please provide a description of the function:def _label_path_from_index(self, index): label_file = os.path.join(self.label_dir, index + self.label_extension) assert os.path.exists(label_file), 'Path does not exist: {}'.format(label_file) return label_file
[ "\n given image index, find out annotation path\n\n Parameters:\n ----------\n index: int\n index of a specific image\n\n Returns:\n ----------\n full path of annotation file\n " ]
Please provide a description of the function:def _load_image_labels(self): temp = [] # load ground-truths for idx in self.image_set_index: label_file = self._label_path_from_index(idx) with open(label_file, 'r') as f: label = [] f...
[ "\n preprocess all ground-truths\n\n Returns:\n ----------\n labels packed in [num_images x max_num_objects x 5] tensor\n " ]
Please provide a description of the function:def get_register_func(base_class, nickname): if base_class not in _REGISTRY: _REGISTRY[base_class] = {} registry = _REGISTRY[base_class] def register(klass, name=None): assert issubclass(klass, base_class), \ "Can only r...
[ "Get registrator function.\n\n Parameters\n ----------\n base_class : type\n base class for classes that will be reigstered\n nickname : str\n nickname of base_class for logging\n\n Returns\n -------\n a registrator function\n ", "Register functions" ]
Please provide a description of the function:def get_alias_func(base_class, nickname): register = get_register_func(base_class, nickname) def alias(*aliases): def reg(klass): for name in aliases: register(klass, name) return klass ...
[ "Get registrator function that allow aliases.\n\n Parameters\n ----------\n base_class : type\n base class for classes that will be reigstered\n nickname : str\n nickname of base_class for logging\n\n Returns\n -------\n a registrator function\n ", "alias registrator", "reg...
Please provide a description of the function:def get_create_func(base_class, nickname): if base_class not in _REGISTRY: _REGISTRY[base_class] = {} registry = _REGISTRY[base_class] def create(*args, **kwargs): if len(args): name = args[0] args = args[1:]...
[ "Get creator function\n\n Parameters\n ----------\n base_class : type\n base class for classes that will be reigstered\n nickname : str\n nickname of base_class for logging\n\n Returns\n -------\n a creator function\n ", "Create instance from config", "Create a %s instance ...
Please provide a description of the function:def parse_args(): parser = argparse.ArgumentParser( formatter_class=argparse.ArgumentDefaultsHelpFormatter, description='Diagnose script for checking the current system.') choices = ['python', 'pip', 'mxnet', 'os', 'hardware', 'network'] for ...
[ "Parse arguments." ]
Please provide a description of the function:def clean_str(string): string = re.sub(r"[^A-Za-z0-9(),!?\'\`]", " ", string) string = re.sub(r"\'s", " \'s", string) string = re.sub(r"\'ve", " \'ve", string) string = re.sub(r"n\'t", " n\'t", string) string = re.sub(r"\'re", " \'re", string) st...
[ "Tokenization/string cleaning for all datasets except for SST.\n Original taken from https://github.com/yoonkim/CNN_sentence/blob/master/process_data.py\n " ]
Please provide a description of the function:def load_data_and_labels(): # Load data from files pos_path = "./data/rt-polaritydata/rt-polarity.pos" neg_path = "./data/rt-polaritydata/rt-polarity.neg" if not os.path.exists(pos_path): os.system("git clone https://github.com/dennybritz/cnn-tex...
[ "Loads MR polarity data from files, splits the data into words and generates labels.\n Returns split sentences and labels.\n " ]
Please provide a description of the function:def pad_sentences(sentences, padding_word="</s>"): sequence_length = max(len(x) for x in sentences) padded_sentences = [] for i, sentence in enumerate(sentences): num_padding = sequence_length - len(sentence) new_sentence = sentence + [paddin...
[ "Pads all sentences to the same length. The length is defined by the longest sentence.\n Returns padded sentences.\n " ]
Please provide a description of the function:def build_input_data(sentences, labels, vocabulary): x = np.array([[vocabulary[word] for word in sentence] for sentence in sentences]) y = np.array(labels) return [x, y]
[ "Maps sentencs and labels to vectors based on a vocabulary." ]
Please provide a description of the function:def build_input_data_with_word2vec(sentences, labels, word2vec_list): x_vec = [] for sent in sentences: vec = [] for word in sent: if word in word2vec_list: vec.append(word2vec_list[word]) else: ...
[ "\n Map sentences and labels to vectors based on a pretrained word2vec\n " ]
Please provide a description of the function:def load_data_with_word2vec(word2vec_list): # Load and preprocess data sentences, labels = load_data_and_labels() sentences_padded = pad_sentences(sentences) # vocabulary, vocabulary_inv = build_vocab(sentences_padded) return build_input_data_with_wo...
[ "Loads and preprocessed data for the MR dataset.\n Returns input vectors, labels, vocabulary, and inverse vocabulary.\n " ]
Please provide a description of the function:def load_data(): # Load and preprocess data sentences, labels = load_data_and_labels() sentences_padded = pad_sentences(sentences) vocabulary, vocabulary_inv = build_vocab(sentences_padded) x, y = build_input_data(sentences_padded, labels, vocabulary...
[ "Loads and preprocessed data for the MR dataset.\n Returns input vectors, labels, vocabulary, and inverse vocabulary.\n " ]
Please provide a description of the function:def batch_iter(data, batch_size, num_epochs): data = np.array(data) data_size = len(data) num_batches_per_epoch = int(len(data)/batch_size) + 1 for epoch in range(num_epochs): # Shuffle the data at each epoch shuffle_indices = np.random.p...
[ "Generates a batch iterator for a dataset." ]
Please provide a description of the function:def load_pretrained_word2vec(infile): if isinstance(infile, str): infile = open(infile) word2vec_list = {} for idx, line in enumerate(infile): if idx == 0: vocab_size, dim = line.strip().split() else: tks = li...
[ "Load the pre-trained word2vec from file." ]
Please provide a description of the function:def generate_batch(im_tensor, im_info): data = [im_tensor, im_info] data_shapes = [('data', im_tensor.shape), ('im_info', im_info.shape)] data_batch = mx.io.DataBatch(data=data, label=None, provide_data=data_shapes, provide_label=None) return data_batch
[ "return batch" ]
Please provide a description of the function:def get_symbol(num_classes=1000, **kwargs): data = mx.symbol.Variable(name="data") label = mx.symbol.Variable(name="label") # group 1 conv1_1 = mx.symbol.Convolution( data=data, kernel=(3, 3), pad=(1, 1), num_filter=64, name="conv1_1") relu1...
[ "\n VGG 16 layers network\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 " ]
Please provide a description of the function:def get_mlp(): data = mx.symbol.Variable('data') fc1 = mx.symbol.CaffeOp(data_0=data, num_weight=2, name='fc1', prototxt="layer{type:\"InnerProduct\" inner_product_param{num_output: 128} }") act1 = mx.symbol.CaffeOp(data_0=fc1, pr...
[ "Get multi-layer perceptron" ]
Please provide a description of the function:def get_lenet(): data = mx.symbol.Variable('data') # first conv conv1 = mx.symbol.CaffeOp(data_0=data, num_weight=2, prototxt="layer{type:\"Convolution\" " "convolution_param { num_output:...
[ "LeCun, Yann, Leon Bottou, Yoshua Bengio, and Patrick\n Haffner. \"Gradient-based learning applied to document recognition.\"\n Proceedings of the IEEE (1998)\n " ]
Please provide a description of the function:def parse_args(): parser = argparse.ArgumentParser(description='train an image classifier on mnist') parser.add_argument('--network', type=str, default='lenet', help='the cnn to use (mlp | lenet | <path to network json file>') parser....
[ "Parse the arguments" ]
Please provide a description of the function:def forward(self, is_train, req, in_data, out_data, aux): data = in_data[0] label = in_data[1] pred = mx.nd.SoftmaxOutput(data, label) self.assign(out_data[0], req[0], pred)
[ "Implements forward computation.\n\n is_train : bool, whether forwarding for training or testing.\n req : list of {'null', 'write', 'inplace', 'add'}, how to assign to out_data. 'null' means skip assignment, etc.\n in_data : list of NDArray, input data.\n out_data : list of NDArray, pre-...
Please provide a description of the function:def backward(self, req, out_grad, in_data, out_data, in_grad, aux): label = in_data[1] pred = out_data[0] dx = pred - mx.nd.one_hot(label, 2) pos_cls_weight = self.positive_cls_weight scale_factor = ((1 + label * pos_cls_weigh...
[ "Implements backward computation\n\n req : list of {'null', 'write', 'inplace', 'add'}, how to assign to in_grad\n out_grad : list of NDArray, gradient w.r.t. output data.\n in_grad : list of NDArray, gradient w.r.t. input data. This is the output buffer.\n " ]
Please provide a description of the function:def _reset_bind(self): self.binded = False self._buckets = {} self._curr_module = None self._curr_bucket_key = None
[ "Internal utility function to reset binding." ]
Please provide a description of the function:def data_names(self): if self.binded: return self._curr_module.data_names else: _, data_names, _ = self._call_sym_gen(self._default_bucket_key) return data_names
[ "A list of names for data required by this module." ]
Please provide a description of the function:def output_names(self): if self.binded: return self._curr_module.output_names else: symbol, _, _ = self._call_sym_gen(self._default_bucket_key) return symbol.list_outputs()
[ "A list of names for the outputs of this module." ]
Please provide a description of the function:def get_params(self): assert self.binded and self.params_initialized self._curr_module._params_dirty = self._params_dirty params = self._curr_module.get_params() self._params_dirty = False return 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: return assert self.binded, 'c...
[ "Initializes parameters.\n\n Parameters\n ----------\n initializer : Initializer\n arg_params : dict\n Defaults to ``None``. Existing parameters. This has higher priority\n than `initializer`.\n aux_params : dict\n Defaults to ``None``. Existing au...
Please provide a description of the function:def get_states(self, merge_multi_context=True): assert self.binded and self.params_initialized return self._curr_module.get_states(merge_multi_context=merge_multi_context)
[ "Gets states from all devices.\n\n Parameters\n ----------\n merge_multi_context : bool\n Default is `True`. In the case when data-parallelism is used, the states\n will be collected from multiple devices. A `True` value indicate that we\n should merge the colle...
Please provide a description of the function:def set_states(self, states=None, value=None): assert self.binded and self.params_initialized self._curr_module.set_states(states, value)
[ "Sets value for states. Only one of states & values can be specified.\n\n Parameters\n ----------\n states : list of list of NDArrays\n Source states arrays formatted like ``[[state1_dev1, state1_dev2],\n [state2_dev1, state2_dev2]]``.\n value : number\n ...
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'): # in case we already initialized params, keep it if self.params_initialized...
[ "Binding for a `BucketingModule` means setting up the buckets and binding the\n executor for the default bucket key. Executors corresponding to other keys are\n bound afterwards with `switch_bucket`.\n\n Parameters\n ----------\n data_shapes : list of (str, tuple)\n Thi...
Please provide a description of the function:def switch_bucket(self, bucket_key, data_shapes, label_shapes=None): assert self.binded, 'call bind before switching bucket' if not bucket_key in self._buckets: symbol, data_names, label_names = self._call_sym_gen(bucket_key) ...
[ "Switches to a different bucket. This will change ``self.curr_module``.\n\n Parameters\n ----------\n bucket_key : str (or any python object)\n The key of the target bucket.\n data_shapes : list of (str, tuple)\n Typically ``data_batch.provide_data``.\n label...
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 ...
[ "Installs and initializes optimizers.\n\n Parameters\n ----------\n kvstore : str or KVStore\n Defaults to `'local'`.\n optimizer : str or Optimizer\n Defaults to `'sgd'`\n optimizer_params : dict\n Defaults to `(('learning_rate', 0.01),)`. The def...
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 forward(self, data_batch, is_train=None): assert self.binded and self.params_initialized self.switch_bucket(data_batch.bucket_key, data_batch.provide_data, data_batch.provide_label) self._curr_module.forward(dat...
[ "Forward computation.\n\n Parameters\n ----------\n data_batch : DataBatch\n is_train : bool\n Defaults to ``None``, in which case `is_train` is take as ``self.for_training``.\n " ]
Please provide a description of the function:def backward(self, out_grads=None): assert self.binded and self.params_initialized self._curr_module.backward(out_grads=out_grads)
[ "Backward computation." ]
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 self._curr_module.update()
[ "Updates parameters according to installed optimizer and the gradient computed\n in the previous forward-backward cycle.\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` paramet...
Please provide a description of the function:def get_outputs(self, merge_multi_context=True): assert self.binded and self.params_initialized return self._curr_module.get_outputs(merge_multi_context=merge_multi_context)
[ "Gets outputs from a previous forward computation.\n\n Parameters\n ----------\n merge_multi_context : bool\n Defaults to ``True``. In the case when data-parallelism is used, the outputs\n will be collected from multiple devices. A ``True`` value indicate that we\n ...
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._curr_module.get_input_grads(merge_multi_context=merge_multi_context)
[ "Gets the gradients with respect to the inputs of the module.\n\n Parameters\n ----------\n merge_multi_context : bool\n Defaults to ``True``. In the case when data-parallelism is used, the outputs\n will be collected from multiple devices. A ``True`` value indicate that w...
Please provide a description of the function:def update_metric(self, eval_metric, labels, pre_sliced=False): assert self.binded and self.params_initialized self._curr_module.update_metric(eval_metric, labels, pre_sliced)
[ "Evaluates and accumulates evaluation metric on outputs of the last forward computation.\n\n Parameters\n ----------\n eval_metric : EvalMetric\n labels : list of NDArray\n Typically ``data_batch.label``.\n " ]
Please provide a description of the function:def install_monitor(self, mon): assert self.binded self._monitor = mon for mod in self._buckets.values(): mod.install_monitor(mon)
[ "Installs monitor on all executors " ]
Please provide a description of the function:def set_recording(is_recording): #pylint: disable=redefined-outer-name prev = ctypes.c_int() check_call(_LIB.MXAutogradSetIsRecording( ctypes.c_int(is_recording), ctypes.byref(prev))) return bool(prev.value)
[ "Set status to recording/not recording. When recording, graph will be constructed\n for gradient computation.\n\n Parameters\n ----------\n is_recording: bool\n\n Returns\n -------\n previous state before this set.\n " ]
Please provide a description of the function:def set_training(train_mode): #pylint: disable=redefined-outer-name prev = ctypes.c_int() check_call(_LIB.MXAutogradSetIsTraining( ctypes.c_int(train_mode), ctypes.byref(prev))) return bool(prev.value)
[ "Set status to training/predicting. This affects ctx.is_train in operator\n running context. For example, Dropout will drop inputs randomly when\n train_mode=True while simply passing through if train_mode=False.\n\n Parameters\n ----------\n train_mode: bool\n\n Returns\n -------\n previous...
Please provide a description of the function:def is_recording(): curr = ctypes.c_bool() check_call(_LIB.MXAutogradIsRecording(ctypes.byref(curr))) return curr.value
[ "Get status on recording/not recording.\n\n Returns\n -------\n Current state of recording.\n " ]
Please provide a description of the function:def is_training(): curr = ctypes.c_bool() check_call(_LIB.MXAutogradIsTraining(ctypes.byref(curr))) return curr.value
[ "Get status on training/predicting.\n\n Returns\n -------\n Current state of training/predicting.\n " ]
Please provide a description of the function:def mark_variables(variables, gradients, grad_reqs='write'): if isinstance(variables, NDArray): assert isinstance(gradients, NDArray) variables = [variables] gradients = [gradients] if isinstance(grad_reqs, string_types): grad_re...
[ "Mark NDArrays as variables to compute gradient for autograd.\n\n Parameters\n ----------\n variables: NDArray or list of NDArray\n gradients: NDArray or list of NDArray\n grad_reqs: str or list of str\n " ]
Please provide a description of the function:def _parse_head(heads, head_grads): if isinstance(heads, NDArray): heads = [heads] if isinstance(head_grads, NDArray): head_grads = [head_grads] head_handles = c_handle_array(heads) if head_grads is None: hgrad_handles = ctypes....
[ "parse head gradient for backward and grad." ]
Please provide a description of the function:def backward(heads, head_grads=None, retain_graph=False, train_mode=True): #pylint: disable=redefined-outer-name head_handles, hgrad_handles = _parse_head(heads, head_grads) check_call(_LIB.MXAutogradBackwardEx( len(head_handles), head_handles, ...
[ "Compute the gradients of heads w.r.t previously marked variables.\n\n Parameters\n ----------\n heads: NDArray or list of NDArray\n Output NDArray(s)\n head_grads: NDArray or list of NDArray or None\n Gradients with respect to heads.\n train_mode: bool, optional\n Whether to do ...
Please provide a description of the function:def grad(heads, variables, head_grads=None, retain_graph=None, create_graph=False, train_mode=True): #pylint: disable=redefined-outer-name head_handles, hgrad_handles = _parse_head(heads, head_grads) if isinstance(variables, NDArray): variable...
[ "Compute the gradients of heads w.r.t variables. Gradients will be\n returned as new NDArrays instead of stored into `variable.grad`.\n Supports recording gradient graph for computing higher order gradients.\n\n .. note::\n\n Currently only a very limited set of operators support higher order \\\n ...
Please provide a description of the function:def get_symbol(x): hdl = SymbolHandle() check_call(_LIB.MXAutogradGetSymbol(x.handle, ctypes.byref(hdl))) return Symbol(hdl)
[ "Retrieve recorded computation history as `Symbol`.\n\n Parameters\n ----------\n x : NDArray\n Array representing the head of computation graph.\n\n Returns\n -------\n Symbol\n The retrieved Symbol.\n " ]
Please provide a description of the function:def load_mldataset(filename): user = [] item = [] score = [] with open(filename) as f: for line in f: tks = line.strip().split('\t') if len(tks) != 4: continue user.append(int(tks[0])) ...
[ "Not particularly fast code to parse the text file and load it into three NDArray's\n and product an NDArrayIter\n " ]
Please provide a description of the function:def ParseAllOps(): cdll.libmxnet = cdll.LoadLibrary(sys.argv[1]) ListOP = cdll.libmxnet.MXSymbolListAtomicSymbolCreators GetOpInfo = cdll.libmxnet.MXSymbolGetAtomicSymbolInfo ListOP.argtypes=[POINTER(c_int), POINTER(POINTER(c_void_p))] GetOpInfo.argt...
[ "\n MXNET_DLL int MXSymbolListAtomicSymbolCreators(mx_uint *out_size,\n AtomicSymbolCreator **out_array);\n\n MXNET_DLL int MXSymbolGetAtomicSymbolInfo(AtomicSymbolCreator creator,\n const char **name,\n ...
Please provide a description of the function:def main(): parser = argparse.ArgumentParser(description='.caffemodel to MXNet .params converter.') parser.add_argument('caffemodel', help='Path to the .caffemodel file to convert.') parser.add_argument('output_file_name', help='Name of the output .params fi...
[ "Read .caffemodel path and .params path as input from command line\n and use CaffeModelConverter to do the conversion" ]
Please provide a description of the function:def add_param(self, param_name, layer_index, blob_index): blobs = self.layers[layer_index].blobs self.dict_param[param_name] = mx.nd.array(caffe.io.blobproto_to_array(blobs[blob_index]))
[ "Add a param to the .params file" ]
Please provide a description of the function:def add_arg_param(self, param_name, layer_index, blob_index): self.add_param('arg:%s' % param_name, layer_index, blob_index)
[ "Add an arg param to .params file. Example: weights of a fully connected layer." ]
Please provide a description of the function:def add_aux_param(self, param_name, layer_index, blob_index): self.add_param('aux:%s' % param_name, layer_index, blob_index)
[ "Add an aux param to .params file. Example: moving_mean in BatchNorm layer " ]
Please provide a description of the function:def add_optional_arg_param(self, param_name, layer_index, blob_index): blobs = self.layers[layer_index].blobs if blob_index < len(blobs): self.add_arg_param(param_name, layer_index, blob_index)
[ "Add an arg param. If there is no such param in .caffemodel fie, silently ignore it." ]
Please provide a description of the function:def convert(self, caffemodel_path, outmodel_path): net_param = caffe_pb2.NetParameter() with open(caffemodel_path, 'rb') as caffe_model_file: net_param.ParseFromString(caffe_model_file.read()) layers = net_param.layer sel...
[ "Convert a Caffe .caffemodel file to MXNet .params file" ]
Please provide a description of the function:def sample_rois(rois, gt_boxes, num_classes, rois_per_image, fg_rois_per_image, fg_overlap, box_stds): overlaps = bbox_overlaps(rois[:, 1:], gt_boxes[:, :4]) gt_assignment = overlaps.argmax(axis=1) labels = gt_boxes[gt_assignment, 4] max_overlaps = overl...
[ "\n generate random sample of ROIs comprising foreground and background examples\n :param rois: [n, 5] (batch_index, x1, y1, x2, y2)\n :param gt_boxes: [n, 5] (x1, y1, x2, y2, cls)\n :param num_classes: number of classes\n :param rois_per_image: total roi number\n :param fg_rois_per_image: foregro...
Please provide a description of the function:def register(reg_name): def do_register(prop_cls): fb_functype = CFUNCTYPE(c_int, c_int, POINTER(c_void_p), POINTER(c_int), POINTER(c_int), c_int, c_void_p) del_functype = CFUNCTYPE(c_int, c_void_p) i...
[ "Register a subclass of CustomOpProp to the registry with name reg_name.", "Register a subclass of CustomOpProp to the registry.", "internal function", "C Callback for ``CustomOpProp::InferShape``.", "C Callback for CustomOpProp::InferStorageTypeBackward", "C Callback for CustomOpProp::InferStorageType", ...
Please provide a description of the function:def declare_backward_dependency(self, out_grad, in_data, out_data): deps = [] if self.need_top_grad(): deps.extend(out_grad) deps.extend(in_data) deps.extend(out_data) return deps
[ "Declare dependencies of this operator for backward pass.\n\n Parameters\n ----------\n out_grad : list of int\n ids of out_grad blobs.\n in_data : list of int\n ids of in_data blobs.\n out_data: list of int\n ids of out_data blobs.\n\n Retu...
Please provide a description of the function:def assign(self, dst, req, src): if req == 'null': return elif req in ('write', 'inplace'): dst[:] = src elif req == 'add': dst[:] += src
[ "Helper function for assigning into dst depending on requirements." ]
Please provide a description of the function:def infer_type(self, in_type): return in_type, [in_type[0]]*len(self.list_outputs()), \ [in_type[0]]*len(self.list_auxiliary_states())
[ "infer_type interface. override to create new operators\n\n Parameters\n ----------\n in_type : list of np.dtype\n list of argument types in the same order as\n declared in list_arguments.\n\n Returns\n -------\n in_type : list\n list of arg...