Code stringlengths 103 85.9k | Summary listlengths 0 94 |
|---|---|
Please provide a description of the function:def retry(target_exception, tries=4, delay_s=1, backoff=2):
import time
from functools import wraps
def decorated_retry(f):
@wraps(f)
def f_retry(*args, **kwargs):
mtries, mdelay = tries, delay_s
while mtries > 1:
... | [
"Retry calling the decorated function using an exponential backoff.\n\n http://www.saltycrane.com/blog/2009/11/trying-out-retry-decorator-python/\n original from: http://wiki.python.org/moin/PythonDecoratorLibrary#Retry\n\n :param target_exception: the exception to check. may be a tuple of\n excepti... |
Please provide a description of the function:def load_model(model_name, epoch_num, data_shapes, label_shapes, label_names, gpus=''):
sym, arg_params, aux_params = mx.model.load_checkpoint(model_name, epoch_num)
mod = create_module(sym, data_shapes, label_shapes, label_names, gpus)
mod.set_params(
... | [
"Returns a module loaded with the provided model.\n\n Parameters\n ----------\n model_name: str\n Prefix of the MXNet model name as stored on the local directory.\n\n epoch_num : int\n Epoch number of model we would like to load.\n\n input_shape: tuple\n The shape of the input da... |
Please provide a description of the function:def create_module(sym, data_shapes, label_shapes, label_names, gpus=''):
if gpus == '':
devices = mx.cpu()
else:
devices = [mx.gpu(int(i)) for i in gpus.split(',')]
data_names = [data_shape[0] for data_shape in data_shapes]
mod = mx.mod... | [
"Creates a new MXNet module.\n\n Parameters\n ----------\n sym : Symbol\n An MXNet symbol.\n\n input_shape: tuple\n The shape of the input data in the form of (batch_size, channels, height, width)\n\n files: list of strings\n List of URLs pertaining to files that need to be downl... |
Please provide a description of the function:def evaluate_net(net, path_imgrec, num_classes, num_batch, mean_pixels, data_shape,
model_prefix, epoch, ctx=mx.cpu(), batch_size=32,
path_imglist="", nms_thresh=0.45, force_nms=False,
ovp_thresh=0.5, use_difficult=False, cl... | [
"\n evalute network given validation record file\n\n Parameters:\n ----------\n net : str or None\n Network name or use None to load from json without modifying\n path_imgrec : str\n path to the record validation file\n path_imglist : str\n path to the list file to replace lab... |
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):
pass | [
"Initializes the parameters and auxiliary states. By default this function\n does nothing. Subclass should override this method if contains parameters.\n\n Parameters\n ----------\n initializer : Initializer\n Called to initialize parameters if needed.\n arg_params : di... |
Please provide a description of the function:def update_metric(self, eval_metric, labels, pre_sliced=False):
if self._label_shapes is None:
# since we do not need labels, we are probably not a module with a loss
# function or predictions, so just ignore this call
ret... | [
"Evaluates and accumulates evaluation metric on outputs of the last forward computation.\n Subclass should override this method if needed.\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 bind(self, data_shapes, label_shapes=None, for_training=True,
inputs_need_grad=False, force_rebind=False, shared_module=None,
grad_req='write'):
if self.binded and not force_rebind:
self.logger.warning('Already bound... | [
"Binds the symbols to construct executors. This is necessary before one\n can perform computation with the module.\n\n Parameters\n ----------\n data_shapes : list of (str, tuple)\n Typically is ``data_iter.provide_data``.\n label_shapes : list of (str, tuple)\n ... |
Please provide a description of the function:def forward(self, data_batch, is_train=None):
self._scores = data_batch.data[0]
if is_train is None:
is_train = self.for_training
if is_train:
self._labels = data_batch.label[0] | [
"Forward computation. Here we do nothing but to keep a reference to\n the scores and the labels so that we can do backward computation.\n\n Parameters\n ----------\n data_batch : DataBatch\n Could be anything with similar API implemented.\n is_train : bool\n ... |
Please provide a description of the function:def _backward_impl(self):
if self._grad_func is not None:
grad = self._grad_func(self._scores, self._labels)
if not isinstance(grad, nd.NDArray):
grad = nd.array(grad)
self._scores_grad = grad
else:... | [
"Actual implementation of the backward computation. The computation\n should take ``self._scores`` and ``self._labels`` and then compute the\n gradients with respect to the scores, store it as an `NDArray` in\n ``self._scores_grad``.\n\n Instead of defining a subclass and overriding this... |
Please provide a description of the function:def encode_sentences(sentences, vocab=None, invalid_label=-1, invalid_key='\n',
start_label=0, unknown_token=None):
idx = start_label
if vocab is None:
vocab = {invalid_key: invalid_label}
new_vocab = True
else:
n... | [
"Encode sentences and (optionally) build a mapping\n from string tokens to integer indices. Unknown keys\n will be added to vocabulary.\n\n Parameters\n ----------\n sentences : list of list of str\n A list of sentences to encode. Each sentence\n should be a list of string tokens.\n ... |
Please provide a description of the function:def reset(self):
self.curr_idx = 0
random.shuffle(self.idx)
for buck in self.data:
np.random.shuffle(buck)
self.nddata = []
self.ndlabel = []
for buck in self.data:
label = np.empty_like(buck)
... | [
"Resets the iterator to the beginning of the data."
] |
Please provide a description of the function:def next(self):
if self.curr_idx == len(self.idx):
raise StopIteration
i, j = self.idx[self.curr_idx]
self.curr_idx += 1
if self.major_axis == 1:
data = self.nddata[i][j:j+self.batch_size].T
label ... | [
"Returns the next batch of data."
] |
Please provide a description of the function:def getInstance(self):
try:
return self._instance
except AttributeError:
self._instance = self._decorated()
return self._instance | [
"\n Returns the singleton instance. Upon its first call, it creates a\n new instance of the decorated class and calls its `__init__` method.\n On all subsequent calls, the already created instance is returned.\n\n "
] |
Please provide a description of the function:def main():
parser = argparse.ArgumentParser()
parser.add_argument('--batch_size', type=int, default=64)
parser.add_argument('--image_path', type=str, default='./data/datasets/')
parser.add_argument('--align_path', type=str, default='./data/align/')
... | [
"\n Description : run lipnet training code using argument info\n "
] |
Please provide a description of the function:def get(self, name, **kwargs):
name = self._prefix + name
if name not in self._params:
self._params[name] = symbol.Variable(name, **kwargs)
return self._params[name] | [
"Get the variable given a name if one exists or create a new one if missing.\n\n Parameters\n ----------\n name : str\n name of the variable\n **kwargs :\n more arguments that's passed to symbol.Variable\n "
] |
Please provide a description of the function:def reset(self):
self._init_counter = -1
self._counter = -1
if hasattr(self, '_cells'):
for cell in self._cells:
cell.reset() | [
"Reset before re-using the cell for another graph."
] |
Please provide a description of the function:def begin_state(self, func=symbol.zeros, **kwargs):
assert not self._modified, \
"After applying modifier cells (e.g. DropoutCell) the base " \
"cell cannot be called directly. Call the modifier cell instead."
states = []
... | [
"Initial state for this cell.\n\n Parameters\n ----------\n func : callable, default symbol.zeros\n Function for creating initial state. Can be symbol.zeros,\n symbol.uniform, symbol.Variable etc.\n Use symbol.Variable if you want to directly\n feed i... |
Please provide a description of the function:def unpack_weights(self, args):
args = args.copy()
if not self._gate_names:
return args
h = self._num_hidden
for group_name in ['i2h', 'h2h']:
weight = args.pop('%s%s_weight'%(self._prefix, group_name))
... | [
"Unpack fused weight matrices into separate\n weight matrices.\n\n For example, say you use a module object `mod` to run a network that has an lstm cell.\n In `mod.get_params()[0]`, the lstm parameters are all represented as a single big vector.\n `cell.unpack_weights(mod.get_params()[0]... |
Please provide a description of the function:def pack_weights(self, args):
args = args.copy()
if not self._gate_names:
return args
for group_name in ['i2h', 'h2h']:
weight = []
bias = []
for gate in self._gate_names:
wname ... | [
"Pack separate weight matrices into a single packed\n weight.\n\n Parameters\n ----------\n args : dict of str -> NDArray\n Dictionary containing unpacked weights.\n\n Returns\n -------\n args : dict of str -> NDArray\n Dictionary with packed we... |
Please provide a description of the function:def unroll(self, length, inputs, begin_state=None, layout='NTC', merge_outputs=None):
self.reset()
inputs, _ = _normalize_sequence(length, inputs, layout, False)
if begin_state is None:
begin_state = self.begin_state()
s... | [
"Unroll an RNN cell across time steps.\n\n Parameters\n ----------\n length : int\n Number of steps to unroll.\n inputs : Symbol, list of Symbol, or None\n If `inputs` is a single Symbol (usually the output\n of Embedding symbol), it should have shape\n ... |
Please provide a description of the function:def _get_activation(self, inputs, activation, **kwargs):
if isinstance(activation, string_types):
return symbol.Activation(inputs, act_type=activation, **kwargs)
else:
return activation(inputs, **kwargs) | [
"Get activation function. Convert if is string"
] |
Please provide a description of the function:def _slice_weights(self, arr, li, lh):
args = {}
gate_names = self._gate_names
directions = self._directions
b = len(directions)
p = 0
for layer in range(self._num_layers):
for direction in directions:
... | [
"slice fused rnn weights"
] |
Please provide a description of the function:def unfuse(self):
stack = SequentialRNNCell()
get_cell = {'rnn_relu': lambda cell_prefix: RNNCell(self._num_hidden,
activation='relu',
... | [
"Unfuse the fused RNN in to a stack of rnn cells.\n\n Returns\n -------\n cell : mxnet.rnn.SequentialRNNCell\n unfused cell that can be used for stepping, and can run on CPU.\n "
] |
Please provide a description of the function:def add(self, cell):
self._cells.append(cell)
if self._override_cell_params:
assert cell._own_params, \
"Either specify params for SequentialRNNCell " \
"or child cells, not both."
cell.params._... | [
"Append a cell into the stack.\n\n Parameters\n ----------\n cell : BaseRNNCell\n The cell to be appended. During unroll, previous cell's output (or raw inputs if\n no previous cell) is used as the input to this cell.\n "
] |
Please provide a description of the function:def read_image(img_path, image_dims=None, mean=None):
import urllib
filename = img_path.split("/")[-1]
if img_path.startswith('http'):
urllib.urlretrieve(img_path, filename)
img = cv2.imread(filename)
else:
img = cv2.imread(img_... | [
"\n Reads an image from file path or URL, optionally resizing to given image dimensions and\n subtracting mean.\n :param img_path: path to file, or url to download\n :param image_dims: image dimensions to resize to, or None\n :param mean: mean file to subtract, or None\n :return: loaded image, in ... |
Please provide a description of the function:def _ch_dev(arg_params, aux_params, ctx):
new_args = dict()
new_auxs = dict()
for k, v in arg_params.items():
new_args[k] = v.as_in_context(ctx)
for k, v in aux_params.items():
new_auxs[k] = v.as_in_context(ctx)
return new_args, new_a... | [
"\n Changes device of given mxnet arguments\n :param arg_params: arguments\n :param aux_params: auxiliary parameters\n :param ctx: new device context\n :return: arguments and auxiliary parameters on new device\n "
] |
Please provide a description of the function:def convert_and_compare_caffe_to_mxnet(image_url, gpu, caffe_prototxt_path, caffe_model_path,
caffe_mean, mean_diff_allowed, max_diff_allowed):
import caffe
from caffe_proto_utils import read_network_dag, process_network_p... | [
"\n Run the layer comparison on a caffe model, given its prototxt, weights and mean.\n The comparison is done by inferring on a given image using both caffe and mxnet model\n :param image_url: image file or url to run inference on\n :param gpu: gpu to use, -1 for cpu\n :param caffe_prototxt_path: pat... |
Please provide a description of the function:def _bfs(root_node, process_node):
from collections import deque
seen_nodes = set()
next_nodes = deque()
seen_nodes.add(root_node)
next_nodes.append(root_node)
while next_nodes:
current_node = next_nodes.popleft()
# process c... | [
"\n Implementation of Breadth-first search (BFS) on caffe network DAG\n :param root_node: root node of caffe network DAG\n :param process_node: function to run on each node\n "
] |
Please provide a description of the function:def compare_layers_from_nets(caffe_net, arg_params, aux_params, exe, layer_name_to_record,
top_to_layers, mean_diff_allowed, max_diff_allowed):
import re
log_format = ' {0:<40} {1:<40} {2:<8} {3:>10} {4:>10} {5:<1}'
comp... | [
"\n Compare layer by layer of a caffe network with mxnet network\n :param caffe_net: loaded caffe network\n :param arg_params: arguments\n :param aux_params: auxiliary parameters\n :param exe: mxnet model\n :param layer_name_to_record: map between caffe layer and information record\n :param top... |
Please provide a description of the function:def main():
parser = argparse.ArgumentParser(
description='Tool for testing caffe to mxnet conversion layer by layer')
parser.add_argument('--image_url', type=str,
default='https://github.com/dmlc/web-data/raw/master/mxnet/doc/'\... | [
"Entrypoint for compare_layers"
] |
Please provide a description of the function:def get_executor(sym, ctx, data_inputs, initializer=None):
data_shapes = {k: v.shape for k, v in data_inputs.items()}
arg_names = sym.list_arguments()
aux_names = sym.list_auxiliary_states()
param_names = list(set(arg_names) - set(data_inputs.keys()))
... | [
"Get executor to Stochastic Gradient Langevin Dynamics and/or Bayesian Dark Knowledge"
] |
Please provide a description of the function:def copy_param(exe, new_param=None):
if new_param is None:
new_param = {k: nd.empty(v.shape, ctx=mx.cpu()) for k, v in exe.arg_dict.items()}
for k, v in new_param.items():
exe.arg_dict[k].copyto(v)
return new_param | [
"Create copy of parameters"
] |
Please provide a description of the function:def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument("font_path", help="Path to ttf font file or directory containing ttf files")
parser.add_argument("--loss", help="'ctc' or 'warpctc' loss [Default 'ctc']", default='ctc')
parser.add_... | [
"Parse command line arguments"
] |
Please provide a description of the function:def main():
args = parse_args()
if not any(args.loss == s for s in ['ctc', 'warpctc']):
raise ValueError("Invalid loss '{}' (must be 'ctc' or 'warpctc')".format(args.loss))
hp = Hyperparams()
# Start a multiprocessor captcha image generator
... | [
"Program entry point"
] |
Please provide a description of the function:def optimize(args):
if args.cuda:
ctx = mx.gpu(0)
else:
ctx = mx.cpu(0)
# load the content and style target
content_image = utils.tensor_load_rgbimage(args.content_image,ctx, size=args.content_size, keep_asp=True)
content_image = util... | [
" Gatys et al. CVPR 2017\n ref: Image Style Transfer Using Convolutional Neural Networks\n "
] |
Please provide a description of the function:def get_mnist_sym(output_op=None, num_hidden=400):
net = mx.symbol.Variable('data')
net = mx.symbol.FullyConnected(data=net, name='mnist_fc1', num_hidden=num_hidden)
net = mx.symbol.Activation(data=net, name='mnist_relu1', act_type="relu")
net = mx.symbo... | [
"Get symbol of mnist"
] |
Please provide a description of the function:def synthetic_grad(X, theta, sigma1, sigma2, sigmax, rescale_grad=1.0, grad=None):
if grad is None:
grad = nd.empty(theta.shape, theta.context)
theta1 = theta.asnumpy()[0]
theta2 = theta.asnumpy()[1]
v1 = sigma1 ** 2
v2 = sigma2 ** 2
vx =... | [
"Get synthetic gradient value"
] |
Please provide a description of the function:def get_toy_sym(teacher=True, teacher_noise_precision=None):
if teacher:
net = mx.symbol.Variable('data')
net = mx.symbol.FullyConnected(data=net, name='teacher_fc1', num_hidden=100)
net = mx.symbol.Activation(data=net, name='teacher_relu1', ... | [
"Get toy symbol"
] |
Please provide a description of the function:def run_mnist_DistilledSGLD(num_training=50000, gpu_id=None):
X, Y, X_test, Y_test = load_mnist(num_training)
minibatch_size = 100
if num_training >= 10000:
num_hidden = 800
total_iter_num = 1000000
teacher_learning_rate = 1E-6
... | [
"Run DistilledSGLD on mnist dataset"
] |
Please provide a description of the function:def run_toy_SGLD(gpu_id=None):
X, Y, X_test, Y_test = load_toy()
minibatch_size = 1
teacher_noise_precision = 1.0 / 9.0
net = get_toy_sym(True, teacher_noise_precision)
data_shape = (minibatch_size,) + X.shape[1::]
data_inputs = {'data': nd.zeros... | [
"Run SGLD on toy dataset"
] |
Please provide a description of the function:def run_toy_DistilledSGLD(gpu_id):
X, Y, X_test, Y_test = load_toy()
minibatch_size = 1
teacher_noise_precision = 1.0
teacher_net = get_toy_sym(True, teacher_noise_precision)
student_net = get_toy_sym(False)
data_shape = (minibatch_size,) + X.sha... | [
"Run DistilledSGLD on toy dataset"
] |
Please provide a description of the function:def run_toy_HMC(gpu_id=None):
X, Y, X_test, Y_test = load_toy()
minibatch_size = Y.shape[0]
noise_precision = 1 / 9.0
net = get_toy_sym(True, noise_precision)
data_shape = (minibatch_size,) + X.shape[1::]
data_inputs = {'data': nd.zeros(data_shap... | [
"Run HMC on toy dataset"
] |
Please provide a description of the function:def run_synthetic_SGLD():
theta1 = 0
theta2 = 1
sigma1 = numpy.sqrt(10)
sigma2 = 1
sigmax = numpy.sqrt(2)
X = load_synthetic(theta1=theta1, theta2=theta2, sigmax=sigmax, num=100)
minibatch_size = 1
total_iter_num = 1000000
lr_schedule... | [
"Run synthetic SGLD"
] |
Please provide a description of the function:def load_pascal(image_set, year, devkit_path, shuffle=False):
image_set = [y.strip() for y in image_set.split(',')]
assert image_set, "No image_set specified"
year = [y.strip() for y in year.split(',')]
assert year, "No year specified"
# make sure (... | [
"\n wrapper function for loading pascal voc dataset\n\n Parameters:\n ----------\n image_set : str\n train, trainval...\n year : str\n 2007, 2012 or combinations splitted by comma\n devkit_path : str\n root directory of dataset\n shuffle : bool\n whether to shuffle i... |
Please provide a description of the function:def load_coco(image_set, dirname, shuffle=False):
anno_files = ['instances_' + y.strip() + '.json' for y in image_set.split(',')]
assert anno_files, "No image set specified"
imdbs = []
for af in anno_files:
af_path = os.path.join(dirname, 'annota... | [
"\n wrapper function for loading ms coco dataset\n\n Parameters:\n ----------\n image_set : str\n train2014, val2014, valminusminival2014, minival2014\n dirname: str\n root dir for coco\n shuffle: boolean\n initial shuffle\n "
] |
Please provide a description of the function:def reset(self):
self.curr_idx = 0
#shuffle data in each bucket
random.shuffle(self.idx)
for i, buck in enumerate(self.sentences):
self.indices[i], self.sentences[i], self.characters[i], self.label[i] = shuffle(self.indice... | [
"Resets the iterator to the beginning of the data."
] |
Please provide a description of the function:def next(self):
if self.curr_idx == len(self.idx):
raise StopIteration
#i = batches index, j = starting record
i, j = self.idx[self.curr_idx]
self.curr_idx += 1
indices = self.ndindex[i][j:j + self.batch_size]
... | [
"Returns the next batch of data."
] |
Please provide a description of the function:def convert_reshape(net, node, module, builder):
input_name, output_name = _get_input_output_name(net, node)
name = node['name']
target_shape = node['shape']
if any(item <= 0 for item in target_shape):
raise NotImplementedError('Special dimensio... | [
"Converts a reshape layer from mxnet to coreml.\n\n This doesn't currently handle the deprecated parameters for the reshape layer.\n\n Parameters\n ----------\n network: net\n An mxnet network object.\n\n layer: node\n Node to convert.\n\n module: module\n A module for MXNet\n... |
Please provide a description of the function:def convert_transpose(net, node, module, builder):
input_name, output_name = _get_input_output_name(net, node)
name = node['name']
param = _get_attrs(node)
axes = literal_eval(param['axes'])
builder.add_permute(name, axes, input_name, output_name) | [
"Convert a transpose layer from mxnet to coreml.\n\n Parameters\n ----------\n network: net\n A mxnet network object.\n\n layer: node\n Node to convert.\n\n module: module\n An module for MXNet\n\n builder: NeuralNetworkBuilder\n A neural network builder object.\n "
... |
Please provide a description of the function:def convert_flatten(net, node, module, builder):
input_name, output_name = _get_input_output_name(net, node)
name = node['name']
mode = 0 # CHANNEL_FIRST
builder.add_flatten(name, mode, input_name, output_name) | [
"Convert a flatten layer from mxnet to coreml.\n\n Parameters\n ----------\n network: net\n A mxnet network object.\n\n layer: node\n Node to convert.\n\n module: module\n An module for MXNet\n\n builder: NeuralNetworkBuilder\n A neural network builder object.\n "
] |
Please provide a description of the function:def convert_softmax(net, node, module, builder):
input_name, output_name = _get_input_output_name(net, node)
name = node['name']
builder.add_softmax(name=name,
input_name=input_name,
output_name=output_name) | [
"Convert a softmax layer from mxnet to coreml.\n\n Parameters\n ----------\n network: net\n A mxnet network object.\n\n layer: node\n Node to convert.\n\n module: module\n An module for MXNet\n\n builder: NeuralNetworkBuilder\n A neural network builder object.\n "
] |
Please provide a description of the function:def convert_activation(net, node, module, builder):
input_name, output_name = _get_input_output_name(net, node)
name = node['name']
mx_non_linearity = _get_attrs(node)['act_type']
#TODO add SCALED_TANH, SOFTPLUS, SOFTSIGN, SIGMOID_HARD, LEAKYRELU, PRELU,... | [
"Convert an activation layer from mxnet to coreml.\n\n Parameters\n ----------\n network: net\n A mxnet network object.\n\n layer: node\n Node to convert.\n\n module: module\n An module for MXNet\n\n builder: NeuralNetworkBuilder\n A neural network builder object.\n ... |
Please provide a description of the function:def convert_leakyrelu(net, node, module, builder):
input_name, output_name = _get_input_output_name(net, node)
name = node['name']
inputs = node['inputs']
args, _ = module.get_params()
mx_non_linearity = _get_attrs(node)['act_type']
if mx_non_li... | [
"Convert a leakyrelu layer from mxnet to coreml.\n\n Parameters\n ----------\n network: net\n A mxnet network object.\n\n layer: node\n Node to convert.\n\n module: module\n An module for MXNet\n\n builder: NeuralNetworkBuilder\n A neural network builder object.\n "
... |
Please provide a description of the function:def convert_elementwise_add(net, node, module, builder):
input_names, output_name = _get_input_output_name(net, node, [0, 1])
name = node['name']
builder.add_elementwise(name, input_names, output_name, 'ADD') | [
"Convert an elementwise add layer from mxnet to coreml.\n\n Parameters\n ----------\n network: net\n A mxnet network object.\n\n layer: node\n Node to convert.\n\n module: module\n An module for MXNet\n\n builder: NeuralNetworkBuilder\n A neural network builder object.\... |
Please provide a description of the function:def convert_convolution(net, node, module, builder):
input_name, output_name = _get_input_output_name(net, node)
name = node['name']
param = _get_attrs(node)
inputs = node['inputs']
args, _ = module.get_params()
if 'no_bias' in param.keys():
... | [
"Convert a convolution layer from mxnet to coreml.\n\n Parameters\n ----------\n network: net\n A mxnet network object.\n\n layer: node\n Node to convert.\n\n module: module\n An module for MXNet\n\n builder: NeuralNetworkBuilder\n A neural network builder object.\n ... |
Please provide a description of the function:def convert_pooling(net, node, module, builder):
input_name, output_name = _get_input_output_name(net, node)
name = node['name']
param = _get_attrs(node)
layer_type_mx = param['pool_type']
if layer_type_mx == 'max':
layer_type = 'MAX'
el... | [
"Convert a pooling layer from mxnet to coreml.\n\n Parameters\n ----------\n network: net\n A mxnet network object.\n\n layer: node\n Node to convert.\n\n module: module\n An module for MXNet\n\n builder: NeuralNetworkBuilder\n A neural network builder object.\n "
] |
Please provide a description of the function:def convert_batchnorm(net, node, module, builder):
input_name, output_name = _get_input_output_name(net, node)
name = node['name']
inputs = node['inputs']
eps = 1e-3 # Default value of eps for MXNet.
use_global_stats = False # Default value of us... | [
"Convert a batchnorm layer from mxnet to coreml.\n\n Parameters\n ----------\n network: net\n A mxnet network object.\n\n layer: node\n Node to convert.\n\n module: module\n An module for MXNet\n\n builder: NeuralNetworkBuilder\n A neural network builder object.\n "
... |
Please provide a description of the function:def convert_concat(net, node, module, builder):
# Get input and output names
input_names, output_name = _get_input_output_name(net, node, 'all')
name = node['name']
mode = 'CONCAT'
builder.add_elementwise(name = name, input_names = input_names,
... | [
"Convert concat layer from mxnet to coreml.\n\n Parameters\n ----------\n network: net\n A mxnet network object.\n\n layer: node\n Node to convert.\n\n module: module\n An module for MXNet\n\n builder: NeuralNetworkBuilder\n A neural network builder object.\n "
] |
Please provide a description of the function:def dmlc_opts(opts):
args = ['--num-workers', str(opts.num_workers),
'--num-servers', str(opts.num_servers),
'--cluster', opts.launcher,
'--host-file', opts.hostfile,
'--sync-dst-dir', opts.sync_dst_dir]
# convert... | [
"convert from mxnet's opts to dmlc's opts\n "
] |
Please provide a description of the function:def _unfuse(self):
assert not self._projection_size, "_unfuse does not support projection layer yet!"
assert not self._lstm_state_clip_min and not self._lstm_state_clip_max, \
"_unfuse does not support state clipping yet!"
get... | [
"Unfuses the fused RNN in to a stack of rnn cells."
] |
Please provide a description of the function:def begin_state(self, batch_size=0, func=ndarray.zeros, **kwargs):
states = []
for i, info in enumerate(self.state_info(batch_size)):
if info is not None:
info.update(kwargs)
else:
info = kwargs... | [
"Initial state for this cell.\n\n Parameters\n ----------\n batch_size: int\n Only required for `NDArray` API. Size of the batch ('N' in layout).\n Dimension of the input.\n func : callable, default `ndarray.zeros`\n Function for creating initial state.\n... |
Please provide a description of the function:def _forward_kernel(self, F, inputs, states, **kwargs):
if self._layout == 'NTC':
inputs = F.swapaxes(inputs, dim1=0, dim2=1)
if self._projection_size is None:
params = (kwargs['{}{}_{}_{}'.format(d, l, g, t)].reshape(-1)
... | [
" forward using CUDNN or CPU kenrel"
] |
Please provide a description of the function:def wait_ssh_open(server, port, keep_waiting=None, timeout=None):
import socket
import errno
import time
log = logging.getLogger('wait_ssh_open')
sleep_s = 1
if timeout:
from time import time as now
# time module is needed to calc... | [
" Wait for network service to appear\n @param server: host to connect to (str)\n @param port: port (int)\n @param timeout: in seconds, if None or 0 wait forever\n @return: True of False, if timeout is None may return only True or\n throw unhandled network exception\n "... |
Please provide a description of the function:def wait_port_open(server, port, timeout=None):
import socket
import errno
import time
sleep_s = 0
if timeout:
from time import time as now
# time module is needed to calc timeout shared between two exceptions
end = now() + ti... | [
" Wait for network service to appear\n @param server: host to connect to (str)\n @param port: port (int)\n @param timeout: in seconds, if None or 0 wait forever\n @return: True of False, if timeout is None may return only True or\n throw unhandled network exception\n "... |
Please provide a description of the function:def print_summary(symbol, shape=None, line_length=120, positions=[.44, .64, .74, 1.]):
if not isinstance(symbol, Symbol):
raise TypeError("symbol must be Symbol")
show_shape = False
if shape is not None:
show_shape = True
interals = s... | [
"Convert symbol for detail information.\n\n Parameters\n ----------\n symbol: Symbol\n Symbol to be visualized.\n shape: dict\n A dict of shapes, str->shape (tuple), given input shapes.\n line_length: int\n Rotal length of printed lines\n positions: list\n Relative or a... |
Please provide a description of the function:def plot_network(symbol, title="plot", save_format='pdf', shape=None, dtype=None, node_attrs={},
hide_weights=True):
# todo add shape support
try:
from graphviz import Digraph
except:
raise ImportError("Draw network requires ... | [
"Creates a visualization (Graphviz digraph object) of the given computation graph.\n Graphviz must be installed for this function to work.\n\n Parameters\n ----------\n title: str, optional\n Title of the generated visualization.\n symbol: Symbol\n A symbol from the computation graph. T... |
Please provide a description of the function:def evaluate_accuracy(data_iterator, network):
acc = mx.metric.Accuracy()
# Iterate through data and label
for i, (data, label) in enumerate(data_iterator):
# Get the data and label into the GPU
data = data.as_in_context(ctx[0])
lab... | [
" Measure the accuracy of ResNet\n\n Parameters\n ----------\n data_iterator: Iter\n examples of dataset\n network:\n ResNet\n\n Returns\n ----------\n tuple of array element\n "
] |
Please provide a description of the function:def train_batch(batch_list, context, network, gluon_trainer):
# Split and load data into multiple GPUs
data = batch_list[0]
data = gluon.utils.split_and_load(data, context)
# Split and load label into multiple GPUs
label = batch_list[1]
label = ... | [
" Training with multiple GPUs\n\n Parameters\n ----------\n batch_list: List\n list of dataset\n context: List\n a list of all GPUs to be used for training\n network:\n ResNet\n gluon_trainer:\n rain module of gluon\n "
] |
Please provide a description of the function:def get_optimized_symbol(executor):
handle = SymbolHandle()
try:
check_call(_LIB.MXExecutorGetOptimizedSymbol(executor.handle, ctypes.byref(handle)))
result = sym.Symbol(handle=handle)
return result
except MXNetError:
logging.... | [
"\n Take an executor's underlying symbol graph and return its generated optimized version.\n\n Parameters\n ----------\n executor :\n An executor for which you want to see an optimized symbol. Getting an optimized symbol\n is useful to compare and verify the work TensorRT has done against ... |
Please provide a description of the function:def tensorrt_bind(symbol, ctx, all_params, type_dict=None, stype_dict=None, group2ctx=None,
**kwargs):
kwargs['shared_buffer'] = all_params
return symbol.simple_bind(ctx, type_dict=type_dict, stype_dict=stype_dict,
... | [
"Bind current symbol to get an optimized trt executor.\n\n Parameters\n ----------\n symbol : Symbol\n The symbol you wish to bind, and optimize with TensorRT.\n\n ctx : Context\n The device context the generated executor to run on.\n\n all_params : Dict of str->ndarray\n A dicti... |
Please provide a description of the function:def get_symbol(num_classes, num_layers=11, batch_norm=False, dtype='float32', **kwargs):
vgg_spec = {11: ([1, 1, 2, 2, 2], [64, 128, 256, 512, 512]),
13: ([2, 2, 2, 2, 2], [64, 128, 256, 512, 512]),
16: ([2, 2, 3, 3, 3], [64, 128, 256... | [
"\n Parameters\n ----------\n num_classes : int, default 1000\n Number of classification classes.\n num_layers : int\n Number of layers for the variant of densenet. Options are 11, 13, 16, 19.\n batch_norm : bool, default False\n Use batch normalization.\n dtype: str, float32 ... |
Please provide a description of the function:def create_batch(self, frame):
frame_resize = mx.nd.array(cv2.resize(frame, (self.data_shape[0], self.data_shape[1])))
#frame_resize = mx.img.imresize(frame, self.data_shape[0], self.data_shape[1], cv2.INTER_LINEAR)
# Change dimensions from (... | [
"\n :param frame: an (w,h,channels) numpy array (image)\n :return: DataBatch of (1,channels,data_shape,data_shape)\n "
] |
Please provide a description of the function:def detect_iter(self, det_iter, show_timer=False):
num_images = det_iter._size
if not isinstance(det_iter, mx.io.PrefetchingIter):
det_iter = mx.io.PrefetchingIter(det_iter)
start = timer()
detections = self.mod.predict(de... | [
"\n detect all images in iterator\n\n Parameters:\n ----------\n det_iter : DetIter\n iterator for all testing images\n show_timer : Boolean\n whether to print out detection exec time\n\n Returns:\n ----------\n list of detection results\... |
Please provide a description of the function:def detect_batch(self, batch):
self.mod.forward(batch, is_train=False)
detections = self.mod.get_outputs()[0]
positive_detections = Detector.filter_positive_detections(detections)
return positive_detections | [
"\n Return detections for batch\n :param batch:\n :return:\n "
] |
Please provide a description of the function:def im_detect(self, im_list, root_dir=None, extension=None, show_timer=False):
test_db = TestDB(im_list, root_dir=root_dir, extension=extension)
test_iter = DetIter(test_db, 1, self.data_shape, self.mean_pixels,
is_train=F... | [
"\n wrapper for detecting multiple images\n\n Parameters:\n ----------\n im_list : list of str\n image path or list of image paths\n root_dir : str\n directory of input images, optional if image path already\n has full directory information\n ... |
Please provide a description of the function:def visualize_detection(self, img, dets, classes=[], thresh=0.6):
import matplotlib.pyplot as plt
import random
plt.imshow(img)
height = img.shape[0]
width = img.shape[1]
colors = dict()
for det in dets:
... | [
"\n visualize detections in one image\n\n Parameters:\n ----------\n img : numpy.array\n image, in bgr format\n dets : numpy.array\n ssd detections, numpy.array([[id, score, x1, y1, x2, y2]...])\n each row is one object\n classes : tuple or ... |
Please provide a description of the function:def filter_positive_detections(detections):
class_idx = 0
assert(isinstance(detections, mx.nd.NDArray) or isinstance(detections, np.ndarray))
detections_per_image = []
# for each image
for i in range(detections.shape[0]):
... | [
"\n First column (class id) is -1 for negative detections\n :param detections:\n :return:\n "
] |
Please provide a description of the function:def detect_and_visualize(self, im_list, root_dir=None, extension=None,
classes=[], thresh=0.6, show_timer=False):
dets = self.im_detect(im_list, root_dir, extension, show_timer=show_timer)
if not isinstance(im_list, list)... | [
"\n wrapper for im_detect and visualize_detection\n\n Parameters:\n ----------\n im_list : list of str or str\n image path or list of image paths\n root_dir : str or None\n directory of input images, optional if image path already\n has full direct... |
Please provide a description of the function:def process_network_proto(caffe_root, deploy_proto):
processed_deploy_proto = deploy_proto + ".processed"
from shutil import copyfile
copyfile(deploy_proto, processed_deploy_proto)
# run upgrade tool on new file name (same output file)
import os
... | [
"\n Runs the caffe upgrade tool on the prototxt to create a prototxt in the latest format.\n This enable us to work just with latest structures, instead of supporting all the variants\n\n :param caffe_root: link to caffe root folder, where the upgrade tool is located\n :param deploy_proto: name of the o... |
Please provide a description of the function:def read_network_dag(processed_deploy_prototxt):
from caffe.proto import caffe_pb2
from google.protobuf import text_format # pylint: disable=relative-import
from collections import OrderedDict
# load prototxt file
network_def = caffe_pb2.NetParamet... | [
"\n Reads from the caffe prototxt the network structure\n :param processed_deploy_prototxt: name of prototxt to load, preferably the prototxt should\n be processed before using a call to process_network_proto()\n :return: network_def, layer_name_to_record, top_to_layers\n network_def: caffe network ... |
Please provide a description of the function:def read_caffe_mean(caffe_mean_file):
import caffe_parser
import numpy as np
mean_blob = caffe_parser.caffe_pb2.BlobProto()
with open(caffe_mean_file, 'rb') as f:
mean_blob.ParseFromString(f.read())
img_mean_np = np.array(mean_blob.data)
... | [
"\n Reads caffe formatted mean file\n :param caffe_mean_file: path to caffe mean file, presumably with 'binaryproto' suffix\n :return: mean image, converted from BGR to RGB format\n "
] |
Please provide a description of the function:def get_distance(F, x):
n = x.shape[0]
square = F.sum(x ** 2.0, axis=1, keepdims=True)
distance_square = square + square.transpose() - (2.0 * F.dot(x, x.transpose()))
# Adding identity to make sqrt work.
return F.sqrt(distance_square + F.array(np.i... | [
"Helper function for margin-based loss. Return a distance matrix given a matrix."
] |
Please provide a description of the function:def cross_entropy_loss(inputs, labels, rescale_loss=1):
criterion = mx.gluon.loss.SoftmaxCrossEntropyLoss(weight=rescale_loss)
loss = criterion(inputs, labels)
mask = S.var('mask')
loss = loss * S.reshape(mask, shape=(-1,))
return S.make_loss(loss.me... | [
" cross entropy loss with a mask "
] |
Please provide a description of the function:def rnn(bptt, vocab_size, num_embed, nhid, num_layers, dropout, num_proj, batch_size):
state_names = []
data = S.var('data')
weight = S.var("encoder_weight", stype='row_sparse')
embed = S.sparse.Embedding(data=data, weight=weight, input_dim=vocab_size,
... | [
" word embedding + LSTM Projected "
] |
Please provide a description of the function:def sampled_softmax(num_classes, num_samples, in_dim, inputs, weight, bias,
sampled_values, remove_accidental_hits=True):
# inputs = (n, in_dim)
sample, prob_sample, prob_target = sampled_values
# (num_samples, )
... | [
" Sampled softmax via importance sampling.\n This under-estimates the full softmax and is only used for training.\n "
] |
Please provide a description of the function:def generate_samples(label, num_splits, sampler):
def listify(x):
return x if isinstance(x, list) else [x]
label_splits = listify(label.split(num_splits, axis=0))
prob_samples = []
prob_targets = []
samples = []
for label_split in label_s... | [
" Split labels into `num_splits` and\n generate candidates based on log-uniform distribution.\n "
] |
Please provide a description of the function:def get_model(name, **kwargs):
models = {'resnet18_v1': resnet18_v1,
'resnet34_v1': resnet34_v1,
'resnet50_v1': resnet50_v1,
'resnet101_v1': resnet101_v1,
'resnet152_v1': resnet152_v1,
'resnet18_v... | [
"Returns a pre-defined model by name\n\n Parameters\n ----------\n name : str\n Name of the model.\n pretrained : bool\n Whether to load the pretrained weights for model.\n classes : int\n Number of classes for the output layer.\n ctx : Context, default CPU\n The contex... |
Please provide a description of the function:def _new_alloc_handle(stype, shape, ctx, delay_alloc, dtype, aux_types, aux_shapes=None):
hdl = NDArrayHandle()
for aux_t in aux_types:
if np.dtype(aux_t) != np.dtype("int64"):
raise NotImplementedError("only int64 is supported for aux types"... | [
"Return a new handle with specified storage type, shape, dtype and context.\n\n Empty handle is only used to hold results\n\n Returns\n -------\n handle\n A new empty ndarray handle\n "
] |
Please provide a description of the function:def _prepare_src_array(source_array, dtype):
if not isinstance(source_array, NDArray) and not isinstance(source_array, np.ndarray):
try:
source_array = np.array(source_array, dtype=dtype)
except:
raise TypeError('values must b... | [
"Prepare `source_array` so that it can be used to construct NDArray.\n `source_array` is converted to a `np.ndarray` if it's neither an `NDArray` \\\n nor an `np.ndarray`.\n "
] |
Please provide a description of the function:def _prepare_default_dtype(src_array, dtype):
if dtype is None:
if isinstance(src_array, (NDArray, np.ndarray)):
dtype = src_array.dtype
elif spsp and isinstance(src_array, spsp.csr.csr_matrix):
dtype = src_array.dtype
... | [
"Prepare the value of dtype if `dtype` is None. If `src_array` is an NDArray, numpy.ndarray\n or scipy.sparse.csr.csr_matrix, return src_array.dtype. float32 is returned otherwise."
] |
Please provide a description of the function:def _check_shape(s1, s2):
if s1 and s2 and s1 != s2:
raise ValueError("Shape mismatch detected. " + str(s1) + " v.s. " + str(s2)) | [
"check s1 == s2 if both are not None"
] |
Please provide a description of the function:def csr_matrix(arg1, shape=None, ctx=None, dtype=None):
# construct a csr matrix from (M, N) or (data, indices, indptr)
if isinstance(arg1, tuple):
arg_len = len(arg1)
if arg_len == 2:
# construct a sparse csr matrix from
... | [
"Creates a `CSRNDArray`, an 2D array with compressed sparse row (CSR) format.\n\n The CSRNDArray can be instantiated in several ways:\n\n - csr_matrix(D):\n to construct a CSRNDArray with a dense 2D array ``D``\n - **D** (*array_like*) - An object exposing the array interface, an object who... |
Please provide a description of the function:def _csr_matrix_from_definition(data, indices, indptr, shape=None, ctx=None,
dtype=None, indices_type=None, indptr_type=None):
# pylint: disable= no-member, protected-access
storage_type = 'csr'
# context
ctx = current_con... | [
"Create a `CSRNDArray` based on data, indices and indptr"
] |
Please provide a description of the function:def row_sparse_array(arg1, shape=None, ctx=None, dtype=None):
# construct a row sparse array from (D0, D1 ..) or (data, indices)
if isinstance(arg1, tuple):
arg_len = len(arg1)
if arg_len < 2:
raise ValueError("Unexpected length of in... | [
"Creates a `RowSparseNDArray`, a multidimensional row sparse array with a set of \\\n tensor slices at given indices.\n\n The RowSparseNDArray can be instantiated in several ways:\n\n - row_sparse_array(D):\n to construct a RowSparseNDArray with a dense ndarray ``D``\n - **D** (*array_like*)... |
Please provide a description of the function:def _row_sparse_ndarray_from_definition(data, indices, shape=None, ctx=None,
dtype=None, indices_type=None):
storage_type = 'row_sparse'
# context
ctx = current_context() if ctx is None else ctx
# types
dtype =... | [
"Create a `RowSparseNDArray` based on data and indices"
] |
Please provide a description of the function:def add(lhs, rhs):
# pylint: disable= no-member, protected-access
if isinstance(lhs, NDArray) and isinstance(rhs, NDArray) and lhs.shape == rhs.shape:
return _ufunc_helper(
lhs,
rhs,
op.elemwise_add,
operat... | [
"Returns element-wise sum of the input arrays with broadcasting.\n\n Equivalent to ``lhs + rhs``, ``mx.nd.broadcast_add(lhs, rhs)`` and\n ``mx.nd.broadcast_plus(lhs, rhs)`` when shapes of lhs and rhs do not\n match. If lhs.shape == rhs.shape, this is equivalent to\n ``mx.nd.elemwise_add(lhs, rhs)``\n\n ... |
Please provide a description of the function:def subtract(lhs, rhs):
# pylint: disable= no-member, protected-access
if isinstance(lhs, NDArray) and isinstance(rhs, NDArray) and lhs.shape == rhs.shape:
return _ufunc_helper(
lhs,
rhs,
op.elemwise_sub,
o... | [
"Returns element-wise difference of the input arrays with broadcasting.\n\n Equivalent to ``lhs - rhs``, ``mx.nd.broadcast_sub(lhs, rhs)`` and\n ``mx.nd.broadcast_minus(lhs, rhs)`` when shapes of lhs and rhs do not\n match. If lhs.shape == rhs.shape, this is equivalent to\n ``mx.nd.elemwise_sub(lhs, rhs... |
Please provide a description of the function:def multiply(lhs, rhs):
# pylint: disable= no-member, protected-access
if isinstance(lhs, NDArray) and isinstance(rhs, NDArray) and lhs.shape == rhs.shape:
return _ufunc_helper(
lhs,
rhs,
op.elemwise_mul,
o... | [
"Returns element-wise product of the input arrays with broadcasting.\n\n Equivalent to ``lhs * rhs`` and ``mx.nd.broadcast_mul(lhs, rhs)``\n when shapes of lhs and rhs do not match. If lhs.shape == rhs.shape,\n this is equivalent to ``mx.nd.elemwise_mul(lhs, rhs)``\n\n .. note::\n\n I... |
Please provide a description of the function:def divide(lhs, rhs):
# pylint: disable= no-member, protected-access
if isinstance(lhs, NDArray) and isinstance(rhs, NDArray) and lhs.shape == rhs.shape:
return _ufunc_helper(
lhs,
rhs,
op.elemwise_div,
ope... | [
"Returns element-wise division of the input arrays with broadcasting.\n\n Equivalent to ``lhs / rhs`` and ``mx.nd.broadcast_div(lhs, rhs)``\n when shapes of lhs and rhs do not match. If lhs.shape == rhs.shape,\n this is equivalent to ``mx.nd.elemwise_div(lhs, rhs)``\n\n .. note::\n\n If the corre... |
Please provide a description of the function:def zeros(stype, shape, ctx=None, dtype=None, **kwargs):
# pylint: disable= no-member, protected-access
if stype == 'default':
return _zeros_ndarray(shape, ctx=ctx, dtype=dtype, **kwargs)
if ctx is None:
ctx = current_context()
dtype = mx... | [
"Return a new array of given shape and type, filled with zeros.\n\n Parameters\n ----------\n stype: string\n The storage type of the empty array, such as 'row_sparse', 'csr', etc\n shape : int or tuple of int\n The shape of the empty array\n ctx : Context, optional\n An optional... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.