Code
stringlengths
103
85.9k
Summary
listlengths
0
94
Please provide a description of the function:def discriminator1(ndf, no_bias=True, fix_gamma=True, eps=1e-5 + 1e-12): '''First part of the discriminator which takes a 32x32 image as input and output a convolutional feature map, this is required to calculate the layer loss''' BatchNorm = mx.sym.BatchNorm...
[]
Please provide a description of the function:def discriminator2(ndf, no_bias=True, fix_gamma=True, eps=1e-5 + 1e-12): '''Second part of the discriminator which takes a 256x8x8 feature map as input and generates the loss based on whether the input image was a real one or fake one''' BatchNorm = mx.sym.Batch...
[]
Please provide a description of the function:def GaussianLogDensity(x, mu, log_var, name='GaussianLogDensity', EPSILON = 1e-6): '''GaussianLogDensity loss calculation for layer wise loss ''' c = mx.sym.ones_like(log_var)*2.0 * 3.1416 c = mx.symbol.log(c) var = mx.sym.exp(log_var) x_mu2 = mx.symb...
[]
Please provide a description of the function:def DiscriminatorLayerLoss(): '''Calculate the discriminator layer loss ''' data = mx.sym.Variable('data') label = mx.sym.Variable('label') data = mx.sym.Flatten(data) label = mx.sym.Flatten(label) label = mx.sym.BlockGrad(label) zeros = ...
[]
Please provide a description of the function:def KLDivergenceLoss(): '''KLDivergenceLoss loss ''' data = mx.sym.Variable('data') mu1, lv1 = mx.sym.split(data, num_outputs=2, axis=0) mu2 = mx.sym.zeros_like(mu1) lv2 = mx.sym.zeros_like(lv1) v1 = mx.sym.exp(lv1) v2 = mx.sym.exp(lv2) ...
[]
Please provide a description of the function:def get_data(path, activation): '''Get the dataset ''' data = [] image_names = [] for filename in os.listdir(path): img = cv2.imread(os.path.join(path,filename), cv2.IMREAD_GRAYSCALE) image_names.append(filename) if img is not None...
[]
Please provide a description of the function:def fill_buf(buf, i, img, shape): '''fill the ith grid of the buffer matrix with the values from the img buf : buffer matrix i : serial of the image in the 2D grid img : image data shape : ( height width depth ) of image''' # grid height is a multipl...
[]
Please provide a description of the function:def visual(title, X, activation): '''create a grid of images and save it as a final image title : grid image name X : array of images ''' assert len(X.shape) == 4 X = X.transpose((0, 2, 3, 1)) if activation == 'sigmoid': X = np.clip((X)*(...
[]
Please provide a description of the function:def train(dataset, nef, ndf, ngf, nc, batch_size, Z, lr, beta1, epsilon, ctx, check_point, g_dl_weight, output_path, checkpoint_path, data_path, activation,num_epoch, save_after_every, visualize_after_every, show_after_every): '''adversarial training of the VAE ''' ...
[]
Please provide a description of the function:def create_and_validate_dir(data_dir): '''Creates/Validates dir ''' if data_dir != "": if not os.path.exists(data_dir): try: logging.info('create directory %s', data_dir) os.makedirs(data_dir) except...
[]
Please provide a description of the function:def parse_args(): '''Parse args ''' parser = argparse.ArgumentParser(description='Train and Test an Adversarial Variatiional Encoder') parser.add_argument('--train', help='train the network', action='store_true') parser.add_argument('--test', help='test ...
[]
Please provide a description of the function:def get_rmse_log(net, X_train, y_train): num_train = X_train.shape[0] clipped_preds = nd.clip(net(X_train), 1, float('inf')) return np.sqrt(2 * nd.sum(square_loss( nd.log(clipped_preds), nd.log(y_train))).asscalar() / num_train)
[ "Gets root mse between the logarithms of the prediction and the truth." ]
Please provide a description of the function:def get_net(): net = gluon.nn.Sequential() with net.name_scope(): net.add(gluon.nn.Dense(50, activation="relu")) net.add(gluon.nn.Dense(1)) net.initialize() return net
[ "Gets a neural network. Better results are obtained with modifications." ]
Please provide a description of the function:def train(net, X_train, y_train, epochs, verbose_epoch, learning_rate, weight_decay, batch_size): dataset_train = gluon.data.ArrayDataset(X_train, y_train) data_iter_train = gluon.data.DataLoader(dataset_train, batch_size, ...
[ "Trains the model." ]
Please provide a description of the function:def k_fold_cross_valid(k, epochs, verbose_epoch, X_train, y_train, learning_rate, weight_decay, batch_size): assert k > 1 fold_size = X_train.shape[0] // k train_loss_sum = 0.0 test_loss_sum = 0.0 for test_idx in range(k): ...
[ "Conducts k-fold cross validation for the model." ]
Please provide a description of the function:def learn(epochs, verbose_epoch, X_train, y_train, test, learning_rate, weight_decay, batch_size): net = get_net() _ = train(net, X_train, y_train, epochs, verbose_epoch, learning_rate, weight_decay, batch_size) preds = net(X_test)...
[ "Trains the model and predicts on the test data set." ]
Please provide a description of the function:def capsnet(batch_size, n_class, num_routing, recon_loss_weight): # data.shape = [batch_size, 1, 28, 28] data = mx.sym.Variable('data') input_shape = (1, 28, 28) # Conv2D layer # net.shape = [batch_size, 256, 20, 20] conv1 = mx.sym.Convolution(d...
[ "Create CapsNet" ]
Please provide a description of the function:def do_training(num_epoch, optimizer, kvstore, learning_rate, model_prefix, decay): summary_writer = SummaryWriter(args.tblog_dir) lr_scheduler = SimpleLRScheduler(learning_rate) optimizer_params = {'lr_scheduler': lr_scheduler} module.init_params() ...
[ "Perform CapsNet training" ]
Please provide a description of the function:def _shuffle(data, idx): shuffle_data = [] for idx_k, idx_v in data: shuffle_data.append((idx_k, mx.ndarray.array(idx_v.asnumpy()[idx], idx_v.context))) return shuffle_data
[ "Shuffle the data." ]
Please provide a description of the function:def update(self, labels, preds): batch_sum_metric = 0 batch_num_inst = 0 for label, pred_outcaps in zip(labels[0], preds[0]): label_np = int(label.asnumpy()) pred_label = int(np.argmax(pred_outcaps.asnumpy())) ...
[ "Update the hyper-parameters and loss of CapsNet" ]
Please provide a description of the function:def reset(self): # shuffle data if self.is_train: np.random.shuffle(self.idx) self.data = _shuffle(self.data, self.idx) self.label = _shuffle(self.label, self.idx) if self.last_batch_handle == 'roll_over' ...
[ "Reset class MNISTCustomIter(mx.io.NDArrayIter):" ]
Please provide a description of the function:def next(self): if self.iter_next(): if self.is_train: data_raw_list = self.getdata() data_shifted = [] for data_raw in data_raw_list[0]: data_shifted.append(random_shift(data_ra...
[ "Generate next of iterator" ]
Please provide a description of the function:def get(self, attr): if self._attr: ret = self._attr.copy() if attr: ret.update(attr) return ret else: return attr if attr else {}
[ "\n Get the attribute dict given the attribute set by the symbol.\n\n Parameters\n ----------\n attr : dict of string to string\n The attribute passed in by user during symbol creation.\n\n Returns\n -------\n attr : dict of string to string\n U...
Please provide a description of the function:def _create_sparse_kvstore(kvstore): # always update on kvstore update_on_kvstore = True if isinstance(kvstore, kvs.KVStore): kv = kvstore elif isinstance(kvstore, str): kv = kvs.create(kvstore) else: raise TypeError("Cannot c...
[ "Create kvstore assuming some parameters' storage types are row_sparse.\n\n Parameters\n ----------\n kvstore : KVStore or str\n The kvstore.\n\n Returns\n -------\n kvstore : KVStore\n update_on_kvstore : bool. Always True.\n " ]
Please provide a description of the function:def _create_kvstore(kvstore, num_device, arg_params): update_on_kvstore = bool(int(os.getenv('MXNET_UPDATE_ON_KVSTORE', "1"))) if kvstore is None: kv = None elif isinstance(kvstore, kvs.KVStore): kv = kvstore elif isinstance(kvstore, str)...
[ "Create kvstore\n This function select and create a proper kvstore if given the kvstore type.\n\n Parameters\n ----------\n kvstore : KVStore or str\n The kvstore.\n num_device : int\n The number of devices\n arg_params : dict of str to `NDArray`.\n Model parameter, dict of na...
Please provide a description of the function:def _initialize_kvstore(kvstore, param_arrays, arg_params, param_names, update_on_kvstore): for idx, param_on_devs in enumerate(param_arrays): name = param_names[idx] kvstore.init(name, arg_params[name]) if update_on_kvstore: kvs...
[ "Initialize kvstore" ]
Please provide a description of the function:def _update_params_on_kvstore_nccl(param_arrays, grad_arrays, kvstore, param_names): valid_indices = [index for index, grad_list in enumerate(grad_arrays) if grad_list[0] is not None] valid_grad_arrays = [grad_arrays[i] for i in valid_indice...
[ "Perform update of param_arrays from grad_arrays on NCCL kvstore." ]
Please provide a description of the function:def _update_params_on_kvstore(param_arrays, grad_arrays, kvstore, param_names): for index, pair in enumerate(zip(param_arrays, grad_arrays)): arg_list, grad_list = pair if grad_list[0] is None: continue name = param_names[index] ...
[ "Perform update of param_arrays from grad_arrays on kvstore." ]
Please provide a description of the function:def _update_params(param_arrays, grad_arrays, updater, num_device, kvstore=None, param_names=None): updates = [[] for _ in range(num_device)] for i, pair in enumerate(zip(param_arrays, grad_arrays)): arg_list, grad_list = pair ...
[ "Perform update of param_arrays from grad_arrays not on kvstore." ]
Please provide a description of the function:def _multiple_callbacks(callbacks, *args, **kwargs): if isinstance(callbacks, list): for cb in callbacks: cb(*args, **kwargs) return if callbacks: callbacks(*args, **kwargs)
[ "Sends args and kwargs to any configured callbacks.\n This handles the cases where the 'callbacks' variable\n is ``None``, a single function, or a list.\n " ]
Please provide a description of the function:def _train_multi_device(symbol, ctx, arg_names, param_names, aux_names, arg_params, aux_params, begin_epoch, end_epoch, epoch_size, optimizer, kvstore, update_on_kvstore, train_da...
[ "Internal training function on multiple devices.\n This function will also work for single device as well.\n\n Parameters\n ----------\n symbol : Symbol\n The network configuration.\n ctx : list of Context\n The training devices.\n arg_names: list of str\n Name of all argument...
Please provide a description of the function:def save_checkpoint(prefix, epoch, symbol, arg_params, aux_params): if symbol is not None: symbol.save('%s-symbol.json' % prefix) save_dict = {('arg:%s' % k) : v.as_in_context(cpu()) for k, v in arg_params.items()} save_dict.update({('aux:%s' % k) :...
[ "Checkpoint the model data into file.\n\n Parameters\n ----------\n prefix : str\n Prefix of model name.\n epoch : int\n The epoch number of the model.\n symbol : Symbol\n The input Symbol.\n arg_params : dict of str to NDArray\n Model parameter, dict of name to NDArray...
Please provide a description of the function:def load_checkpoint(prefix, epoch): symbol = sym.load('%s-symbol.json' % prefix) save_dict = nd.load('%s-%04d.params' % (prefix, epoch)) arg_params = {} aux_params = {} for k, v in save_dict.items(): tp, name = k.split(':', 1) if tp =...
[ "Load model checkpoint from file.\n\n Parameters\n ----------\n prefix : str\n Prefix of model name.\n epoch : int\n Epoch number of model we would like to load.\n\n Returns\n -------\n symbol : Symbol\n The symbol configuration of computation network.\n arg_params : dic...
Please provide a description of the function:def _check_arguments(self): if self.argument_checked: return assert(self.symbol is not None) self.argument_checked = True # check if symbol contain duplicated names. _check_arguments(self.symbol) # rematc...
[ "verify the argument of the default symbol and user provided parameters" ]
Please provide a description of the function:def _init_params(self, inputs, overwrite=False): inputs = [x if isinstance(x, DataDesc) else DataDesc(*x) for x in inputs] input_shapes = {item.name: item.shape for item in inputs} arg_shapes, _, aux_shapes = self.symbol.infer_shape(**input_s...
[ "Initialize weight parameters and auxiliary states." ]
Please provide a description of the function:def _init_predictor(self, input_shapes, type_dict=None): shapes = {name: self.arg_params[name].shape for name in self.arg_params} shapes.update(dict(input_shapes)) if self._pred_exec is not None: arg_shapes, _, _ = self.symbol.inf...
[ "Initialize the predictor module for running prediction." ]
Please provide a description of the function:def _init_iter(self, X, y, is_train): if isinstance(X, (np.ndarray, nd.NDArray)): if y is None: if is_train: raise ValueError('y must be specified when X is numpy.ndarray') else: ...
[ "Initialize the iterator given input." ]
Please provide a description of the function:def _init_eval_iter(self, eval_data): if eval_data is None: return eval_data if isinstance(eval_data, (tuple, list)) and len(eval_data) == 2: if eval_data[0] is not None: if eval_data[1] is None and isinstance(...
[ "Initialize the iterator given eval_data." ]
Please provide a description of the function:def predict(self, X, num_batch=None, return_data=False, reset=True): X = self._init_iter(X, None, is_train=False) if reset: X.reset() data_shapes = X.provide_data data_names = [x[0] for x in data_shapes] type_dict...
[ "Run the prediction, always only use one device.\n\n Parameters\n ----------\n X : mxnet.DataIter\n num_batch : int or None\n The number of batch to run. Go though all batches if ``None``.\n Returns\n -------\n y : numpy.ndarray or a list of numpy.ndarray ...
Please provide a description of the function:def score(self, X, eval_metric='acc', num_batch=None, batch_end_callback=None, reset=True): # setup metric if not isinstance(eval_metric, metric.EvalMetric): eval_metric = metric.create(eval_metric) X = self._init_iter(X, None, i...
[ "Run the model given an input and calculate the score\n as assessed by an evaluation metric.\n\n Parameters\n ----------\n X : mxnet.DataIter\n eval_metric : metric.metric\n The metric for calculating score.\n num_batch : int or None\n The number of ba...
Please provide a description of the function:def fit(self, X, y=None, eval_data=None, eval_metric='acc', epoch_end_callback=None, batch_end_callback=None, kvstore='local', logger=None, work_load_list=None, monitor=None, eval_end_callback=LogValidationMetricsCallback(), eval_batch_end...
[ "Fit the model.\n\n Parameters\n ----------\n X : DataIter, or numpy.ndarray/NDArray\n Training data. If `X` is a `DataIter`, the name or (if name not available)\n the position of its outputs should match the corresponding variable\n names defined in the symboli...
Please provide a description of the function:def save(self, prefix, epoch=None): if epoch is None: epoch = self.num_epoch assert epoch is not None save_checkpoint(prefix, epoch, self.symbol, self.arg_params, self.aux_params)
[ "Checkpoint the model checkpoint into file.\n You can also use `pickle` to do the job if you only work on Python.\n The advantage of `load` and `save` (as compared to `pickle`) is that\n the resulting file can be loaded from other MXNet language bindings.\n One can also directly `load`/`...
Please provide a description of the function:def load(prefix, epoch, ctx=None, **kwargs): symbol, arg_params, aux_params = load_checkpoint(prefix, epoch) return FeedForward(symbol, ctx=ctx, arg_params=arg_params, aux_params=aux_params, begin...
[ "Load model checkpoint from file.\n\n Parameters\n ----------\n prefix : str\n Prefix of model name.\n epoch : int\n epoch number of model we would like to load.\n ctx : Context or list of Context, optional\n The device context of training and pred...
Please provide a description of the function:def create(symbol, X, y=None, ctx=None, num_epoch=None, epoch_size=None, optimizer='sgd', initializer=Uniform(0.01), eval_data=None, eval_metric='acc', epoch_end_callback=None, batch_end_callback=None, kvstore='loca...
[ "Functional style to create a model.\n This function is more consistent with functional\n languages such as R, where mutation is not allowed.\n\n Parameters\n ----------\n symbol : Symbol\n The symbol configuration of a computation network.\n X : DataIter\n ...
Please provide a description of the function:def build_save_containers(platforms, registry, load_cache) -> int: from joblib import Parallel, delayed if len(platforms) == 0: return 0 platform_results = Parallel(n_jobs=PARALLEL_BUILDS, backend="multiprocessing")( delayed(_build_save_cont...
[ "\n Entry point to build and upload all built dockerimages in parallel\n :param platforms: List of platforms\n :param registry: Docker registry name\n :param load_cache: Load cache before building\n :return: 1 if error occurred, 0 otherwise\n " ]
Please provide a description of the function:def _build_save_container(platform, registry, load_cache) -> Optional[str]: docker_tag = build_util.get_docker_tag(platform=platform, registry=registry) # Preload cache if load_cache: load_docker_cache(registry=registry, docker_tag=docker_tag) ...
[ "\n Build image for passed platform and upload the cache to the specified S3 bucket\n :param platform: Platform\n :param registry: Docker registry name\n :param load_cache: Load cache before building\n :return: Platform if failed, None otherwise\n " ]
Please provide a description of the function:def _upload_image(registry, docker_tag, image_id) -> None: # We don't have to retag the image since it is already in the right format logging.info('Uploading %s (%s) to %s', docker_tag, image_id, registry) push_cmd = ['docker', 'push', docker_tag] subpro...
[ "\n Upload the passed image by id, tag it with docker tag and upload to S3 bucket\n :param registry: Docker registry name\n :param docker_tag: Docker tag\n :param image_id: Image id\n :return: None\n " ]
Please provide a description of the function:def _login_dockerhub(): dockerhub_credentials = _get_dockerhub_credentials() logging.info('Logging in to DockerHub') # We use password-stdin instead of --password to avoid leaking passwords in case of an error. # This method will produce the following o...
[ "\n Login to the Docker Hub account\n :return: None\n " ]
Please provide a description of the function:def load_docker_cache(registry, docker_tag) -> None: # We don't have to retag the image since it's already in the right format if not registry: return assert docker_tag logging.info('Loading Docker cache for %s from %s', docker_tag, registry) ...
[ "\n Load the precompiled docker cache from the registry\n :param registry: Docker registry name\n :param docker_tag: Docker tag to load\n :return: None\n " ]
Please provide a description of the function:def delete_local_docker_cache(docker_tag): history_cmd = ['docker', 'history', '-q', docker_tag] try: image_ids_b = subprocess.check_output(history_cmd) image_ids_str = image_ids_b.decode('utf-8').strip() layer_ids = [id.strip() for id i...
[ "\n Delete the local docker cache for the entire docker image chain\n :param docker_tag: Docker tag\n :return: None\n " ]
Please provide a description of the function:def main() -> int: # We need to be in the same directory than the script so the commands in the dockerfiles work as # expected. But the script can be invoked from a different path base = os.path.split(os.path.realpath(__file__))[0] os.chdir(base) lo...
[ "\n Utility to create and publish the Docker cache to Docker Hub\n :return:\n " ]
Please provide a description of the function:def get_chinese_text(): if not os.path.isdir("data/"): os.system("mkdir data/") if (not os.path.exists('data/pos.txt')) or \ (not os.path.exists('data/neg')): os.system("wget -q https://raw.githubusercontent.com/dmlc/web-data/master/mxnet/...
[ "Download the chinese_text dataset and unzip it" ]
Please provide a description of the function:def load_data_and_labels(): # download dataset get_chinese_text() # Load data from files positive_examples = list(codecs.open("./data/pos.txt", "r", "utf-8").readlines()) positive_examples = [s.strip() for s in positive_examples] positive_exampl...
[ "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 reset(self): if getattr(self, 'num', None) is None: self.num_inst = 0 self.sum_metric = 0.0 else: self.num_inst = [0] * self.num self.sum_metric = [0.0] * self.num
[ "\n override reset behavior\n " ]
Please provide a description of the function:def reset_local(self): if getattr(self, 'num', None) is None: self.num_inst = 0 self.sum_metric = 0.0 else: self.num_inst = [0] * self.num self.sum_metric = [0.0] * self.num
[ "\n override reset behavior\n " ]
Please provide a description of the function:def update(self, labels, preds): # get generated multi label from network cls_prob = preds[0].asnumpy() loc_loss = preds[1].asnumpy() cls_label = preds[2].asnumpy() valid_count = np.sum(cls_label >= 0) # overall accura...
[ "\n Implementation of updating metrics\n " ]
Please provide a description of the function:def get(self): if self.num is None: if self.num_inst == 0: return (self.name, float('nan')) else: return (self.name, self.sum_metric / self.num_inst) else: names = ['%s'%(self.name[i...
[ "Get the current evaluation result.\n Override the default behavior\n\n Returns\n -------\n name : str\n Name of the metric.\n value : float\n Value of the evaluation.\n " ]
Please provide a description of the function:def dqn_sym_nips(action_num, data=None, name='dqn'): if data is None: net = mx.symbol.Variable('data') else: net = data net = mx.symbol.Convolution(data=net, name='conv1', kernel=(8, 8), stride=(4, 4), num_filter=16) net = mx.symbol.Activ...
[ "Structure of the Deep Q Network in the NIPS 2013 workshop paper:\n Playing Atari with Deep Reinforcement Learning (https://www.cs.toronto.edu/~vmnih/docs/dqn.pdf)\n\n Parameters\n ----------\n action_num : int\n data : mxnet.sym.Symbol, optional\n name : str, optional\n " ]
Please provide a description of the function:def _monitor_callback_wrapper(callback): def callback_handle(name, array, _): callback(name, array) return callback_handle
[ "A wrapper for the user-defined handle.", " ctypes function " ]
Please provide a description of the function:def _get_dict(names, ndarrays): nset = set() for nm in names: if nm in nset: raise ValueError('Duplicate names detected, %s' % str(names)) nset.add(nm) return dict(zip(names, ndarrays))
[ "Get the dictionary given name and ndarray pairs." ]
Please provide a description of the function:def _get_outputs(self): out_size = mx_uint() handles = ctypes.POINTER(NDArrayHandle)() check_call(_LIB.MXExecutorOutputs(self.handle, ctypes.byref(out_size), ctypes.byref(handles))) num_output...
[ "List all the output NDArray.\n\n Returns\n -------\n A list of ndarray bound to the heads of executor.\n " ]
Please provide a description of the function:def forward(self, is_train=False, **kwargs): if len(kwargs) != 0: arg_dict = self.arg_dict for name, array in kwargs.items(): if not isinstance(array, (NDArray, np.ndarray)): raise ValueError('only ...
[ "Calculate the outputs specified by the bound symbol.\n\n Parameters\n ----------\n is_train: bool, optional\n Whether this forward is for evaluation purpose. If True,\n a backward call is expected to follow.\n\n **kwargs\n Additional specification of inp...
Please provide a description of the function:def backward(self, out_grads=None, is_train=True): if out_grads is None: out_grads = [] elif isinstance(out_grads, NDArray): out_grads = [out_grads] elif isinstance(out_grads, dict): out_grads = [out_grads[...
[ "Do backward pass to get the gradient of arguments.\n\n Parameters\n ----------\n out_grads : NDArray or list of NDArray or dict of str to NDArray, optional\n Gradient on the outputs to be propagated back.\n This parameter is only needed when bind is called\n on...
Please provide a description of the function:def set_monitor_callback(self, callback, monitor_all=False): cb_type = ctypes.CFUNCTYPE(None, ctypes.c_char_p, NDArrayHandle, ctypes.c_void_p) self._monitor_callback = cb_type(_monitor_callback_wrapper(callback)) check_call(_LIB.MXExecutorSet...
[ "Install callback for monitor.\n\n Parameters\n ----------\n callback : function\n Takes a string and an NDArrayHandle.\n monitor_all : bool, default False\n If true, monitor both input and output, otherwise monitor output only.\n\n Examples\n --------...
Please provide a description of the function:def arg_dict(self): if self._arg_dict is None: self._arg_dict = Executor._get_dict( self._symbol.list_arguments(), self.arg_arrays) return self._arg_dict
[ "Get dictionary representation of argument arrrays.\n\n Returns\n -------\n arg_dict : dict of str to NDArray\n The dictionary that maps the names of arguments to NDArrays.\n\n Raises\n ------\n ValueError : if there are duplicated names in the arguments.\n ...
Please provide a description of the function:def grad_dict(self): if self._grad_dict is None: self._grad_dict = Executor._get_dict( self._symbol.list_arguments(), self.grad_arrays) return self._grad_dict
[ "Get dictionary representation of gradient arrays.\n\n Returns\n -------\n grad_dict : dict of str to NDArray\n The dictionary that maps name of arguments to gradient arrays.\n " ]
Please provide a description of the function:def aux_dict(self): if self._aux_dict is None: self._aux_dict = Executor._get_dict( self._symbol.list_auxiliary_states(), self.aux_arrays) return self._aux_dict
[ "Get dictionary representation of auxiliary states arrays.\n\n Returns\n -------\n aux_dict : dict of str to NDArray\n The dictionary that maps name of auxiliary states to NDArrays.\n\n Raises\n ------\n ValueError : if there are duplicated names in the auxiliary...
Please provide a description of the function:def output_dict(self): if self._output_dict is None: self._output_dict = Executor._get_dict( self._symbol.list_outputs(), self.outputs) return self._output_dict
[ "Get dictionary representation of output arrays.\n\n Returns\n -------\n output_dict : dict of str to NDArray\n The dictionary that maps name of output names to NDArrays.\n\n Raises\n ------\n ValueError : if there are duplicated names in the outputs.\n " ...
Please provide a description of the function:def copy_params_from(self, arg_params, aux_params=None, allow_extra_params=False): for name, array in arg_params.items(): if name in self.arg_dict: dst = self.arg_dict[name] array.astype(dst.dtype).copyto(dst) ...
[ "Copy parameters from arg_params, aux_params into executor's internal array.\n\n Parameters\n ----------\n arg_params : dict of str to NDArray\n Parameters, dict of name to NDArray of arguments.\n\n aux_params : dict of str to NDArray, optional\n Parameters, dict of...
Please provide a description of the function:def reshape(self, partial_shaping=False, allow_up_sizing=False, **kwargs): # pylint: disable=too-many-branches provided_arg_shape_data = [] # shape data # argument shape index in sdata, # e.g. [sdata[indptr[0]], sdata[indptr[1]]) is ...
[ "Return a new executor with the same symbol and shared memory,\n but different input/output shapes.\n For runtime reshaping, variable length sequences, etc.\n The returned executor shares state with the current one,\n and cannot be used in parallel with it.\n\n Parameters\n ...
Please provide a description of the function:def debug_str(self): debug_str = ctypes.c_char_p() check_call(_LIB.MXExecutorPrint( self.handle, ctypes.byref(debug_str))) return py_str(debug_str.value)
[ "Get a debug string about internal execution plan.\n\n Returns\n -------\n debug_str : string\n Debug string of the executor.\n\n Examples\n --------\n >>> a = mx.sym.Variable('a')\n >>> b = mx.sym.sin(a)\n >>> c = 2 * a + b\n >>> texec = c.b...
Please provide a description of the function:def parse_voc_rec(filename): import xml.etree.ElementTree as ET tree = ET.parse(filename) objects = [] for obj in tree.findall('object'): obj_dict = dict() obj_dict['name'] = obj.find('name').text obj_dict['difficult'] = int(obj.f...
[ "\n parse pascal voc record into a dictionary\n :param filename: xml file path\n :return: list of dict\n " ]
Please provide a description of the function:def voc_eval(detpath, annopath, imageset_file, classname, cache_dir, ovthresh=0.5, use_07_metric=False): if not os.path.isdir(cache_dir): os.mkdir(cache_dir) cache_file = os.path.join(cache_dir, 'annotations.pkl') with open(imageset_file, 'r') as f: ...
[ "\n pascal voc evaluation\n :param detpath: detection results detpath.format(classname)\n :param annopath: annotations annopath.format(classname)\n :param imageset_file: text file containing list of images\n :param classname: category name\n :param cache_dir: caching annotations\n :param ovthre...
Please provide a description of the function:def register(op_name): def wrapper(func): try: import onnx as _ MXNetGraph.registry_[op_name] = func except ImportError: pass return func return wrapper
[ "Register operators", "Helper function to map functions" ]
Please provide a description of the function:def convert_layer(node, **kwargs): op = str(node["op"]) if op not in MXNetGraph.registry_: raise AttributeError("No conversion function registered for op type %s yet." % op) convert_func = MXNetGraph.registry_[op] return c...
[ "Convert MXNet layer to ONNX" ]
Please provide a description of the function:def split_params(sym, params): arg_params = {} aux_params = {} for args in sym.list_arguments(): if args in params: arg_params.update({args: nd.array(params[args])}) for aux in sym.list_auxiliary_states(): ...
[ "Helper function to split params dictionary into args and aux params\n\n Parameters\n ----------\n sym : :class:`~mxnet.symbol.Symbol`\n MXNet symbol object\n params : dict of ``str`` to :class:`~mxnet.ndarray.NDArray`\n Dict of converted parameters stored in ``mxne...
Please provide a description of the function:def get_outputs(sym, params, in_shape, in_label): # remove any input listed in params from sym.list_inputs() and bind them to the input shapes provided # by user. Also remove in_label, which is the name of the label symbol that may have been used ...
[ " Infer output shapes and return dictionary of output name to shape\n\n :param :class:`~mxnet.symbol.Symbol` sym: symbol to perform infer shape on\n :param dic of (str, nd.NDArray) params:\n :param list of tuple(int, ...) in_shape: list of all input shapes\n :param in_label: name of lab...
Please provide a description of the function:def convert_weights_to_numpy(weights_dict): return dict([(k.replace("arg:", "").replace("aux:", ""), v.asnumpy()) for k, v in weights_dict.items()])
[ "Convert weights to numpy" ]
Please provide a description of the function:def create_onnx_graph_proto(self, sym, params, in_shape, in_type, verbose=False): try: from onnx import (checker, helper, NodeProto, ValueInfoProto, TensorProto) from onnx.helper import make_tensor_value_info except ImportErro...
[ "Convert MXNet graph to ONNX graph\n\n Parameters\n ----------\n sym : :class:`~mxnet.symbol.Symbol`\n MXNet symbol object\n params : dict of ``str`` to :class:`~mxnet.ndarray.NDArray`\n Dict of converted parameters stored in ``mxnet.ndarray.NDArray`` format\n ...
Please provide a description of the function:def get_lr_scheduler(learning_rate, lr_refactor_step, lr_refactor_ratio, num_example, batch_size, begin_epoch): assert lr_refactor_ratio > 0 iter_refactor = [int(r) for r in lr_refactor_step.split(',') if r.strip()] if lr_refactor_ratio ...
[ "\n Compute learning rate and refactor scheduler\n\n Parameters:\n ---------\n learning_rate : float\n original learning rate\n lr_refactor_step : comma separated str\n epochs to change learning rate\n lr_refactor_ratio : float\n lr *= ratio at certain steps\n num_example :...
Please provide a description of the function:def train_net(net, train_path, num_classes, batch_size, data_shape, mean_pixels, resume, finetune, pretrained, epoch, prefix, ctx, begin_epoch, end_epoch, frequent, learning_rate, momentum, weight_decay, lr_refactor_step, lr_refactor...
[ "\n Wrapper for training phase.\n\n Parameters:\n ----------\n net : str\n symbol name for the network structure\n train_path : str\n record file path for training\n num_classes : int\n number of object classes, not including background\n batch_size : int\n training ...
Please provide a description of the function:def imagenet50(display=False, resolution=224): prefix = github_data_url + "imagenet50_" X = np.load(cache(prefix + "%sx%s.npy" % (resolution, resolution))).astype(np.float32) y = np.loadtxt(cache(prefix + "labels.csv")) return X, y
[ " This is a set of 50 images representative of ImageNet images.\n\n This dataset was collected by randomly finding a working ImageNet link and then pasting the\n original ImageNet image into Google image search restricted to images licensed for reuse. A\n similar image (now with rights to reuse) was downlo...
Please provide a description of the function:def boston(display=False): d = sklearn.datasets.load_boston() df = pd.DataFrame(data=d.data, columns=d.feature_names) # pylint: disable=E1101 return df, d.target
[ " Return the boston housing data in a nice package. " ]
Please provide a description of the function:def imdb(display=False): with open(cache(github_data_url + "imdb_train.txt")) as f: data = f.readlines() y = np.ones(25000, dtype=np.bool) y[:12500] = 0 return data, y
[ " Return the clssic IMDB sentiment analysis training data in a nice package.\n\n Full data is at: http://ai.stanford.edu/~amaas/data/sentiment/aclImdb_v1.tar.gz\n Paper to cite when using the data is: http://www.aclweb.org/anthology/P11-1015\n " ]
Please provide a description of the function:def communitiesandcrime(display=False): raw_data = pd.read_csv( cache(github_data_url + "CommViolPredUnnormalizedData.txt"), na_values="?" ) # find the indices where the total violent crimes are known valid_inds = np.where(np.invert(np....
[ " Predict total number of non-violent crimes per 100K popuation.\n\n This dataset is from the classic UCI Machine Learning repository:\n https://archive.ics.uci.edu/ml/datasets/Communities+and+Crime+Unnormalized\n " ]
Please provide a description of the function:def diabetes(display=False): d = sklearn.datasets.load_diabetes() df = pd.DataFrame(data=d.data, columns=d.feature_names) # pylint: disable=E1101 return df, d.target
[ " Return the diabetes data in a nice package. " ]
Please provide a description of the function:def iris(display=False): d = sklearn.datasets.load_iris() df = pd.DataFrame(data=d.data, columns=d.feature_names) # pylint: disable=E1101 if display: return df, [d.target_names[v] for v in d.target] # pylint: disable=E1101 else: return d...
[ " Return the classic iris data in a nice package. " ]
Please provide a description of the function:def adult(display=False): dtypes = [ ("Age", "float32"), ("Workclass", "category"), ("fnlwgt", "float32"), ("Education", "category"), ("Education-Num", "float32"), ("Marital Status", "category"), ("Occupation", "category"), ("Relationship", "...
[ " Return the Adult census data in a nice package. " ]
Please provide a description of the function:def nhanesi(display=False): X = pd.read_csv(cache(github_data_url + "NHANESI_subset_X.csv")) y = pd.read_csv(cache(github_data_url + "NHANESI_subset_y.csv"))["y"] if display: X_display = X.copy() X_display["Sex"] = ["Male" if v == 1 else "Fem...
[ " A nicely packaged version of NHANES I data with surivival times as labels.\n " ]
Please provide a description of the function:def cric(display=False): X = pd.read_csv(cache(github_data_url + "CRIC_time_4yearESRD_X.csv")) y = np.loadtxt(cache(github_data_url + "CRIC_time_4yearESRD_y.csv")) if display: X_display = X.copy() return X_display, y else: return ...
[ " A nicely packaged version of CRIC data with progression to ESRD within 4 years as the label.\n " ]
Please provide a description of the function:def corrgroups60(display=False): # set a constant seed old_seed = np.random.seed() np.random.seed(0) # generate dataset with known correlation N = 1000 M = 60 # set one coefficent from each group of 3 to 1 beta = np.zeros(M) beta[0...
[ " Correlated Groups 60\n \n A simulated dataset with tight correlations among distinct groups of features.\n " ]
Please provide a description of the function:def independentlinear60(display=False): # set a constant seed old_seed = np.random.seed() np.random.seed(0) # generate dataset with known correlation N = 1000 M = 60 # set one coefficent from each group of 3 to 1 beta = np.zeros(M) ...
[ " A simulated dataset with tight correlations among distinct groups of features.\n " ]
Please provide a description of the function:def rank(): rank_data_url = 'https://raw.githubusercontent.com/Microsoft/LightGBM/master/examples/lambdarank/' x_train, y_train = sklearn.datasets.load_svmlight_file(cache(rank_data_url + 'rank.train')) x_test, y_test = sklearn.datasets.load_svmlight_file(ca...
[ " Ranking datasets from lightgbm repository.\n " ]
Please provide a description of the function:def batch_remove_retrain(nmask_train, nmask_test, X_train, y_train, X_test, y_test, attr_train, attr_test, model_generator, metric): warnings.warn("The retrain based measures can incorrectly evaluate models in some cases!") X_train, X_test = to_array(X_train, ...
[ " An approximation of holdout that only retraines the model once.\n\n This is alse called ROAR (RemOve And Retrain) in work by Google. It is much more computationally\n efficient that the holdout method because it masks the most important features in every sample\n and then retrains the model once, instead...
Please provide a description of the function:def keep_retrain(nkeep, X_train, y_train, X_test, y_test, attr_test, model_generator, metric, trained_model, random_state): warnings.warn("The retrain based measures can incorrectly evaluate models in some cases!") # see if we match the last cached call gl...
[ " The model is retrained for each test sample with the non-important features set to a constant.\n\n If you want to know how important a set of features is you can ask how the model would be\n different if only those features had existed. To determine this we can mask the other features\n across the entire...
Please provide a description of the function:def keep_mask(nkeep, X_train, y_train, X_test, y_test, attr_test, model_generator, metric, trained_model, random_state): X_train, X_test = to_array(X_train, X_test) # how many features to mask assert X_train.shape[1] == X_test.shape[1] # keep nkeep to...
[ " The model is revaluated for each test sample with the non-important features set to their mean.\n " ]
Please provide a description of the function:def keep_impute(nkeep, X_train, y_train, X_test, y_test, attr_test, model_generator, metric, trained_model, random_state): X_train, X_test = to_array(X_train, X_test) # how many features to mask assert X_train.shape[1] == X_test.shape[1] # keep nkeep ...
[ " The model is revaluated for each test sample with the non-important features set to an imputed value.\n\n Note that the imputation is done using a multivariate normality assumption on the dataset. This depends on\n being able to estimate the full data covariance matrix (and inverse) accuractly. So X_train.s...
Please provide a description of the function:def keep_resample(nkeep, X_train, y_train, X_test, y_test, attr_test, model_generator, metric, trained_model, random_state): # why broken? overwriting? X_train, X_test = to_array(X_train, X_test) # how many features to mask assert X_train.shape[1] == X_tes...
[ " The model is revaluated for each test sample with the non-important features set to resample background values.\n " ]
Please provide a description of the function:def local_accuracy(X_train, y_train, X_test, y_test, attr_test, model_generator, metric, trained_model): X_train, X_test = to_array(X_train, X_test) # how many features to mask assert X_train.shape[1] == X_test.shape[1] # keep nkeep top features and r...
[ " The how well do the features plus a constant base rate sum up to the model output.\n " ]
Please provide a description of the function:def const_rand(size, seed=23980): old_seed = np.random.seed() np.random.seed(seed) out = np.random.rand(size) np.random.seed(old_seed) return out
[ " Generate a random array with a fixed seed.\n " ]