text
stringlengths
81
112k
Ignore roll over data and set to start. def hard_reset(self): """Ignore roll over data and set to start.""" if self.shuffle: self._shuffle_data() self.cursor = -self.batch_size self._cache_data = None self._cache_label = None
Resets the iterator to the beginning of the data. def reset(self): """Resets the iterator to the beginning of the data.""" if self.shuffle: self._shuffle_data() # the range below indicate the last batch if self.last_batch_handle == 'roll_over' and \ self.num_data...
Increments the coursor by batch_size for next batch and check current cursor if it exceed the number of data points. def iter_next(self): """Increments the coursor by batch_size for next batch and check current cursor if it exceed the number of data points.""" self.cursor += self.batch_...
Returns the next batch of data. def next(self): """Returns the next batch of data.""" if not self.iter_next(): raise StopIteration data = self.getdata() label = self.getlabel() # iter should stop when last batch is not complete if data[0].shape[0] != self.bat...
Load data from underlying arrays. def _getdata(self, data_source, start=None, end=None): """Load data from underlying arrays.""" assert start is not None or end is not None, 'should at least specify start or end' start = start if start is not None else 0 if end is None: end ...
Helper function to concat two NDArrays. def _concat(self, first_data, second_data): """Helper function to concat two NDArrays.""" assert len(first_data) == len( second_data), 'data source should contain the same size' if first_data and second_data: return [ ...
Load data from underlying arrays, internal use only. def _batchify(self, data_source): """Load data from underlying arrays, internal use only.""" assert self.cursor < self.num_data, 'DataIter needs reset.' # first batch of next epoch with 'roll_over' if self.last_batch_handle == 'roll_o...
Get pad value of DataBatch. def getpad(self): """Get pad value of DataBatch.""" if self.last_batch_handle == 'pad' and \ self.cursor + self.batch_size > self.num_data: return self.cursor + self.batch_size - self.num_data # check the first batch elif self.last_batc...
Shuffle the data. def _shuffle_data(self): """Shuffle the data.""" # shuffle index np.random.shuffle(self.idx) # get the data by corresponding index self.data = _getdata_by_idx(self.data, self.idx) self.label = _getdata_by_idx(self.label, self.idx)
Given a quantized symbol and a dict of params that have not been quantized, generate quantized params. Currently only supports quantizing the arg_params with names of `weight` or `bias`, not aux_params. If `qsym` contains symbols that are excluded from being quantized, their corresponding params will no...
Given a symbol object representing a neural network of data type FP32, quantize it into a INT8 network. Parameters ---------- sym : Symbol FP32 neural network symbol. excluded_sym_names : list of strings A list of strings representing the names of the symbols that users want to excl...
Given a dictionary containing the thresholds for quantizing the layers, set the thresholds into the quantized symbol as the params of requantize operators. def _calibrate_quantized_sym(qsym, th_dict): """Given a dictionary containing the thresholds for quantizing the layers, set the thresholds into the qua...
Collect min and max values from layer outputs and save them in a dictionary mapped by layer names. def _collect_layer_output_min_max(mod, data, include_layer=None, max_num_examples=None, logger=None): """Collect min and max values from layer outputs and save them in a dict...
Collect layer outputs and save them in a dictionary mapped by layer names. def _collect_layer_outputs(mod, data, include_layer=None, max_num_examples=None, logger=None): """Collect layer outputs and save them in a dictionary mapped by layer names.""" collector = _LayerOutputCollector(include_layer=include_laye...
Given a discrete distribution (may have not been normalized to 1), smooth it by replacing zeros with eps multiplied by a scaling factor and taking the corresponding amount off the non-zero values. Ref: http://web.engr.illinois.edu/~hanj/cs412/bk3/KL-divergence.pdf def _smooth_distribution(p, eps=0.0001): ...
Given a dataset, find the optimal threshold for quantizing it. The reference distribution is `q`, and the candidate distribution is `p`. `q` is a truncated version of the original distribution. Ref: http://on-demand.gputechconf.com/gtc/2017/presentation/s7310-8-bit-inference-with-tensorrt.pdf def _get_opt...
Given a ndarray dict, find the optimal threshold for quantizing each value of the key. def _get_optimal_thresholds(nd_dict, quantized_dtype, num_bins=8001, num_quantized_bins=255, logger=None): """Given a ndarray dict, find the optimal threshold for quantizing each value of the key.""" if stats is None: ...
Given a str as a path the symbol .json file or a symbol, returns a Symbol object. def _load_sym(sym, logger=logging): """Given a str as a path the symbol .json file or a symbol, returns a Symbol object.""" if isinstance(sym, str): # sym is a symbol file path cur_path = os.path.dirname(os.path.realpath...
Given a str as a path to the .params file or a pair of params, returns two dictionaries representing arg_params and aux_params. def _load_params(params, logger=logging): """Given a str as a path to the .params file or a pair of params, returns two dictionaries representing arg_params and aux_params. ""...
User-level API for generating a quantized model from a FP32 model w/ or w/o calibration. The backend quantized operators are only enabled for Linux systems. Please do not run inference using the quantized models on Windows for now. The quantization implementation adopts the TensorFlow's approach: https:...
Callback function for collecting layer output NDArrays. def collect(self, name, arr): """Callback function for collecting layer output NDArrays.""" name = py_str(name) if self.include_layer is not None and not self.include_layer(name): return handle = ctypes.cast(arr, NDArra...
Callback function for collecting min and max values from an NDArray. def collect(self, name, arr): """Callback function for collecting min and max values from an NDArray.""" name = py_str(name) if self.include_layer is not None and not self.include_layer(name): return handle...
The encoder is a CNN which takes 32x32 image as input generates the 100 dimensional shape embedding as a sample from normal distribution using predicted meand and variance def encoder(nef, z_dim, batch_size, no_bias=True, fix_gamma=True, eps=1e-5 + 1e-12): '''The encoder is a CNN which takes 32x32 image as...
The genrator is a CNN which takes 100 dimensional embedding as input and reconstructs the input image given to the encoder def generator(ngf, nc, no_bias=True, fix_gamma=True, eps=1e-5 + 1e-12, z_dim=100, activation='sigmoid'): '''The genrator is a CNN which takes 100 dimensional embedding as input and rec...
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 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 outp...
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 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 ...
GaussianLogDensity loss calculation for layer wise loss 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_m...
Calculate the discriminator layer loss def DiscriminatorLayerLoss(): '''Calculate the discriminator layer loss ''' data = mx.sym.Variable('data') label = mx.sym.Variable('label') data = mx.sym.Flatten(data) label = mx.sym.Flatten(label) label = mx.sym.BlockGrad(label) zeros = mx.sy...
KLDivergenceLoss loss 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) mu_diff_sq = mx.sym.s...
Get the dataset def get_data(path, activation): '''Get the dataset ''' data = [] image_names = [] for filename in os.listdir(path): img = cv2.imread(os.path.join(path,filename), cv2.IMREAD_GRAYSCALE) image_names.append(filename) if img is not None: data.append(im...
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 def fill_buf(buf, i, img, shape): '''fill the ith grid of the buffer matrix with the values from the img buf : ...
create a grid of images and save it as a final image title : grid image name X : array of images 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, ...
adversarial training of the VAE 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 ''' #encoder...
Creates/Validates dir 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 OSError as exc: ...
Parse args 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 the network', action='store_true'...
Gets root mse between the logarithms of the prediction and the truth. def get_rmse_log(net, X_train, y_train): """Gets root mse between the logarithms of the prediction and the truth.""" num_train = X_train.shape[0] clipped_preds = nd.clip(net(X_train), 1, float('inf')) return np.sqrt(2 * nd.sum(square...
Gets a neural network. Better results are obtained with modifications. def get_net(): """Gets a neural network. Better results are obtained with modifications.""" net = gluon.nn.Sequential() with net.name_scope(): net.add(gluon.nn.Dense(50, activation="relu")) net.add(gluon.nn.Dense(1)) ...
Trains the model. def train(net, X_train, y_train, epochs, verbose_epoch, learning_rate, weight_decay, batch_size): """Trains the model.""" dataset_train = gluon.data.ArrayDataset(X_train, y_train) data_iter_train = gluon.data.DataLoader(dataset_train, batch_size, ...
Conducts k-fold cross validation for the model. def k_fold_cross_valid(k, epochs, verbose_epoch, X_train, y_train, learning_rate, weight_decay, batch_size): """Conducts k-fold cross validation for the model.""" assert k > 1 fold_size = X_train.shape[0] // k train_loss_sum = 0.0 ...
Trains the model and predicts on the test data set. def learn(epochs, verbose_epoch, X_train, y_train, test, learning_rate, weight_decay, batch_size): """Trains the model and predicts on the test data set.""" net = get_net() _ = train(net, X_train, y_train, epochs, verbose_epoch, learning_rate, ...
Create CapsNet def capsnet(batch_size, n_class, num_routing, recon_loss_weight): """Create CapsNet""" # 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(data=data,...
Perform CapsNet training def do_training(num_epoch, optimizer, kvstore, learning_rate, model_prefix, decay): """Perform CapsNet training""" summary_writer = SummaryWriter(args.tblog_dir) lr_scheduler = SimpleLRScheduler(learning_rate) optimizer_params = {'lr_scheduler': lr_scheduler} module.init_pa...
Shuffle the data. def _shuffle(data, idx): """Shuffle the data.""" 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
Update the hyper-parameters and loss of CapsNet def update(self, labels, preds): """Update the hyper-parameters and loss of CapsNet""" batch_sum_metric = 0 batch_num_inst = 0 for label, pred_outcaps in zip(labels[0], preds[0]): label_np = int(label.asnumpy()) pre...
Reset class MNISTCustomIter(mx.io.NDArrayIter): def reset(self): """Reset class MNISTCustomIter(mx.io.NDArrayIter):""" # shuffle data if self.is_train: np.random.shuffle(self.idx) self.data = _shuffle(self.data, self.idx) self.label = _shuffle(self.label, sel...
Generate next of iterator def next(self): """Generate next of iterator""" if self.iter_next(): if self.is_train: data_raw_list = self.getdata() data_shifted = [] for data_raw in data_raw_list[0]: data_shifted.append(random_...
Get the attribute dict given the attribute set by the symbol. Parameters ---------- attr : dict of string to string The attribute passed in by user during symbol creation. Returns ------- attr : dict of string to string Updated attributes to add ...
Create kvstore assuming some parameters' storage types are row_sparse. Parameters ---------- kvstore : KVStore or str The kvstore. Returns ------- kvstore : KVStore update_on_kvstore : bool. Always True. def _create_sparse_kvstore(kvstore): """Create kvstore assuming some para...
Create kvstore This function select and create a proper kvstore if given the kvstore type. Parameters ---------- kvstore : KVStore or str The kvstore. num_device : int The number of devices arg_params : dict of str to `NDArray`. Model parameter, dict of name to `NDArray`...
Initialize kvstore def _initialize_kvstore(kvstore, param_arrays, arg_params, param_names, update_on_kvstore): """Initialize kvstore""" for idx, param_on_devs in enumerate(param_arrays): name = param_names[idx] kvstore.init(name, arg_params[name]) if update_on_kvstore: kvst...
Perform update of param_arrays from grad_arrays on NCCL kvstore. def _update_params_on_kvstore_nccl(param_arrays, grad_arrays, kvstore, param_names): """Perform update of param_arrays from grad_arrays on NCCL kvstore.""" valid_indices = [index for index, grad_list in enumerate(grad_arrays)...
Perform update of param_arrays from grad_arrays on kvstore. def _update_params_on_kvstore(param_arrays, grad_arrays, kvstore, param_names): """Perform update of param_arrays from grad_arrays on kvstore.""" for index, pair in enumerate(zip(param_arrays, grad_arrays)): arg_list, grad_list = pair ...
Perform update of param_arrays from grad_arrays not on kvstore. def _update_params(param_arrays, grad_arrays, updater, num_device, kvstore=None, param_names=None): """Perform update of param_arrays from grad_arrays not on kvstore.""" updates = [[] for _ in range(num_device)] for i, pair ...
Sends args and kwargs to any configured callbacks. This handles the cases where the 'callbacks' variable is ``None``, a single function, or a list. def _multiple_callbacks(callbacks, *args, **kwargs): """Sends args and kwargs to any configured callbacks. This handles the cases where the 'callbacks' var...
Internal training function on multiple devices. This function will also work for single device as well. Parameters ---------- symbol : Symbol The network configuration. ctx : list of Context The training devices. arg_names: list of str Name of all arguments of the networ...
Checkpoint the model data into file. Parameters ---------- prefix : str Prefix of model name. epoch : int The epoch number of the model. symbol : Symbol The input Symbol. arg_params : dict of str to NDArray Model parameter, dict of name to NDArray of net's weight...
Load model checkpoint from file. Parameters ---------- prefix : str Prefix of model name. epoch : int Epoch number of model we would like to load. Returns ------- symbol : Symbol The symbol configuration of computation network. arg_params : dict of str to NDArra...
verify the argument of the default symbol and user provided parameters def _check_arguments(self): """verify the argument of the default symbol and user provided parameters""" if self.argument_checked: return assert(self.symbol is not None) self.argument_checked = True ...
Initialize weight parameters and auxiliary states. def _init_params(self, inputs, overwrite=False): """Initialize weight parameters and auxiliary states.""" inputs = [x if isinstance(x, DataDesc) else DataDesc(*x) for x in inputs] input_shapes = {item.name: item.shape for item in inputs} ...
Initialize the predictor module for running prediction. def _init_predictor(self, input_shapes, type_dict=None): """Initialize the predictor module for running prediction.""" shapes = {name: self.arg_params[name].shape for name in self.arg_params} shapes.update(dict(input_shapes)) if se...
Initialize the iterator given input. def _init_iter(self, X, y, is_train): """Initialize the iterator given input.""" if isinstance(X, (np.ndarray, nd.NDArray)): if y is None: if is_train: raise ValueError('y must be specified when X is numpy.ndarray') ...
Initialize the iterator given eval_data. def _init_eval_iter(self, eval_data): """Initialize the iterator given eval_data.""" if eval_data is None: return eval_data if isinstance(eval_data, (tuple, list)) and len(eval_data) == 2: if eval_data[0] is not None: ...
Run the prediction, always only use one device. Parameters ---------- X : mxnet.DataIter num_batch : int or None The number of batch to run. Go though all batches if ``None``. Returns ------- y : numpy.ndarray or a list of numpy.ndarray if the network...
Run the model given an input and calculate the score as assessed by an evaluation metric. Parameters ---------- X : mxnet.DataIter eval_metric : metric.metric The metric for calculating score. num_batch : int or None The number of batches to run. ...
Fit the model. Parameters ---------- X : DataIter, or numpy.ndarray/NDArray Training data. If `X` is a `DataIter`, the name or (if name not available) the position of its outputs should match the corresponding variable names defined in the symbolic graph. ...
Checkpoint the model checkpoint into file. You can also use `pickle` to do the job if you only work on Python. The advantage of `load` and `save` (as compared to `pickle`) is that the resulting file can be loaded from other MXNet language bindings. One can also directly `load`/`save` fro...
Load model checkpoint from file. Parameters ---------- prefix : str Prefix of model name. epoch : int epoch number of model we would like to load. ctx : Context or list of Context, optional The device context of training and prediction. ...
Functional style to create a model. This function is more consistent with functional languages such as R, where mutation is not allowed. Parameters ---------- symbol : Symbol The symbol configuration of a computation network. X : DataIter Training...
Entry point to build and upload all built dockerimages in parallel :param platforms: List of platforms :param registry: Docker registry name :param load_cache: Load cache before building :return: 1 if error occurred, 0 otherwise def build_save_containers(platforms, registry, load_cache) -> int: """...
Build image for passed platform and upload the cache to the specified S3 bucket :param platform: Platform :param registry: Docker registry name :param load_cache: Load cache before building :return: Platform if failed, None otherwise def _build_save_container(platform, registry, load_cache) -> Optional...
Upload the passed image by id, tag it with docker tag and upload to S3 bucket :param registry: Docker registry name :param docker_tag: Docker tag :param image_id: Image id :return: None def _upload_image(registry, docker_tag, image_id) -> None: """ Upload the passed image by id, tag it with doc...
Login to the Docker Hub account :return: None def _login_dockerhub(): """ Login to the Docker Hub account :return: None """ dockerhub_credentials = _get_dockerhub_credentials() logging.info('Logging in to DockerHub') # We use password-stdin instead of --password to avoid leaking passwo...
Load the precompiled docker cache from the registry :param registry: Docker registry name :param docker_tag: Docker tag to load :return: None def load_docker_cache(registry, docker_tag) -> None: """ Load the precompiled docker cache from the registry :param registry: Docker registry name :p...
Delete the local docker cache for the entire docker image chain :param docker_tag: Docker tag :return: None def delete_local_docker_cache(docker_tag): """ Delete the local docker cache for the entire docker image chain :param docker_tag: Docker tag :return: None """ history_cmd = ['dock...
Utility to create and publish the Docker cache to Docker Hub :return: def main() -> int: """ Utility to create and publish the Docker cache to Docker Hub :return: """ # We need to be in the same directory than the script so the commands in the dockerfiles work as # expected. But the script ...
Download the chinese_text dataset and unzip it def get_chinese_text(): """Download the chinese_text dataset and unzip it""" if not os.path.isdir("data/"): os.system("mkdir data/") if (not os.path.exists('data/pos.txt')) or \ (not os.path.exists('data/neg')): os.system("wget -q https:...
Loads MR polarity data from files, splits the data into words and generates labels. Returns split sentences and labels. def load_data_and_labels(): """Loads MR polarity data from files, splits the data into words and generates labels. Returns split sentences and labels. """ # download dataset g...
override reset behavior def reset(self): """ override reset behavior """ 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
override reset behavior def reset_local(self): """ override reset behavior """ 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
Implementation of updating metrics def update(self, labels, preds): """ Implementation of updating metrics """ # get generated multi label from network cls_prob = preds[0].asnumpy() loc_loss = preds[1].asnumpy() cls_label = preds[2].asnumpy() valid_count ...
Get the current evaluation result. Override the default behavior Returns ------- name : str Name of the metric. value : float Value of the evaluation. def get(self): """Get the current evaluation result. Override the default behavior ...
Structure of the Deep Q Network in the NIPS 2013 workshop paper: Playing Atari with Deep Reinforcement Learning (https://www.cs.toronto.edu/~vmnih/docs/dqn.pdf) Parameters ---------- action_num : int data : mxnet.sym.Symbol, optional name : str, optional def dqn_sym_nips(action_num, data=None,...
A wrapper for the user-defined handle. def _monitor_callback_wrapper(callback): """A wrapper for the user-defined handle.""" def callback_handle(name, array, _): """ ctypes function """ callback(name, array) return callback_handle
Get the dictionary given name and ndarray pairs. def _get_dict(names, ndarrays): """Get the dictionary given name and ndarray pairs.""" nset = set() for nm in names: if nm in nset: raise ValueError('Duplicate names detected, %s' % str(names)) nset.add(nm)...
List all the output NDArray. Returns ------- A list of ndarray bound to the heads of executor. def _get_outputs(self): """List all the output NDArray. Returns ------- A list of ndarray bound to the heads of executor. """ out_size = mx_uint() ...
Calculate the outputs specified by the bound symbol. Parameters ---------- is_train: bool, optional Whether this forward is for evaluation purpose. If True, a backward call is expected to follow. **kwargs Additional specification of input arguments. ...
Do backward pass to get the gradient of arguments. Parameters ---------- out_grads : NDArray or list of NDArray or dict of str to NDArray, optional Gradient on the outputs to be propagated back. This parameter is only needed when bind is called on outputs tha...
Install callback for monitor. Parameters ---------- callback : function Takes a string and an NDArrayHandle. monitor_all : bool, default False If true, monitor both input and output, otherwise monitor output only. Examples -------- >>> de...
Get dictionary representation of argument arrrays. Returns ------- arg_dict : dict of str to NDArray The dictionary that maps the names of arguments to NDArrays. Raises ------ ValueError : if there are duplicated names in the arguments. def arg_dict(self): ...
Get dictionary representation of gradient arrays. Returns ------- grad_dict : dict of str to NDArray The dictionary that maps name of arguments to gradient arrays. def grad_dict(self): """Get dictionary representation of gradient arrays. Returns ------- ...
Get dictionary representation of auxiliary states arrays. Returns ------- aux_dict : dict of str to NDArray The dictionary that maps name of auxiliary states to NDArrays. Raises ------ ValueError : if there are duplicated names in the auxiliary states. def ...
Get dictionary representation of output arrays. Returns ------- output_dict : dict of str to NDArray The dictionary that maps name of output names to NDArrays. Raises ------ ValueError : if there are duplicated names in the outputs. def output_dict(self): ...
Copy parameters from arg_params, aux_params into executor's internal array. Parameters ---------- arg_params : dict of str to NDArray Parameters, dict of name to NDArray of arguments. aux_params : dict of str to NDArray, optional Parameters, dict of name to NDAr...
Return a new executor with the same symbol and shared memory, but different input/output shapes. For runtime reshaping, variable length sequences, etc. The returned executor shares state with the current one, and cannot be used in parallel with it. Parameters ---------- ...
Get a debug string about internal execution plan. Returns ------- debug_str : string Debug string of the executor. Examples -------- >>> a = mx.sym.Variable('a') >>> b = mx.sym.sin(a) >>> c = 2 * a + b >>> texec = c.bind(mx.cpu(), {'a...
parse pascal voc record into a dictionary :param filename: xml file path :return: list of dict def parse_voc_rec(filename): """ parse pascal voc record into a dictionary :param filename: xml file path :return: list of dict """ import xml.etree.ElementTree as ET tree = ET.parse(filen...
pascal voc evaluation :param detpath: detection results detpath.format(classname) :param annopath: annotations annopath.format(classname) :param imageset_file: text file containing list of images :param classname: category name :param cache_dir: caching annotations :param ovthresh: overlap thres...
Register operators def register(op_name): """Register operators""" def wrapper(func): """Helper function to map functions""" try: import onnx as _ MXNetGraph.registry_[op_name] = func except ImportError: pass ...
Convert MXNet layer to ONNX def convert_layer(node, **kwargs): """Convert MXNet layer to ONNX""" op = str(node["op"]) if op not in MXNetGraph.registry_: raise AttributeError("No conversion function registered for op type %s yet." % op) convert_func = MXNetGraph.registry_[op]...
Helper function to split params dictionary into args and aux params Parameters ---------- sym : :class:`~mxnet.symbol.Symbol` MXNet symbol object params : dict of ``str`` to :class:`~mxnet.ndarray.NDArray` Dict of converted parameters stored in ``mxnet.ndarray.ND...