id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
23,900
apache/incubator-mxnet
example/gluon/lipnet/BeamSearch.py
BeamState.sort
def sort(self): """ return beam-labelings, sorted by probability """ beams = [v for (_, v) in self.entries.items()] sortedBeams = sorted(beams, reverse=True, key=lambda x: x.prTotal*x.prText) return [x.labeling for x in sortedBeams]
python
def sort(self): """ return beam-labelings, sorted by probability """ beams = [v for (_, v) in self.entries.items()] sortedBeams = sorted(beams, reverse=True, key=lambda x: x.prTotal*x.prText) return [x.labeling for x in sortedBeams]
[ "def", "sort", "(", "self", ")", ":", "beams", "=", "[", "v", "for", "(", "_", ",", "v", ")", "in", "self", ".", "entries", ".", "items", "(", ")", "]", "sortedBeams", "=", "sorted", "(", "beams", ",", "reverse", "=", "True", ",", "key", "=", ...
return beam-labelings, sorted by probability
[ "return", "beam", "-", "labelings", "sorted", "by", "probability" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/gluon/lipnet/BeamSearch.py#L56-L62
23,901
apache/incubator-mxnet
example/image-classification/symbols/lenet.py
get_loc
def get_loc(data, attr={'lr_mult':'0.01'}): """ the localisation network in lenet-stn, it will increase acc about more than 1%, when num-epoch >=15 """ loc = mx.symbol.Convolution(data=data, num_filter=30, kernel=(5, 5), stride=(2,2)) loc = mx.symbol.Activation(data = loc, act_type='relu') l...
python
def get_loc(data, attr={'lr_mult':'0.01'}): """ the localisation network in lenet-stn, it will increase acc about more than 1%, when num-epoch >=15 """ loc = mx.symbol.Convolution(data=data, num_filter=30, kernel=(5, 5), stride=(2,2)) loc = mx.symbol.Activation(data = loc, act_type='relu') l...
[ "def", "get_loc", "(", "data", ",", "attr", "=", "{", "'lr_mult'", ":", "'0.01'", "}", ")", ":", "loc", "=", "mx", ".", "symbol", ".", "Convolution", "(", "data", "=", "data", ",", "num_filter", "=", "30", ",", "kernel", "=", "(", "5", ",", "5", ...
the localisation network in lenet-stn, it will increase acc about more than 1%, when num-epoch >=15
[ "the", "localisation", "network", "in", "lenet", "-", "stn", "it", "will", "increase", "acc", "about", "more", "than", "1%", "when", "num", "-", "epoch", ">", "=", "15" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/image-classification/symbols/lenet.py#L25-L38
23,902
apache/incubator-mxnet
example/ssd/demo.py
get_detector
def get_detector(net, prefix, epoch, data_shape, mean_pixels, ctx, num_class, nms_thresh=0.5, force_nms=True, nms_topk=400): """ wrapper for initialize a detector Parameters: ---------- net : str test network name prefix : str load model prefix epoch : int ...
python
def get_detector(net, prefix, epoch, data_shape, mean_pixels, ctx, num_class, nms_thresh=0.5, force_nms=True, nms_topk=400): """ wrapper for initialize a detector Parameters: ---------- net : str test network name prefix : str load model prefix epoch : int ...
[ "def", "get_detector", "(", "net", ",", "prefix", ",", "epoch", ",", "data_shape", ",", "mean_pixels", ",", "ctx", ",", "num_class", ",", "nms_thresh", "=", "0.5", ",", "force_nms", "=", "True", ",", "nms_topk", "=", "400", ")", ":", "if", "net", "is",...
wrapper for initialize a detector Parameters: ---------- net : str test network name prefix : str load model prefix epoch : int load model epoch data_shape : int resize image shape mean_pixels : tuple (float, float, float) mean pixel values (R, G, B) ...
[ "wrapper", "for", "initialize", "a", "detector" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/ssd/demo.py#L32-L64
23,903
apache/incubator-mxnet
example/ssd/demo.py
parse_data_shape
def parse_data_shape(data_shape_str): """Parse string to tuple or int""" ds = data_shape_str.strip().split(',') if len(ds) == 1: data_shape = (int(ds[0]), int(ds[0])) elif len(ds) == 2: data_shape = (int(ds[0]), int(ds[1])) else: raise ValueError("Unexpected data_shape: %s", ...
python
def parse_data_shape(data_shape_str): """Parse string to tuple or int""" ds = data_shape_str.strip().split(',') if len(ds) == 1: data_shape = (int(ds[0]), int(ds[0])) elif len(ds) == 2: data_shape = (int(ds[0]), int(ds[1])) else: raise ValueError("Unexpected data_shape: %s", ...
[ "def", "parse_data_shape", "(", "data_shape_str", ")", ":", "ds", "=", "data_shape_str", ".", "strip", "(", ")", ".", "split", "(", "','", ")", "if", "len", "(", "ds", ")", "==", "1", ":", "data_shape", "=", "(", "int", "(", "ds", "[", "0", "]", ...
Parse string to tuple or int
[ "Parse", "string", "to", "tuple", "or", "int" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/ssd/demo.py#L141-L150
23,904
apache/incubator-mxnet
example/kaggle-ndsb2/Train.py
get_lenet
def get_lenet(): """ A lenet style net, takes difference of each frame as input. """ source = mx.sym.Variable("data") source = (source - 128) * (1.0/128) frames = mx.sym.SliceChannel(source, num_outputs=30) diffs = [frames[i+1] - frames[i] for i in range(29)] source = mx.sym.Concat(*diffs) ...
python
def get_lenet(): """ A lenet style net, takes difference of each frame as input. """ source = mx.sym.Variable("data") source = (source - 128) * (1.0/128) frames = mx.sym.SliceChannel(source, num_outputs=30) diffs = [frames[i+1] - frames[i] for i in range(29)] source = mx.sym.Concat(*diffs) ...
[ "def", "get_lenet", "(", ")", ":", "source", "=", "mx", ".", "sym", ".", "Variable", "(", "\"data\"", ")", "source", "=", "(", "source", "-", "128", ")", "*", "(", "1.0", "/", "128", ")", "frames", "=", "mx", ".", "sym", ".", "SliceChannel", "(",...
A lenet style net, takes difference of each frame as input.
[ "A", "lenet", "style", "net", "takes", "difference", "of", "each", "frame", "as", "input", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/kaggle-ndsb2/Train.py#L33-L55
23,905
apache/incubator-mxnet
example/kaggle-ndsb2/Train.py
CRPS
def CRPS(label, pred): """ Custom evaluation metric on CRPS. """ for i in range(pred.shape[0]): for j in range(pred.shape[1] - 1): if pred[i, j] > pred[i, j + 1]: pred[i, j + 1] = pred[i, j] return np.sum(np.square(label - pred)) / label.size
python
def CRPS(label, pred): """ Custom evaluation metric on CRPS. """ for i in range(pred.shape[0]): for j in range(pred.shape[1] - 1): if pred[i, j] > pred[i, j + 1]: pred[i, j + 1] = pred[i, j] return np.sum(np.square(label - pred)) / label.size
[ "def", "CRPS", "(", "label", ",", "pred", ")", ":", "for", "i", "in", "range", "(", "pred", ".", "shape", "[", "0", "]", ")", ":", "for", "j", "in", "range", "(", "pred", ".", "shape", "[", "1", "]", "-", "1", ")", ":", "if", "pred", "[", ...
Custom evaluation metric on CRPS.
[ "Custom", "evaluation", "metric", "on", "CRPS", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/kaggle-ndsb2/Train.py#L57-L64
23,906
apache/incubator-mxnet
example/kaggle-ndsb2/Train.py
encode_label
def encode_label(label_data): """Run encoding to encode the label into the CDF target. """ systole = label_data[:, 1] diastole = label_data[:, 2] systole_encode = np.array([ (x < np.arange(600)) for x in systole ], dtype=np.uint8) diastole_encode = np.array([ (x <...
python
def encode_label(label_data): """Run encoding to encode the label into the CDF target. """ systole = label_data[:, 1] diastole = label_data[:, 2] systole_encode = np.array([ (x < np.arange(600)) for x in systole ], dtype=np.uint8) diastole_encode = np.array([ (x <...
[ "def", "encode_label", "(", "label_data", ")", ":", "systole", "=", "label_data", "[", ":", ",", "1", "]", "diastole", "=", "label_data", "[", ":", ",", "2", "]", "systole_encode", "=", "np", ".", "array", "(", "[", "(", "x", "<", "np", ".", "arang...
Run encoding to encode the label into the CDF target.
[ "Run", "encoding", "to", "encode", "the", "label", "into", "the", "CDF", "target", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/kaggle-ndsb2/Train.py#L69-L80
23,907
apache/incubator-mxnet
python/mxnet/ndarray/contrib.py
foreach
def foreach(body, data, init_states): """Run a for loop with user-defined computation over NDArrays on dimension 0. This operator simulates a for loop and body has the computation for an iteration of the for loop. It runs the computation in body on each slice from the input NDArrays. body takes tw...
python
def foreach(body, data, init_states): """Run a for loop with user-defined computation over NDArrays on dimension 0. This operator simulates a for loop and body has the computation for an iteration of the for loop. It runs the computation in body on each slice from the input NDArrays. body takes tw...
[ "def", "foreach", "(", "body", ",", "data", ",", "init_states", ")", ":", "def", "check_input", "(", "inputs", ",", "in_type", ",", "msg", ")", ":", "is_NDArray_or_list", "=", "True", "if", "isinstance", "(", "inputs", ",", "list", ")", ":", "for", "i"...
Run a for loop with user-defined computation over NDArrays on dimension 0. This operator simulates a for loop and body has the computation for an iteration of the for loop. It runs the computation in body on each slice from the input NDArrays. body takes two arguments as input and outputs a tuple of t...
[ "Run", "a", "for", "loop", "with", "user", "-", "defined", "computation", "over", "NDArrays", "on", "dimension", "0", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/ndarray/contrib.py#L136-L230
23,908
apache/incubator-mxnet
python/mxnet/ndarray/contrib.py
isfinite
def isfinite(data): """Performs an element-wise check to determine if the NDArray contains an infinite element or not. Parameters ---------- input : NDArray An N-D NDArray. Returns ------- output: NDArray The output NDarray, with same shape as input, where 1 indicates ...
python
def isfinite(data): """Performs an element-wise check to determine if the NDArray contains an infinite element or not. Parameters ---------- input : NDArray An N-D NDArray. Returns ------- output: NDArray The output NDarray, with same shape as input, where 1 indicates ...
[ "def", "isfinite", "(", "data", ")", ":", "is_data_not_nan", "=", "data", "==", "data", "is_data_not_infinite", "=", "data", ".", "abs", "(", ")", "!=", "np", ".", "inf", "return", "ndarray", ".", "logical_and", "(", "is_data_not_infinite", ",", "is_data_not...
Performs an element-wise check to determine if the NDArray contains an infinite element or not. Parameters ---------- input : NDArray An N-D NDArray. Returns ------- output: NDArray The output NDarray, with same shape as input, where 1 indicates the array element is ...
[ "Performs", "an", "element", "-", "wise", "check", "to", "determine", "if", "the", "NDArray", "contains", "an", "infinite", "element", "or", "not", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/ndarray/contrib.py#L492-L519
23,909
apache/incubator-mxnet
example/rcnn/symdata/image.py
imdecode
def imdecode(image_path): """Return BGR image read by opencv""" import os assert os.path.exists(image_path), image_path + ' not found' im = cv2.imread(image_path) return im
python
def imdecode(image_path): """Return BGR image read by opencv""" import os assert os.path.exists(image_path), image_path + ' not found' im = cv2.imread(image_path) return im
[ "def", "imdecode", "(", "image_path", ")", ":", "import", "os", "assert", "os", ".", "path", ".", "exists", "(", "image_path", ")", ",", "image_path", "+", "' not found'", "im", "=", "cv2", ".", "imread", "(", "image_path", ")", "return", "im" ]
Return BGR image read by opencv
[ "Return", "BGR", "image", "read", "by", "opencv" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/rcnn/symdata/image.py#L52-L57
23,910
apache/incubator-mxnet
example/gluon/embedding_learning/train.py
get_distance_matrix
def get_distance_matrix(x): """Get distance matrix given a matrix. Used in testing.""" square = nd.sum(x ** 2.0, axis=1, keepdims=True) distance_square = square + square.transpose() - (2.0 * nd.dot(x, x.transpose())) return nd.sqrt(distance_square)
python
def get_distance_matrix(x): """Get distance matrix given a matrix. Used in testing.""" square = nd.sum(x ** 2.0, axis=1, keepdims=True) distance_square = square + square.transpose() - (2.0 * nd.dot(x, x.transpose())) return nd.sqrt(distance_square)
[ "def", "get_distance_matrix", "(", "x", ")", ":", "square", "=", "nd", ".", "sum", "(", "x", "**", "2.0", ",", "axis", "=", "1", ",", "keepdims", "=", "True", ")", "distance_square", "=", "square", "+", "square", ".", "transpose", "(", ")", "-", "(...
Get distance matrix given a matrix. Used in testing.
[ "Get", "distance", "matrix", "given", "a", "matrix", ".", "Used", "in", "testing", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/gluon/embedding_learning/train.py#L116-L120
23,911
apache/incubator-mxnet
example/gluon/embedding_learning/train.py
evaluate_emb
def evaluate_emb(emb, labels): """Evaluate embeddings based on Recall@k.""" d_mat = get_distance_matrix(emb) d_mat = d_mat.asnumpy() labels = labels.asnumpy() names = [] accs = [] for k in [1, 2, 4, 8, 16]: names.append('Recall@%d' % k) correct, cnt = 0.0, 0.0 for i ...
python
def evaluate_emb(emb, labels): """Evaluate embeddings based on Recall@k.""" d_mat = get_distance_matrix(emb) d_mat = d_mat.asnumpy() labels = labels.asnumpy() names = [] accs = [] for k in [1, 2, 4, 8, 16]: names.append('Recall@%d' % k) correct, cnt = 0.0, 0.0 for i ...
[ "def", "evaluate_emb", "(", "emb", ",", "labels", ")", ":", "d_mat", "=", "get_distance_matrix", "(", "emb", ")", "d_mat", "=", "d_mat", ".", "asnumpy", "(", ")", "labels", "=", "labels", ".", "asnumpy", "(", ")", "names", "=", "[", "]", "accs", "=",...
Evaluate embeddings based on Recall@k.
[ "Evaluate", "embeddings", "based", "on", "Recall" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/gluon/embedding_learning/train.py#L123-L141
23,912
apache/incubator-mxnet
example/gluon/embedding_learning/train.py
get_lr
def get_lr(lr, epoch, steps, factor): """Get learning rate based on schedule.""" for s in steps: if epoch >= s: lr *= factor return lr
python
def get_lr(lr, epoch, steps, factor): """Get learning rate based on schedule.""" for s in steps: if epoch >= s: lr *= factor return lr
[ "def", "get_lr", "(", "lr", ",", "epoch", ",", "steps", ",", "factor", ")", ":", "for", "s", "in", "steps", ":", "if", "epoch", ">=", "s", ":", "lr", "*=", "factor", "return", "lr" ]
Get learning rate based on schedule.
[ "Get", "learning", "rate", "based", "on", "schedule", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/gluon/embedding_learning/train.py#L161-L166
23,913
apache/incubator-mxnet
example/ctc/lstm.py
_add_warp_ctc_loss
def _add_warp_ctc_loss(pred, seq_len, num_label, label): """ Adds Symbol.contrib.ctc_loss on top of pred symbol and returns the resulting symbol """ label = mx.sym.Reshape(data=label, shape=(-1,)) label = mx.sym.Cast(data=label, dtype='int32') return mx.sym.WarpCTC(data=pred, label=label, label_length=n...
python
def _add_warp_ctc_loss(pred, seq_len, num_label, label): """ Adds Symbol.contrib.ctc_loss on top of pred symbol and returns the resulting symbol """ label = mx.sym.Reshape(data=label, shape=(-1,)) label = mx.sym.Cast(data=label, dtype='int32') return mx.sym.WarpCTC(data=pred, label=label, label_length=n...
[ "def", "_add_warp_ctc_loss", "(", "pred", ",", "seq_len", ",", "num_label", ",", "label", ")", ":", "label", "=", "mx", ".", "sym", ".", "Reshape", "(", "data", "=", "label", ",", "shape", "=", "(", "-", "1", ",", ")", ")", "label", "=", "mx", "....
Adds Symbol.contrib.ctc_loss on top of pred symbol and returns the resulting symbol
[ "Adds", "Symbol", ".", "contrib", ".", "ctc_loss", "on", "top", "of", "pred", "symbol", "and", "returns", "the", "resulting", "symbol" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/ctc/lstm.py#L96-L100
23,914
apache/incubator-mxnet
example/ctc/lstm.py
_add_mxnet_ctc_loss
def _add_mxnet_ctc_loss(pred, seq_len, label): """ Adds Symbol.WapCTC on top of pred symbol and returns the resulting symbol """ pred_ctc = mx.sym.Reshape(data=pred, shape=(-4, seq_len, -1, 0)) loss = mx.sym.contrib.ctc_loss(data=pred_ctc, label=label) ctc_loss = mx.sym.MakeLoss(loss) softmax_clas...
python
def _add_mxnet_ctc_loss(pred, seq_len, label): """ Adds Symbol.WapCTC on top of pred symbol and returns the resulting symbol """ pred_ctc = mx.sym.Reshape(data=pred, shape=(-4, seq_len, -1, 0)) loss = mx.sym.contrib.ctc_loss(data=pred_ctc, label=label) ctc_loss = mx.sym.MakeLoss(loss) softmax_clas...
[ "def", "_add_mxnet_ctc_loss", "(", "pred", ",", "seq_len", ",", "label", ")", ":", "pred_ctc", "=", "mx", ".", "sym", ".", "Reshape", "(", "data", "=", "pred", ",", "shape", "=", "(", "-", "4", ",", "seq_len", ",", "-", "1", ",", "0", ")", ")", ...
Adds Symbol.WapCTC on top of pred symbol and returns the resulting symbol
[ "Adds", "Symbol", ".", "WapCTC", "on", "top", "of", "pred", "symbol", "and", "returns", "the", "resulting", "symbol" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/ctc/lstm.py#L103-L113
23,915
apache/incubator-mxnet
example/ctc/lstm.py
_add_ctc_loss
def _add_ctc_loss(pred, seq_len, num_label, loss_type): """ Adds CTC loss on top of pred symbol and returns the resulting symbol """ label = mx.sym.Variable('label') if loss_type == 'warpctc': print("Using WarpCTC Loss") sm = _add_warp_ctc_loss(pred, seq_len, num_label, label) else: ...
python
def _add_ctc_loss(pred, seq_len, num_label, loss_type): """ Adds CTC loss on top of pred symbol and returns the resulting symbol """ label = mx.sym.Variable('label') if loss_type == 'warpctc': print("Using WarpCTC Loss") sm = _add_warp_ctc_loss(pred, seq_len, num_label, label) else: ...
[ "def", "_add_ctc_loss", "(", "pred", ",", "seq_len", ",", "num_label", ",", "loss_type", ")", ":", "label", "=", "mx", ".", "sym", ".", "Variable", "(", "'label'", ")", "if", "loss_type", "==", "'warpctc'", ":", "print", "(", "\"Using WarpCTC Loss\"", ")",...
Adds CTC loss on top of pred symbol and returns the resulting symbol
[ "Adds", "CTC", "loss", "on", "top", "of", "pred", "symbol", "and", "returns", "the", "resulting", "symbol" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/ctc/lstm.py#L116-L126
23,916
apache/incubator-mxnet
example/ctc/lstm.py
lstm_unroll
def lstm_unroll(num_lstm_layer, seq_len, num_hidden, num_label, loss_type=None): """ Creates an unrolled LSTM symbol for inference if loss_type is not specified, and for training if loss_type is specified. loss_type must be one of 'ctc' or 'warpctc' Parameters ---------- num_lstm_layer: int ...
python
def lstm_unroll(num_lstm_layer, seq_len, num_hidden, num_label, loss_type=None): """ Creates an unrolled LSTM symbol for inference if loss_type is not specified, and for training if loss_type is specified. loss_type must be one of 'ctc' or 'warpctc' Parameters ---------- num_lstm_layer: int ...
[ "def", "lstm_unroll", "(", "num_lstm_layer", ",", "seq_len", ",", "num_hidden", ",", "num_label", ",", "loss_type", "=", "None", ")", ":", "# Create the base (shared between training and inference) and add loss to the end", "pred", "=", "_lstm_unroll_base", "(", "num_lstm_l...
Creates an unrolled LSTM symbol for inference if loss_type is not specified, and for training if loss_type is specified. loss_type must be one of 'ctc' or 'warpctc' Parameters ---------- num_lstm_layer: int seq_len: int num_hidden: int num_label: int loss_type: str 'ctc' or 'war...
[ "Creates", "an", "unrolled", "LSTM", "symbol", "for", "inference", "if", "loss_type", "is", "not", "specified", "and", "for", "training", "if", "loss_type", "is", "specified", ".", "loss_type", "must", "be", "one", "of", "ctc", "or", "warpctc" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/ctc/lstm.py#L129-L155
23,917
apache/incubator-mxnet
example/ctc/lstm.py
init_states
def init_states(batch_size, num_lstm_layer, num_hidden): """ Returns name and shape of init states of LSTM network Parameters ---------- batch_size: list of tuple of str and tuple of int and int num_lstm_layer: int num_hidden: int Returns ------- list of tuple of str and tuple ...
python
def init_states(batch_size, num_lstm_layer, num_hidden): """ Returns name and shape of init states of LSTM network Parameters ---------- batch_size: list of tuple of str and tuple of int and int num_lstm_layer: int num_hidden: int Returns ------- list of tuple of str and tuple ...
[ "def", "init_states", "(", "batch_size", ",", "num_lstm_layer", ",", "num_hidden", ")", ":", "init_c", "=", "[", "(", "'l%d_init_c'", "%", "l", ",", "(", "batch_size", ",", "num_hidden", ")", ")", "for", "l", "in", "range", "(", "num_lstm_layer", ")", "]...
Returns name and shape of init states of LSTM network Parameters ---------- batch_size: list of tuple of str and tuple of int and int num_lstm_layer: int num_hidden: int Returns ------- list of tuple of str and tuple of int and int
[ "Returns", "name", "and", "shape", "of", "init", "states", "of", "LSTM", "network" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/ctc/lstm.py#L158-L174
23,918
apache/incubator-mxnet
python/mxnet/_ctypes/ndarray.py
_imperative_invoke
def _imperative_invoke(handle, ndargs, keys, vals, out): """ctypes implementation of imperative invoke wrapper""" if out is not None: original_output = out if isinstance(out, NDArrayBase): out = (out,) num_output = ctypes.c_int(len(out)) output_vars = c_handle_array(o...
python
def _imperative_invoke(handle, ndargs, keys, vals, out): """ctypes implementation of imperative invoke wrapper""" if out is not None: original_output = out if isinstance(out, NDArrayBase): out = (out,) num_output = ctypes.c_int(len(out)) output_vars = c_handle_array(o...
[ "def", "_imperative_invoke", "(", "handle", ",", "ndargs", ",", "keys", ",", "vals", ",", "out", ")", ":", "if", "out", "is", "not", "None", ":", "original_output", "=", "out", "if", "isinstance", "(", "out", ",", "NDArrayBase", ")", ":", "out", "=", ...
ctypes implementation of imperative invoke wrapper
[ "ctypes", "implementation", "of", "imperative", "invoke", "wrapper" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/_ctypes/ndarray.py#L65-L102
23,919
apache/incubator-mxnet
python/mxnet/contrib/autograd.py
backward
def backward(outputs, out_grads=None, retain_graph=False): """Compute the gradients of outputs w.r.t variables. Parameters ---------- outputs: list of NDArray out_grads: list of NDArray or None """ assert isinstance(outputs, (list, tuple)), \ "outputs must be a list or tuple of NDAr...
python
def backward(outputs, out_grads=None, retain_graph=False): """Compute the gradients of outputs w.r.t variables. Parameters ---------- outputs: list of NDArray out_grads: list of NDArray or None """ assert isinstance(outputs, (list, tuple)), \ "outputs must be a list or tuple of NDAr...
[ "def", "backward", "(", "outputs", ",", "out_grads", "=", "None", ",", "retain_graph", "=", "False", ")", ":", "assert", "isinstance", "(", "outputs", ",", "(", "list", ",", "tuple", ")", ")", ",", "\"outputs must be a list or tuple of NDArrays\"", "if", "out_...
Compute the gradients of outputs w.r.t variables. Parameters ---------- outputs: list of NDArray out_grads: list of NDArray or None
[ "Compute", "the", "gradients", "of", "outputs", "w", ".", "r", ".", "t", "variables", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/contrib/autograd.py#L123-L155
23,920
apache/incubator-mxnet
python/mxnet/contrib/autograd.py
grad_and_loss
def grad_and_loss(func, argnum=None): """Return function that computes both gradient of arguments and loss value. Parameters ---------- func: a python function The forward (loss) function. argnum: an int or a list of int The index of argument to calculate gradient for. Returns ...
python
def grad_and_loss(func, argnum=None): """Return function that computes both gradient of arguments and loss value. Parameters ---------- func: a python function The forward (loss) function. argnum: an int or a list of int The index of argument to calculate gradient for. Returns ...
[ "def", "grad_and_loss", "(", "func", ",", "argnum", "=", "None", ")", ":", "@", "functools", ".", "wraps", "(", "func", ")", "def", "wrapped", "(", "*", "args", ")", ":", "\"\"\"Wrapped function.\"\"\"", "variables", "=", "args", "if", "argnum", "is", "n...
Return function that computes both gradient of arguments and loss value. Parameters ---------- func: a python function The forward (loss) function. argnum: an int or a list of int The index of argument to calculate gradient for. Returns ------- grad_and_loss_func: a python ...
[ "Return", "function", "that", "computes", "both", "gradient", "of", "arguments", "and", "loss", "value", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/contrib/autograd.py#L163-L193
23,921
apache/incubator-mxnet
python/mxnet/contrib/autograd.py
grad
def grad(func, argnum=None): """Return function that computes gradient of arguments. Parameters ---------- func: a python function The forward (loss) function. argnum: an int or a list of int The index of argument to calculate gradient for. Returns ------- grad_func: a ...
python
def grad(func, argnum=None): """Return function that computes gradient of arguments. Parameters ---------- func: a python function The forward (loss) function. argnum: an int or a list of int The index of argument to calculate gradient for. Returns ------- grad_func: a ...
[ "def", "grad", "(", "func", ",", "argnum", "=", "None", ")", ":", "grad_with_loss_func", "=", "grad_and_loss", "(", "func", ",", "argnum", ")", "@", "functools", ".", "wraps", "(", "grad_with_loss_func", ")", "def", "wrapped", "(", "*", "args", ")", ":",...
Return function that computes gradient of arguments. Parameters ---------- func: a python function The forward (loss) function. argnum: an int or a list of int The index of argument to calculate gradient for. Returns ------- grad_func: a python function A function t...
[ "Return", "function", "that", "computes", "gradient", "of", "arguments", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/contrib/autograd.py#L195-L230
23,922
apache/incubator-mxnet
python/mxnet/gluon/utils.py
clip_global_norm
def clip_global_norm(arrays, max_norm, check_isfinite=True): """Rescales NDArrays so that the sum of their 2-norm is smaller than `max_norm`. Parameters ---------- arrays : list of NDArray max_norm : float check_isfinite : bool, default True If True, check that the total_norm is finite...
python
def clip_global_norm(arrays, max_norm, check_isfinite=True): """Rescales NDArrays so that the sum of their 2-norm is smaller than `max_norm`. Parameters ---------- arrays : list of NDArray max_norm : float check_isfinite : bool, default True If True, check that the total_norm is finite...
[ "def", "clip_global_norm", "(", "arrays", ",", "max_norm", ",", "check_isfinite", "=", "True", ")", ":", "def", "_norm", "(", "array", ")", ":", "if", "array", ".", "stype", "==", "'default'", ":", "x", "=", "array", ".", "reshape", "(", "(", "-", "1...
Rescales NDArrays so that the sum of their 2-norm is smaller than `max_norm`. Parameters ---------- arrays : list of NDArray max_norm : float check_isfinite : bool, default True If True, check that the total_norm is finite (not nan or inf). This requires a blocking .asscalar() cal...
[ "Rescales", "NDArrays", "so", "that", "the", "sum", "of", "their", "2", "-", "norm", "is", "smaller", "than", "max_norm", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/gluon/utils.py#L122-L161
23,923
apache/incubator-mxnet
python/mxnet/gluon/utils.py
check_sha1
def check_sha1(filename, sha1_hash): """Check whether the sha1 hash of the file content matches the expected hash. Parameters ---------- filename : str Path to the file. sha1_hash : str Expected sha1 hash in hexadecimal digits. Returns ------- bool Whether the f...
python
def check_sha1(filename, sha1_hash): """Check whether the sha1 hash of the file content matches the expected hash. Parameters ---------- filename : str Path to the file. sha1_hash : str Expected sha1 hash in hexadecimal digits. Returns ------- bool Whether the f...
[ "def", "check_sha1", "(", "filename", ",", "sha1_hash", ")", ":", "sha1", "=", "hashlib", ".", "sha1", "(", ")", "with", "open", "(", "filename", ",", "'rb'", ")", "as", "f", ":", "while", "True", ":", "data", "=", "f", ".", "read", "(", "1048576",...
Check whether the sha1 hash of the file content matches the expected hash. Parameters ---------- filename : str Path to the file. sha1_hash : str Expected sha1 hash in hexadecimal digits. Returns ------- bool Whether the file content matches the expected hash.
[ "Check", "whether", "the", "sha1", "hash", "of", "the", "file", "content", "matches", "the", "expected", "hash", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/gluon/utils.py#L176-L199
23,924
apache/incubator-mxnet
python/mxnet/gluon/utils.py
download
def download(url, path=None, overwrite=False, sha1_hash=None, retries=5, verify_ssl=True): """Download an given URL Parameters ---------- url : str URL to download path : str, optional Destination path to store downloaded file. By default stores to the current directory with...
python
def download(url, path=None, overwrite=False, sha1_hash=None, retries=5, verify_ssl=True): """Download an given URL Parameters ---------- url : str URL to download path : str, optional Destination path to store downloaded file. By default stores to the current directory with...
[ "def", "download", "(", "url", ",", "path", "=", "None", ",", "overwrite", "=", "False", ",", "sha1_hash", "=", "None", ",", "retries", "=", "5", ",", "verify_ssl", "=", "True", ")", ":", "if", "path", "is", "None", ":", "fname", "=", "url", ".", ...
Download an given URL Parameters ---------- url : str URL to download path : str, optional Destination path to store downloaded file. By default stores to the current directory with same name as in url. overwrite : bool, optional Whether to overwrite destination file...
[ "Download", "an", "given", "URL" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/gluon/utils.py#L258-L349
23,925
apache/incubator-mxnet
python/mxnet/gluon/utils.py
_get_repo_url
def _get_repo_url(): """Return the base URL for Gluon dataset and model repository.""" default_repo = 'https://apache-mxnet.s3-accelerate.dualstack.amazonaws.com/' repo_url = os.environ.get('MXNET_GLUON_REPO', default_repo) if repo_url[-1] != '/': repo_url = repo_url+'/' return repo_url
python
def _get_repo_url(): """Return the base URL for Gluon dataset and model repository.""" default_repo = 'https://apache-mxnet.s3-accelerate.dualstack.amazonaws.com/' repo_url = os.environ.get('MXNET_GLUON_REPO', default_repo) if repo_url[-1] != '/': repo_url = repo_url+'/' return repo_url
[ "def", "_get_repo_url", "(", ")", ":", "default_repo", "=", "'https://apache-mxnet.s3-accelerate.dualstack.amazonaws.com/'", "repo_url", "=", "os", ".", "environ", ".", "get", "(", "'MXNET_GLUON_REPO'", ",", "default_repo", ")", "if", "repo_url", "[", "-", "1", "]",...
Return the base URL for Gluon dataset and model repository.
[ "Return", "the", "base", "URL", "for", "Gluon", "dataset", "and", "model", "repository", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/gluon/utils.py#L351-L357
23,926
apache/incubator-mxnet
python/mxnet/gluon/utils.py
_get_repo_file_url
def _get_repo_file_url(namespace, filename): """Return the URL for hosted file in Gluon repository. Parameters ---------- namespace : str Namespace of the file. filename : str Name of the file """ return '{base_url}{namespace}/{filename}'.format(base_url=_get_repo_url(), ...
python
def _get_repo_file_url(namespace, filename): """Return the URL for hosted file in Gluon repository. Parameters ---------- namespace : str Namespace of the file. filename : str Name of the file """ return '{base_url}{namespace}/{filename}'.format(base_url=_get_repo_url(), ...
[ "def", "_get_repo_file_url", "(", "namespace", ",", "filename", ")", ":", "return", "'{base_url}{namespace}/{filename}'", ".", "format", "(", "base_url", "=", "_get_repo_url", "(", ")", ",", "namespace", "=", "namespace", ",", "filename", "=", "filename", ")" ]
Return the URL for hosted file in Gluon repository. Parameters ---------- namespace : str Namespace of the file. filename : str Name of the file
[ "Return", "the", "URL", "for", "hosted", "file", "in", "Gluon", "repository", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/gluon/utils.py#L359-L371
23,927
apache/incubator-mxnet
python/mxnet/gluon/utils.py
_brief_print_list
def _brief_print_list(lst, limit=7): """Print at most `limit` elements of list.""" lst = list(lst) if len(lst) > limit: return _brief_print_list(lst[:limit//2], limit) + ', ..., ' + \ _brief_print_list(lst[-limit//2:], limit) return ', '.join(["'%s'"%str(i) for i in lst])
python
def _brief_print_list(lst, limit=7): """Print at most `limit` elements of list.""" lst = list(lst) if len(lst) > limit: return _brief_print_list(lst[:limit//2], limit) + ', ..., ' + \ _brief_print_list(lst[-limit//2:], limit) return ', '.join(["'%s'"%str(i) for i in lst])
[ "def", "_brief_print_list", "(", "lst", ",", "limit", "=", "7", ")", ":", "lst", "=", "list", "(", "lst", ")", "if", "len", "(", "lst", ")", ">", "limit", ":", "return", "_brief_print_list", "(", "lst", "[", ":", "limit", "//", "2", "]", ",", "li...
Print at most `limit` elements of list.
[ "Print", "at", "most", "limit", "elements", "of", "list", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/gluon/utils.py#L373-L379
23,928
apache/incubator-mxnet
python/mxnet/symbol/register.py
_make_symbol_function
def _make_symbol_function(handle, name, func_name): """Create a symbol function by handle and function name.""" code, doc_str = _generate_symbol_function_code(handle, name, func_name) local = {} exec(code, None, local) # pylint: disable=exec-used symbol_function = local[func_name] symbol_funct...
python
def _make_symbol_function(handle, name, func_name): """Create a symbol function by handle and function name.""" code, doc_str = _generate_symbol_function_code(handle, name, func_name) local = {} exec(code, None, local) # pylint: disable=exec-used symbol_function = local[func_name] symbol_funct...
[ "def", "_make_symbol_function", "(", "handle", ",", "name", ",", "func_name", ")", ":", "code", ",", "doc_str", "=", "_generate_symbol_function_code", "(", "handle", ",", "name", ",", "func_name", ")", "local", "=", "{", "}", "exec", "(", "code", ",", "Non...
Create a symbol function by handle and function name.
[ "Create", "a", "symbol", "function", "by", "handle", "and", "function", "name", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/symbol/register.py#L199-L209
23,929
apache/incubator-mxnet
example/sparse/matrix_factorization/train.py
batch_row_ids
def batch_row_ids(data_batch): """ Generate row ids based on the current mini-batch """ item = data_batch.data[0] user = data_batch.data[1] return {'user_weight': user.astype(np.int64), 'item_weight': item.astype(np.int64)}
python
def batch_row_ids(data_batch): """ Generate row ids based on the current mini-batch """ item = data_batch.data[0] user = data_batch.data[1] return {'user_weight': user.astype(np.int64), 'item_weight': item.astype(np.int64)}
[ "def", "batch_row_ids", "(", "data_batch", ")", ":", "item", "=", "data_batch", ".", "data", "[", "0", "]", "user", "=", "data_batch", ".", "data", "[", "1", "]", "return", "{", "'user_weight'", ":", "user", ".", "astype", "(", "np", ".", "int64", ")...
Generate row ids based on the current mini-batch
[ "Generate", "row", "ids", "based", "on", "the", "current", "mini", "-", "batch" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/sparse/matrix_factorization/train.py#L52-L57
23,930
apache/incubator-mxnet
example/sparse/matrix_factorization/train.py
all_row_ids
def all_row_ids(data_batch): """ Generate row ids for all rows """ all_users = mx.nd.arange(0, MOVIELENS['max_user'], dtype='int64') all_movies = mx.nd.arange(0, MOVIELENS['max_movie'], dtype='int64') return {'user_weight': all_users, 'item_weight': all_movies}
python
def all_row_ids(data_batch): """ Generate row ids for all rows """ all_users = mx.nd.arange(0, MOVIELENS['max_user'], dtype='int64') all_movies = mx.nd.arange(0, MOVIELENS['max_movie'], dtype='int64') return {'user_weight': all_users, 'item_weight': all_movies}
[ "def", "all_row_ids", "(", "data_batch", ")", ":", "all_users", "=", "mx", ".", "nd", ".", "arange", "(", "0", ",", "MOVIELENS", "[", "'max_user'", "]", ",", "dtype", "=", "'int64'", ")", "all_movies", "=", "mx", ".", "nd", ".", "arange", "(", "0", ...
Generate row ids for all rows
[ "Generate", "row", "ids", "for", "all", "rows" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/sparse/matrix_factorization/train.py#L59-L63
23,931
apache/incubator-mxnet
example/profiler/profiler_ndarray.py
check_with_uniform
def check_with_uniform(uf, arg_shapes, dim=None, npuf=None, rmin=-10, type_list=[np.float32]): """check function consistency with uniform random numbers""" if isinstance(arg_shapes, int): assert dim shape = tuple(np.random.randint(1, int(1000**(1.0/dim)), size=dim)) arg_shapes = [shape] ...
python
def check_with_uniform(uf, arg_shapes, dim=None, npuf=None, rmin=-10, type_list=[np.float32]): """check function consistency with uniform random numbers""" if isinstance(arg_shapes, int): assert dim shape = tuple(np.random.randint(1, int(1000**(1.0/dim)), size=dim)) arg_shapes = [shape] ...
[ "def", "check_with_uniform", "(", "uf", ",", "arg_shapes", ",", "dim", "=", "None", ",", "npuf", "=", "None", ",", "rmin", "=", "-", "10", ",", "type_list", "=", "[", "np", ".", "float32", "]", ")", ":", "if", "isinstance", "(", "arg_shapes", ",", ...
check function consistency with uniform random numbers
[ "check", "function", "consistency", "with", "uniform", "random", "numbers" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/profiler/profiler_ndarray.py#L51-L77
23,932
apache/incubator-mxnet
example/rcnn/symimdb/imdb.py
IMDB.filter_roidb
def filter_roidb(self): """Remove images without usable rois""" num_roidb = len(self._roidb) self._roidb = [roi_rec for roi_rec in self._roidb if len(roi_rec['gt_classes'])] num_after = len(self._roidb) logger.info('filter roidb: {} -> {}'.format(num_roidb, num_after))
python
def filter_roidb(self): """Remove images without usable rois""" num_roidb = len(self._roidb) self._roidb = [roi_rec for roi_rec in self._roidb if len(roi_rec['gt_classes'])] num_after = len(self._roidb) logger.info('filter roidb: {} -> {}'.format(num_roidb, num_after))
[ "def", "filter_roidb", "(", "self", ")", ":", "num_roidb", "=", "len", "(", "self", ".", "_roidb", ")", "self", ".", "_roidb", "=", "[", "roi_rec", "for", "roi_rec", "in", "self", ".", "_roidb", "if", "len", "(", "roi_rec", "[", "'gt_classes'", "]", ...
Remove images without usable rois
[ "Remove", "images", "without", "usable", "rois" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/rcnn/symimdb/imdb.py#L76-L81
23,933
apache/incubator-mxnet
example/rcnn/symimdb/imdb.py
IMDB.append_flipped_images
def append_flipped_images(self): """Only flip boxes coordinates, images will be flipped when loading into network""" logger.info('%s append flipped images to roidb' % self._name) roidb_flipped = [] for roi_rec in self._roidb: boxes = roi_rec['boxes'].copy() oldx1 ...
python
def append_flipped_images(self): """Only flip boxes coordinates, images will be flipped when loading into network""" logger.info('%s append flipped images to roidb' % self._name) roidb_flipped = [] for roi_rec in self._roidb: boxes = roi_rec['boxes'].copy() oldx1 ...
[ "def", "append_flipped_images", "(", "self", ")", ":", "logger", ".", "info", "(", "'%s append flipped images to roidb'", "%", "self", ".", "_name", ")", "roidb_flipped", "=", "[", "]", "for", "roi_rec", "in", "self", ".", "_roidb", ":", "boxes", "=", "roi_r...
Only flip boxes coordinates, images will be flipped when loading into network
[ "Only", "flip", "boxes", "coordinates", "images", "will", "be", "flipped", "when", "loading", "into", "network" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/rcnn/symimdb/imdb.py#L83-L98
23,934
apache/incubator-mxnet
python/mxnet/gluon/model_zoo/model_store.py
get_model_file
def get_model_file(name, root=os.path.join(base.data_dir(), 'models')): r"""Return location for the pretrained on local file system. This function will download from online model zoo when model cannot be found or has mismatch. The root directory will be created if it doesn't exist. Parameters ----...
python
def get_model_file(name, root=os.path.join(base.data_dir(), 'models')): r"""Return location for the pretrained on local file system. This function will download from online model zoo when model cannot be found or has mismatch. The root directory will be created if it doesn't exist. Parameters ----...
[ "def", "get_model_file", "(", "name", ",", "root", "=", "os", ".", "path", ".", "join", "(", "base", ".", "data_dir", "(", ")", ",", "'models'", ")", ")", ":", "file_name", "=", "'{name}-{short_hash}'", ".", "format", "(", "name", "=", "name", ",", "...
r"""Return location for the pretrained on local file system. This function will download from online model zoo when model cannot be found or has mismatch. The root directory will be created if it doesn't exist. Parameters ---------- name : str Name of the model. root : str, default $MX...
[ "r", "Return", "location", "for", "the", "pretrained", "on", "local", "file", "system", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/gluon/model_zoo/model_store.py#L73-L120
23,935
apache/incubator-mxnet
python/mxnet/gluon/model_zoo/model_store.py
purge
def purge(root=os.path.join(base.data_dir(), 'models')): r"""Purge all pretrained model files in local file store. Parameters ---------- root : str, default '$MXNET_HOME/models' Location for keeping the model parameters. """ root = os.path.expanduser(root) files = os.listdir(root) ...
python
def purge(root=os.path.join(base.data_dir(), 'models')): r"""Purge all pretrained model files in local file store. Parameters ---------- root : str, default '$MXNET_HOME/models' Location for keeping the model parameters. """ root = os.path.expanduser(root) files = os.listdir(root) ...
[ "def", "purge", "(", "root", "=", "os", ".", "path", ".", "join", "(", "base", ".", "data_dir", "(", ")", ",", "'models'", ")", ")", ":", "root", "=", "os", ".", "path", ".", "expanduser", "(", "root", ")", "files", "=", "os", ".", "listdir", "...
r"""Purge all pretrained model files in local file store. Parameters ---------- root : str, default '$MXNET_HOME/models' Location for keeping the model parameters.
[ "r", "Purge", "all", "pretrained", "model", "files", "in", "local", "file", "store", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/gluon/model_zoo/model_store.py#L122-L134
23,936
apache/incubator-mxnet
example/ssd/dataset/mscoco.py
Coco._load_all
def _load_all(self, anno_file, shuffle): """ initialize all entries given annotation json file Parameters: ---------- anno_file: str annotation json file shuffle: bool whether to shuffle image list """ image_set_index = [] ...
python
def _load_all(self, anno_file, shuffle): """ initialize all entries given annotation json file Parameters: ---------- anno_file: str annotation json file shuffle: bool whether to shuffle image list """ image_set_index = [] ...
[ "def", "_load_all", "(", "self", ",", "anno_file", ",", "shuffle", ")", ":", "image_set_index", "=", "[", "]", "labels", "=", "[", "]", "coco", "=", "COCO", "(", "anno_file", ")", "img_ids", "=", "coco", ".", "getImgIds", "(", ")", "# deal with class nam...
initialize all entries given annotation json file Parameters: ---------- anno_file: str annotation json file shuffle: bool whether to shuffle image list
[ "initialize", "all", "entries", "given", "annotation", "json", "file" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/ssd/dataset/mscoco.py#L85-L138
23,937
apache/incubator-mxnet
example/rnn/word_lm/module.py
CustomStatefulModule.forward
def forward(self, data_batch, is_train=None, carry_state=True): """Forward computation. States from previous forward computation are carried to the current iteration if `carry_state` is set to `True`. """ # propagate states from the previous iteration if carry_state: ...
python
def forward(self, data_batch, is_train=None, carry_state=True): """Forward computation. States from previous forward computation are carried to the current iteration if `carry_state` is set to `True`. """ # propagate states from the previous iteration if carry_state: ...
[ "def", "forward", "(", "self", ",", "data_batch", ",", "is_train", "=", "None", ",", "carry_state", "=", "True", ")", ":", "# propagate states from the previous iteration", "if", "carry_state", ":", "if", "isinstance", "(", "self", ".", "_next_states", ",", "(",...
Forward computation. States from previous forward computation are carried to the current iteration if `carry_state` is set to `True`.
[ "Forward", "computation", ".", "States", "from", "previous", "forward", "computation", "are", "carried", "to", "the", "current", "iteration", "if", "carry_state", "is", "set", "to", "True", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/rnn/word_lm/module.py#L78-L90
23,938
apache/incubator-mxnet
example/rnn/word_lm/module.py
CustomStatefulModule.update
def update(self, max_norm=None): """Updates parameters according to the installed optimizer and the gradients computed in the previous forward-backward batch. Gradients are clipped by their global norm if `max_norm` is set. Parameters ---------- max_norm: float, optional...
python
def update(self, max_norm=None): """Updates parameters according to the installed optimizer and the gradients computed in the previous forward-backward batch. Gradients are clipped by their global norm if `max_norm` is set. Parameters ---------- max_norm: float, optional...
[ "def", "update", "(", "self", ",", "max_norm", "=", "None", ")", ":", "if", "max_norm", "is", "not", "None", ":", "self", ".", "_clip_by_global_norm", "(", "max_norm", ")", "self", ".", "_module", ".", "update", "(", ")" ]
Updates parameters according to the installed optimizer and the gradients computed in the previous forward-backward batch. Gradients are clipped by their global norm if `max_norm` is set. Parameters ---------- max_norm: float, optional If set, clip values of all grad...
[ "Updates", "parameters", "according", "to", "the", "installed", "optimizer", "and", "the", "gradients", "computed", "in", "the", "previous", "forward", "-", "backward", "batch", ".", "Gradients", "are", "clipped", "by", "their", "global", "norm", "if", "max_norm...
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/rnn/word_lm/module.py#L92-L104
23,939
apache/incubator-mxnet
example/gluon/dc_gan/dcgan.py
transformer
def transformer(data, label): """Get the translation of images""" # resize to 64x64 data = mx.image.imresize(data, 64, 64) # transpose from (64, 64, 3) to (3, 64, 64) data = mx.nd.transpose(data, (2, 0, 1)) # normalize to [-1, 1] data = data.astype(np.float32)/128 - 1 # if image is greys...
python
def transformer(data, label): """Get the translation of images""" # resize to 64x64 data = mx.image.imresize(data, 64, 64) # transpose from (64, 64, 3) to (3, 64, 64) data = mx.nd.transpose(data, (2, 0, 1)) # normalize to [-1, 1] data = data.astype(np.float32)/128 - 1 # if image is greys...
[ "def", "transformer", "(", "data", ",", "label", ")", ":", "# resize to 64x64", "data", "=", "mx", ".", "image", ".", "imresize", "(", "data", ",", "64", ",", "64", ")", "# transpose from (64, 64, 3) to (3, 64, 64)", "data", "=", "mx", ".", "nd", ".", "tra...
Get the translation of images
[ "Get", "the", "translation", "of", "images" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/gluon/dc_gan/dcgan.py#L117-L128
23,940
apache/incubator-mxnet
example/gluon/dc_gan/dcgan.py
get_netG
def get_netG(): """Get net G""" # build the generator netG = nn.Sequential() with netG.name_scope(): # input is Z, going into a convolution netG.add(nn.Conv2DTranspose(ngf * 8, 4, 1, 0, use_bias=False)) netG.add(nn.BatchNorm()) netG.add(nn.Activation('relu')) # st...
python
def get_netG(): """Get net G""" # build the generator netG = nn.Sequential() with netG.name_scope(): # input is Z, going into a convolution netG.add(nn.Conv2DTranspose(ngf * 8, 4, 1, 0, use_bias=False)) netG.add(nn.BatchNorm()) netG.add(nn.Activation('relu')) # st...
[ "def", "get_netG", "(", ")", ":", "# build the generator", "netG", "=", "nn", ".", "Sequential", "(", ")", "with", "netG", ".", "name_scope", "(", ")", ":", "# input is Z, going into a convolution", "netG", ".", "add", "(", "nn", ".", "Conv2DTranspose", "(", ...
Get net G
[ "Get", "net", "G" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/gluon/dc_gan/dcgan.py#L165-L191
23,941
apache/incubator-mxnet
example/gluon/dc_gan/dcgan.py
get_netD
def get_netD(): """Get the netD""" # build the discriminator netD = nn.Sequential() with netD.name_scope(): # input is (nc) x 64 x 64 netD.add(nn.Conv2D(ndf, 4, 2, 1, use_bias=False)) netD.add(nn.LeakyReLU(0.2)) # state size. (ndf) x 32 x 32 netD.add(nn.Conv2D(ndf...
python
def get_netD(): """Get the netD""" # build the discriminator netD = nn.Sequential() with netD.name_scope(): # input is (nc) x 64 x 64 netD.add(nn.Conv2D(ndf, 4, 2, 1, use_bias=False)) netD.add(nn.LeakyReLU(0.2)) # state size. (ndf) x 32 x 32 netD.add(nn.Conv2D(ndf...
[ "def", "get_netD", "(", ")", ":", "# build the discriminator", "netD", "=", "nn", ".", "Sequential", "(", ")", "with", "netD", ".", "name_scope", "(", ")", ":", "# input is (nc) x 64 x 64", "netD", ".", "add", "(", "nn", ".", "Conv2D", "(", "ndf", ",", "...
Get the netD
[ "Get", "the", "netD" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/gluon/dc_gan/dcgan.py#L194-L218
23,942
apache/incubator-mxnet
example/gluon/dc_gan/dcgan.py
get_configurations
def get_configurations(netG, netD): """Get configurations for net""" # loss loss = gluon.loss.SoftmaxCrossEntropyLoss() # initialize the generator and the discriminator netG.initialize(mx.init.Normal(0.02), ctx=ctx) netD.initialize(mx.init.Normal(0.02), ctx=ctx) # trainer for the generator...
python
def get_configurations(netG, netD): """Get configurations for net""" # loss loss = gluon.loss.SoftmaxCrossEntropyLoss() # initialize the generator and the discriminator netG.initialize(mx.init.Normal(0.02), ctx=ctx) netD.initialize(mx.init.Normal(0.02), ctx=ctx) # trainer for the generator...
[ "def", "get_configurations", "(", "netG", ",", "netD", ")", ":", "# loss", "loss", "=", "gluon", ".", "loss", ".", "SoftmaxCrossEntropyLoss", "(", ")", "# initialize the generator and the discriminator", "netG", ".", "initialize", "(", "mx", ".", "init", ".", "N...
Get configurations for net
[ "Get", "configurations", "for", "net" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/gluon/dc_gan/dcgan.py#L221-L234
23,943
apache/incubator-mxnet
example/gluon/sn_gan/data.py
get_training_data
def get_training_data(batch_size): """ helper function to get dataloader""" return gluon.data.DataLoader( CIFAR10(train=True, transform=transformer), batch_size=batch_size, shuffle=True, last_batch='discard')
python
def get_training_data(batch_size): """ helper function to get dataloader""" return gluon.data.DataLoader( CIFAR10(train=True, transform=transformer), batch_size=batch_size, shuffle=True, last_batch='discard')
[ "def", "get_training_data", "(", "batch_size", ")", ":", "return", "gluon", ".", "data", ".", "DataLoader", "(", "CIFAR10", "(", "train", "=", "True", ",", "transform", "=", "transformer", ")", ",", "batch_size", "=", "batch_size", ",", "shuffle", "=", "Tr...
helper function to get dataloader
[ "helper", "function", "to", "get", "dataloader" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/gluon/sn_gan/data.py#L38-L42
23,944
apache/incubator-mxnet
python/mxnet/symbol/random.py
poisson
def poisson(lam=1, shape=_Null, dtype=_Null, **kwargs): """Draw random samples from a Poisson distribution. Samples are distributed according to a Poisson distribution parametrized by *lambda* (rate). Samples will always be returned as a floating point data type. Parameters ---------- lam : fl...
python
def poisson(lam=1, shape=_Null, dtype=_Null, **kwargs): """Draw random samples from a Poisson distribution. Samples are distributed according to a Poisson distribution parametrized by *lambda* (rate). Samples will always be returned as a floating point data type. Parameters ---------- lam : fl...
[ "def", "poisson", "(", "lam", "=", "1", ",", "shape", "=", "_Null", ",", "dtype", "=", "_Null", ",", "*", "*", "kwargs", ")", ":", "return", "_random_helper", "(", "_internal", ".", "_random_poisson", ",", "_internal", ".", "_sample_poisson", ",", "[", ...
Draw random samples from a Poisson distribution. Samples are distributed according to a Poisson distribution parametrized by *lambda* (rate). Samples will always be returned as a floating point data type. Parameters ---------- lam : float or Symbol, optional Expectation of interval, should...
[ "Draw", "random", "samples", "from", "a", "Poisson", "distribution", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/symbol/random.py#L116-L143
23,945
apache/incubator-mxnet
python/mxnet/symbol/random.py
generalized_negative_binomial
def generalized_negative_binomial(mu=1, alpha=1, shape=_Null, dtype=_Null, **kwargs): """Draw random samples from a generalized negative binomial distribution. Samples are distributed according to a generalized negative binomial distribution parametrized by *mu* (mean) and *alpha* (dispersion). *alpha*...
python
def generalized_negative_binomial(mu=1, alpha=1, shape=_Null, dtype=_Null, **kwargs): """Draw random samples from a generalized negative binomial distribution. Samples are distributed according to a generalized negative binomial distribution parametrized by *mu* (mean) and *alpha* (dispersion). *alpha*...
[ "def", "generalized_negative_binomial", "(", "mu", "=", "1", ",", "alpha", "=", "1", ",", "shape", "=", "_Null", ",", "dtype", "=", "_Null", ",", "*", "*", "kwargs", ")", ":", "return", "_random_helper", "(", "_internal", ".", "_random_generalized_negative_b...
Draw random samples from a generalized negative binomial distribution. Samples are distributed according to a generalized negative binomial distribution parametrized by *mu* (mean) and *alpha* (dispersion). *alpha* is defined as *1/k* where *k* is the failure limit of the number of unsuccessful experim...
[ "Draw", "random", "samples", "from", "a", "generalized", "negative", "binomial", "distribution", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/symbol/random.py#L248-L281
23,946
apache/incubator-mxnet
python/mxnet/module/module.py
Module.load
def load(prefix, epoch, load_optimizer_states=False, **kwargs): """Creates a model from previously saved checkpoint. Parameters ---------- prefix : str path prefix of saved model files. You should have "prefix-symbol.json", "prefix-xxxx.params", and o...
python
def load(prefix, epoch, load_optimizer_states=False, **kwargs): """Creates a model from previously saved checkpoint. Parameters ---------- prefix : str path prefix of saved model files. You should have "prefix-symbol.json", "prefix-xxxx.params", and o...
[ "def", "load", "(", "prefix", ",", "epoch", ",", "load_optimizer_states", "=", "False", ",", "*", "*", "kwargs", ")", ":", "sym", ",", "args", ",", "auxs", "=", "load_checkpoint", "(", "prefix", ",", "epoch", ")", "mod", "=", "Module", "(", "symbol", ...
Creates a model from previously saved checkpoint. Parameters ---------- prefix : str path prefix of saved model files. You should have "prefix-symbol.json", "prefix-xxxx.params", and optionally "prefix-xxxx.states", where xxxx is the epoch number....
[ "Creates", "a", "model", "from", "previously", "saved", "checkpoint", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/module/module.py#L127-L163
23,947
apache/incubator-mxnet
python/mxnet/module/module.py
Module.save_checkpoint
def save_checkpoint(self, prefix, epoch, save_optimizer_states=False): """Saves current progress to checkpoint. Use `mx.callback.module_checkpoint` as `epoch_end_callback` to save during training. Parameters ---------- prefix : str The file prefix to checkpoint to. ...
python
def save_checkpoint(self, prefix, epoch, save_optimizer_states=False): """Saves current progress to checkpoint. Use `mx.callback.module_checkpoint` as `epoch_end_callback` to save during training. Parameters ---------- prefix : str The file prefix to checkpoint to. ...
[ "def", "save_checkpoint", "(", "self", ",", "prefix", ",", "epoch", ",", "save_optimizer_states", "=", "False", ")", ":", "self", ".", "_symbol", ".", "save", "(", "'%s-symbol.json'", "%", "prefix", ")", "param_name", "=", "'%s-%04d.params'", "%", "(", "pref...
Saves current progress to checkpoint. Use `mx.callback.module_checkpoint` as `epoch_end_callback` to save during training. Parameters ---------- prefix : str The file prefix to checkpoint to. epoch : int The current epoch number. save_optimizer_st...
[ "Saves", "current", "progress", "to", "checkpoint", ".", "Use", "mx", ".", "callback", ".", "module_checkpoint", "as", "epoch_end_callback", "to", "save", "during", "training", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/module/module.py#L165-L185
23,948
apache/incubator-mxnet
python/mxnet/module/module.py
Module._reset_bind
def _reset_bind(self): """Internal function to reset binded state.""" self.binded = False self._exec_group = None self._data_shapes = None self._label_shapes = None
python
def _reset_bind(self): """Internal function to reset binded state.""" self.binded = False self._exec_group = None self._data_shapes = None self._label_shapes = None
[ "def", "_reset_bind", "(", "self", ")", ":", "self", ".", "binded", "=", "False", "self", ".", "_exec_group", "=", "None", "self", ".", "_data_shapes", "=", "None", "self", ".", "_label_shapes", "=", "None" ]
Internal function to reset binded state.
[ "Internal", "function", "to", "reset", "binded", "state", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/module/module.py#L187-L192
23,949
apache/incubator-mxnet
python/mxnet/module/module.py
Module.reshape
def reshape(self, data_shapes, label_shapes=None): """Reshapes the module for new input shapes. Parameters ---------- data_shapes : list of (str, tuple) Typically is ``data_iter.provide_data``. label_shapes : list of (str, tuple) Typically is ``data_iter....
python
def reshape(self, data_shapes, label_shapes=None): """Reshapes the module for new input shapes. Parameters ---------- data_shapes : list of (str, tuple) Typically is ``data_iter.provide_data``. label_shapes : list of (str, tuple) Typically is ``data_iter....
[ "def", "reshape", "(", "self", ",", "data_shapes", ",", "label_shapes", "=", "None", ")", ":", "assert", "self", ".", "binded", "self", ".", "_data_shapes", ",", "self", ".", "_label_shapes", "=", "_parse_data_desc", "(", "self", ".", "data_names", ",", "s...
Reshapes the module for new input shapes. Parameters ---------- data_shapes : list of (str, tuple) Typically is ``data_iter.provide_data``. label_shapes : list of (str, tuple) Typically is ``data_iter.provide_label``.
[ "Reshapes", "the", "module", "for", "new", "input", "shapes", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/module/module.py#L458-L472
23,950
apache/incubator-mxnet
python/mxnet/module/module.py
Module.forward
def forward(self, data_batch, is_train=None): """Forward computation. It supports data batches with different shapes, such as different batch sizes or different image sizes. If reshaping of data batch relates to modification of symbol or module, such as changing image layout ordering or ...
python
def forward(self, data_batch, is_train=None): """Forward computation. It supports data batches with different shapes, such as different batch sizes or different image sizes. If reshaping of data batch relates to modification of symbol or module, such as changing image layout ordering or ...
[ "def", "forward", "(", "self", ",", "data_batch", ",", "is_train", "=", "None", ")", ":", "assert", "self", ".", "binded", "and", "self", ".", "params_initialized", "curr_data_shapes", "=", "tuple", "(", "i", ".", "shape", "for", "i", "in", "self", ".", ...
Forward computation. It supports data batches with different shapes, such as different batch sizes or different image sizes. If reshaping of data batch relates to modification of symbol or module, such as changing image layout ordering or switching from training to predicting, module reb...
[ "Forward", "computation", ".", "It", "supports", "data", "batches", "with", "different", "shapes", "such", "as", "different", "batch", "sizes", "or", "different", "image", "sizes", ".", "If", "reshaping", "of", "data", "batch", "relates", "to", "modification", ...
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/module/module.py#L575-L627
23,951
apache/incubator-mxnet
python/mxnet/module/module.py
Module.update
def update(self): """Updates parameters according to the installed optimizer and the gradients computed in the previous forward-backward batch. When KVStore is used to update parameters for multi-device or multi-machine training, a copy of the parameters are stored in KVStore. Note that...
python
def update(self): """Updates parameters according to the installed optimizer and the gradients computed in the previous forward-backward batch. When KVStore is used to update parameters for multi-device or multi-machine training, a copy of the parameters are stored in KVStore. Note that...
[ "def", "update", "(", "self", ")", ":", "assert", "self", ".", "binded", "and", "self", ".", "params_initialized", "and", "self", ".", "optimizer_initialized", "self", ".", "_params_dirty", "=", "True", "if", "self", ".", "_update_on_kvstore", ":", "_update_pa...
Updates parameters according to the installed optimizer and the gradients computed in the previous forward-backward batch. When KVStore is used to update parameters for multi-device or multi-machine training, a copy of the parameters are stored in KVStore. Note that for `row_sparse` parameters,...
[ "Updates", "parameters", "according", "to", "the", "installed", "optimizer", "and", "the", "gradients", "computed", "in", "the", "previous", "forward", "-", "backward", "batch", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/module/module.py#L646-L673
23,952
apache/incubator-mxnet
python/mxnet/module/module.py
Module.get_outputs
def get_outputs(self, merge_multi_context=True): """Gets outputs of the previous forward computation. If ``merge_multi_context`` is ``True``, it is like ``[out1, out2]``. Otherwise, it is like ``[[out1_dev1, out1_dev2], [out2_dev1, out2_dev2]]``. All the output elements are `NDArray`. W...
python
def get_outputs(self, merge_multi_context=True): """Gets outputs of the previous forward computation. If ``merge_multi_context`` is ``True``, it is like ``[out1, out2]``. Otherwise, it is like ``[[out1_dev1, out1_dev2], [out2_dev1, out2_dev2]]``. All the output elements are `NDArray`. W...
[ "def", "get_outputs", "(", "self", ",", "merge_multi_context", "=", "True", ")", ":", "assert", "self", ".", "binded", "and", "self", ".", "params_initialized", "return", "self", ".", "_exec_group", ".", "get_outputs", "(", "merge_multi_context", "=", "merge_mul...
Gets outputs of the previous forward computation. If ``merge_multi_context`` is ``True``, it is like ``[out1, out2]``. Otherwise, it is like ``[[out1_dev1, out1_dev2], [out2_dev1, out2_dev2]]``. All the output elements are `NDArray`. When `merge_multi_context` is `False`, those `NDArray` ...
[ "Gets", "outputs", "of", "the", "previous", "forward", "computation", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/module/module.py#L675-L697
23,953
apache/incubator-mxnet
python/mxnet/module/module.py
Module._sync_params_from_devices
def _sync_params_from_devices(self): """Synchronizes parameters from devices to CPU. This function should be called after calling `update` that updates the parameters on the devices, before one can read the latest parameters from ``self._arg_params`` and ``self._aux_params``. For row_sp...
python
def _sync_params_from_devices(self): """Synchronizes parameters from devices to CPU. This function should be called after calling `update` that updates the parameters on the devices, before one can read the latest parameters from ``self._arg_params`` and ``self._aux_params``. For row_sp...
[ "def", "_sync_params_from_devices", "(", "self", ")", ":", "self", ".", "_exec_group", ".", "get_params", "(", "self", ".", "_arg_params", ",", "self", ".", "_aux_params", ")", "if", "self", ".", "_kvstore", "and", "self", ".", "_update_on_kvstore", ":", "fo...
Synchronizes parameters from devices to CPU. This function should be called after calling `update` that updates the parameters on the devices, before one can read the latest parameters from ``self._arg_params`` and ``self._aux_params``. For row_sparse parameters on devices, ther are pulled from...
[ "Synchronizes", "parameters", "from", "devices", "to", "CPU", ".", "This", "function", "should", "be", "called", "after", "calling", "update", "that", "updates", "the", "parameters", "on", "the", "devices", "before", "one", "can", "read", "the", "latest", "par...
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/module/module.py#L777-L791
23,954
apache/incubator-mxnet
python/mxnet/ndarray/random.py
uniform
def uniform(low=0, high=1, shape=_Null, dtype=_Null, ctx=None, out=None, **kwargs): """Draw random samples from a uniform distribution. Samples are uniformly distributed over the half-open interval *[low, high)* (includes *low*, but excludes *high*). Parameters ---------- low : float or NDArra...
python
def uniform(low=0, high=1, shape=_Null, dtype=_Null, ctx=None, out=None, **kwargs): """Draw random samples from a uniform distribution. Samples are uniformly distributed over the half-open interval *[low, high)* (includes *low*, but excludes *high*). Parameters ---------- low : float or NDArra...
[ "def", "uniform", "(", "low", "=", "0", ",", "high", "=", "1", ",", "shape", "=", "_Null", ",", "dtype", "=", "_Null", ",", "ctx", "=", "None", ",", "out", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "_random_helper", "(", "_interna...
Draw random samples from a uniform distribution. Samples are uniformly distributed over the half-open interval *[low, high)* (includes *low*, but excludes *high*). Parameters ---------- low : float or NDArray, optional Lower boundary of the output interval. All values generated will be ...
[ "Draw", "random", "samples", "from", "a", "uniform", "distribution", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/ndarray/random.py#L54-L110
23,955
apache/incubator-mxnet
python/mxnet/ndarray/random.py
exponential
def exponential(scale=1, shape=_Null, dtype=_Null, ctx=None, out=None, **kwargs): r"""Draw samples from an exponential distribution. Its probability density function is .. math:: f(x; \frac{1}{\beta}) = \frac{1}{\beta} \exp(-\frac{x}{\beta}), for x > 0 and 0 elsewhere. \beta is the scale parameter, w...
python
def exponential(scale=1, shape=_Null, dtype=_Null, ctx=None, out=None, **kwargs): r"""Draw samples from an exponential distribution. Its probability density function is .. math:: f(x; \frac{1}{\beta}) = \frac{1}{\beta} \exp(-\frac{x}{\beta}), for x > 0 and 0 elsewhere. \beta is the scale parameter, w...
[ "def", "exponential", "(", "scale", "=", "1", ",", "shape", "=", "_Null", ",", "dtype", "=", "_Null", ",", "ctx", "=", "None", ",", "out", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "_random_helper", "(", "_internal", ".", "_random_exp...
r"""Draw samples from an exponential distribution. Its probability density function is .. math:: f(x; \frac{1}{\beta}) = \frac{1}{\beta} \exp(-\frac{x}{\beta}), for x > 0 and 0 elsewhere. \beta is the scale parameter, which is the inverse of the rate parameter \lambda = 1/\beta. Parameters -...
[ "r", "Draw", "samples", "from", "an", "exponential", "distribution", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/ndarray/random.py#L279-L329
23,956
apache/incubator-mxnet
python/mxnet/ndarray/random.py
gamma
def gamma(alpha=1, beta=1, shape=_Null, dtype=_Null, ctx=None, out=None, **kwargs): """Draw random samples from a gamma distribution. Samples are distributed according to a gamma distribution parametrized by *alpha* (shape) and *beta* (scale). Parameters ---------- alpha : float or NDArray, op...
python
def gamma(alpha=1, beta=1, shape=_Null, dtype=_Null, ctx=None, out=None, **kwargs): """Draw random samples from a gamma distribution. Samples are distributed according to a gamma distribution parametrized by *alpha* (shape) and *beta* (scale). Parameters ---------- alpha : float or NDArray, op...
[ "def", "gamma", "(", "alpha", "=", "1", ",", "beta", "=", "1", ",", "shape", "=", "_Null", ",", "dtype", "=", "_Null", ",", "ctx", "=", "None", ",", "out", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "_random_helper", "(", "_interna...
Draw random samples from a gamma distribution. Samples are distributed according to a gamma distribution parametrized by *alpha* (shape) and *beta* (scale). Parameters ---------- alpha : float or NDArray, optional The shape of the gamma distribution. Should be greater than zero. beta :...
[ "Draw", "random", "samples", "from", "a", "gamma", "distribution", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/ndarray/random.py#L332-L383
23,957
apache/incubator-mxnet
python/mxnet/ndarray/random.py
negative_binomial
def negative_binomial(k=1, p=1, shape=_Null, dtype=_Null, ctx=None, out=None, **kwargs): """Draw random samples from a negative binomial distribution. Samples are distributed according to a negative binomial distribution parametrized by *k* (limit of unsuccessful experiments) and *p* ...
python
def negative_binomial(k=1, p=1, shape=_Null, dtype=_Null, ctx=None, out=None, **kwargs): """Draw random samples from a negative binomial distribution. Samples are distributed according to a negative binomial distribution parametrized by *k* (limit of unsuccessful experiments) and *p* ...
[ "def", "negative_binomial", "(", "k", "=", "1", ",", "p", "=", "1", ",", "shape", "=", "_Null", ",", "dtype", "=", "_Null", ",", "ctx", "=", "None", ",", "out", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "_random_helper", "(", "_in...
Draw random samples from a negative binomial distribution. Samples are distributed according to a negative binomial distribution parametrized by *k* (limit of unsuccessful experiments) and *p* (failure probability in each experiment). Samples will always be returned as a floating point data type. ...
[ "Draw", "random", "samples", "from", "a", "negative", "binomial", "distribution", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/ndarray/random.py#L386-L439
23,958
apache/incubator-mxnet
python/mxnet/ndarray/random.py
randint
def randint(low, high, shape=_Null, dtype=_Null, ctx=None, out=None, **kwargs): """Draw random samples from a discrete uniform distribution. Samples are uniformly distributed over the half-open interval *[low, high)* (includes *low*, but excludes *high*). Parameters ---------- low : int, requi...
python
def randint(low, high, shape=_Null, dtype=_Null, ctx=None, out=None, **kwargs): """Draw random samples from a discrete uniform distribution. Samples are uniformly distributed over the half-open interval *[low, high)* (includes *low*, but excludes *high*). Parameters ---------- low : int, requi...
[ "def", "randint", "(", "low", ",", "high", ",", "shape", "=", "_Null", ",", "dtype", "=", "_Null", ",", "ctx", "=", "None", ",", "out", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "_random_helper", "(", "_internal", ".", "_random_randin...
Draw random samples from a discrete uniform distribution. Samples are uniformly distributed over the half-open interval *[low, high)* (includes *low*, but excludes *high*). Parameters ---------- low : int, required Lower boundary of the output interval. All values generated will be ...
[ "Draw", "random", "samples", "from", "a", "discrete", "uniform", "distribution", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/ndarray/random.py#L604-L649
23,959
apache/incubator-mxnet
python/mxnet/gluon/trainer.py
Trainer._init_params
def _init_params(self): """Initialize parameters in the KVStore. Parameters with incomplete initialization are ignored. """ assert self._kv_initialized, "Cannot initialize parameters in KVStore " \ "when KVStore is not initialized." params_t...
python
def _init_params(self): """Initialize parameters in the KVStore. Parameters with incomplete initialization are ignored. """ assert self._kv_initialized, "Cannot initialize parameters in KVStore " \ "when KVStore is not initialized." params_t...
[ "def", "_init_params", "(", "self", ")", ":", "assert", "self", ".", "_kv_initialized", ",", "\"Cannot initialize parameters in KVStore \"", "\"when KVStore is not initialized.\"", "params_to_init", "=", "[", "]", "if", "self", ".", "_kvstore", ":", "for", "param", "i...
Initialize parameters in the KVStore. Parameters with incomplete initialization are ignored.
[ "Initialize", "parameters", "in", "the", "KVStore", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/gluon/trainer.py#L137-L157
23,960
apache/incubator-mxnet
python/mxnet/gluon/trainer.py
Trainer._reset_kvstore
def _reset_kvstore(self): """Reset kvstore.""" if self._kvstore and 'dist' in self._kvstore.type: raise RuntimeError("Cannot reset distributed KVStore.") self._kv_initialized = False self._kvstore = None self._distributed = None self._update_on_kvstore = None ...
python
def _reset_kvstore(self): """Reset kvstore.""" if self._kvstore and 'dist' in self._kvstore.type: raise RuntimeError("Cannot reset distributed KVStore.") self._kv_initialized = False self._kvstore = None self._distributed = None self._update_on_kvstore = None ...
[ "def", "_reset_kvstore", "(", "self", ")", ":", "if", "self", ".", "_kvstore", "and", "'dist'", "in", "self", ".", "_kvstore", ".", "type", ":", "raise", "RuntimeError", "(", "\"Cannot reset distributed KVStore.\"", ")", "self", ".", "_kv_initialized", "=", "F...
Reset kvstore.
[ "Reset", "kvstore", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/gluon/trainer.py#L159-L167
23,961
apache/incubator-mxnet
python/mxnet/gluon/trainer.py
Trainer._init_kvstore
def _init_kvstore(self): """Create kvstore.""" config = self._kvstore_params # configure kvstore, update_on_kvstore and self._distributed on three cases: if self._contains_sparse_weight: # If weight is sparse, kvstore must be present and the weight must be updated on kvstore....
python
def _init_kvstore(self): """Create kvstore.""" config = self._kvstore_params # configure kvstore, update_on_kvstore and self._distributed on three cases: if self._contains_sparse_weight: # If weight is sparse, kvstore must be present and the weight must be updated on kvstore....
[ "def", "_init_kvstore", "(", "self", ")", ":", "config", "=", "self", ".", "_kvstore_params", "# configure kvstore, update_on_kvstore and self._distributed on three cases:", "if", "self", ".", "_contains_sparse_weight", ":", "# If weight is sparse, kvstore must be present and the w...
Create kvstore.
[ "Create", "kvstore", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/gluon/trainer.py#L169-L248
23,962
apache/incubator-mxnet
python/mxnet/gluon/trainer.py
Trainer.set_learning_rate
def set_learning_rate(self, lr): """Sets a new learning rate of the optimizer. Parameters ---------- lr : float The new learning rate of the optimizer. """ if not isinstance(self._optimizer, opt.Optimizer): raise UserWarning("Optimizer has to be d...
python
def set_learning_rate(self, lr): """Sets a new learning rate of the optimizer. Parameters ---------- lr : float The new learning rate of the optimizer. """ if not isinstance(self._optimizer, opt.Optimizer): raise UserWarning("Optimizer has to be d...
[ "def", "set_learning_rate", "(", "self", ",", "lr", ")", ":", "if", "not", "isinstance", "(", "self", ".", "_optimizer", ",", "opt", ".", "Optimizer", ")", ":", "raise", "UserWarning", "(", "\"Optimizer has to be defined before its learning \"", "\"rate is mutated.\...
Sets a new learning rate of the optimizer. Parameters ---------- lr : float The new learning rate of the optimizer.
[ "Sets", "a", "new", "learning", "rate", "of", "the", "optimizer", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/gluon/trainer.py#L258-L270
23,963
apache/incubator-mxnet
python/mxnet/gluon/trainer.py
Trainer._row_sparse_pull
def _row_sparse_pull(self, parameter, out, row_id, full_idx=False): """Internal method to invoke pull operations on KVStore. If `full_idx` is set to True, `kv.pull` is preferred instead of `kv.row_sparse_pull`. """ # initialize kv and params if not already if not self._kv_initial...
python
def _row_sparse_pull(self, parameter, out, row_id, full_idx=False): """Internal method to invoke pull operations on KVStore. If `full_idx` is set to True, `kv.pull` is preferred instead of `kv.row_sparse_pull`. """ # initialize kv and params if not already if not self._kv_initial...
[ "def", "_row_sparse_pull", "(", "self", ",", "parameter", ",", "out", ",", "row_id", ",", "full_idx", "=", "False", ")", ":", "# initialize kv and params if not already", "if", "not", "self", ".", "_kv_initialized", ":", "self", ".", "_init_kvstore", "(", ")", ...
Internal method to invoke pull operations on KVStore. If `full_idx` is set to True, `kv.pull` is preferred instead of `kv.row_sparse_pull`.
[ "Internal", "method", "to", "invoke", "pull", "operations", "on", "KVStore", ".", "If", "full_idx", "is", "set", "to", "True", "kv", ".", "pull", "is", "preferred", "instead", "of", "kv", ".", "row_sparse_pull", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/gluon/trainer.py#L272-L286
23,964
apache/incubator-mxnet
python/mxnet/gluon/trainer.py
Trainer.allreduce_grads
def allreduce_grads(self): """For each parameter, reduce the gradients from different contexts. Should be called after `autograd.backward()`, outside of `record()` scope, and before `trainer.update()`. For normal parameter updates, `step()` should be used, which internally calls ...
python
def allreduce_grads(self): """For each parameter, reduce the gradients from different contexts. Should be called after `autograd.backward()`, outside of `record()` scope, and before `trainer.update()`. For normal parameter updates, `step()` should be used, which internally calls ...
[ "def", "allreduce_grads", "(", "self", ")", ":", "if", "not", "self", ".", "_kv_initialized", ":", "self", ".", "_init_kvstore", "(", ")", "if", "self", ".", "_params_to_init", ":", "self", ".", "_init_params", "(", ")", "assert", "not", "(", "self", "."...
For each parameter, reduce the gradients from different contexts. Should be called after `autograd.backward()`, outside of `record()` scope, and before `trainer.update()`. For normal parameter updates, `step()` should be used, which internally calls `allreduce_grads()` and then `update...
[ "For", "each", "parameter", "reduce", "the", "gradients", "from", "different", "contexts", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/gluon/trainer.py#L327-L347
23,965
apache/incubator-mxnet
python/mxnet/gluon/trainer.py
Trainer.update
def update(self, batch_size, ignore_stale_grad=False): """Makes one step of parameter update. Should be called after `autograd.backward()` and outside of `record()` scope, and after `trainer.update()`. For normal parameter updates, `step()` should be used, which internally calls ...
python
def update(self, batch_size, ignore_stale_grad=False): """Makes one step of parameter update. Should be called after `autograd.backward()` and outside of `record()` scope, and after `trainer.update()`. For normal parameter updates, `step()` should be used, which internally calls ...
[ "def", "update", "(", "self", ",", "batch_size", ",", "ignore_stale_grad", "=", "False", ")", ":", "if", "not", "self", ".", "_kv_initialized", ":", "self", ".", "_init_kvstore", "(", ")", "if", "self", ".", "_params_to_init", ":", "self", ".", "_init_para...
Makes one step of parameter update. Should be called after `autograd.backward()` and outside of `record()` scope, and after `trainer.update()`. For normal parameter updates, `step()` should be used, which internally calls `allreduce_grads()` and then `update()`. However, if you need t...
[ "Makes", "one", "step", "of", "parameter", "update", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/gluon/trainer.py#L359-L390
23,966
apache/incubator-mxnet
benchmark/python/sparse/util.py
estimate_density
def estimate_density(DATA_PATH, feature_size): """sample 10 times of a size of 1000 for estimating the density of the sparse dataset""" if not os.path.exists(DATA_PATH): raise Exception("Data is not there!") density = [] P = 0.01 for _ in range(10): num_non_zero = 0 num_sampl...
python
def estimate_density(DATA_PATH, feature_size): """sample 10 times of a size of 1000 for estimating the density of the sparse dataset""" if not os.path.exists(DATA_PATH): raise Exception("Data is not there!") density = [] P = 0.01 for _ in range(10): num_non_zero = 0 num_sampl...
[ "def", "estimate_density", "(", "DATA_PATH", ",", "feature_size", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "DATA_PATH", ")", ":", "raise", "Exception", "(", "\"Data is not there!\"", ")", "density", "=", "[", "]", "P", "=", "0.01", "...
sample 10 times of a size of 1000 for estimating the density of the sparse dataset
[ "sample", "10", "times", "of", "a", "size", "of", "1000", "for", "estimating", "the", "density", "of", "the", "sparse", "dataset" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/benchmark/python/sparse/util.py#L21-L36
23,967
apache/incubator-mxnet
example/reinforcement-learning/a3c/launcher.py
exec_cmd
def exec_cmd(cmd, role, taskid, pass_env): """Execute the command line command.""" if cmd[0].find('/') == -1 and os.path.exists(cmd[0]) and os.name != 'nt': cmd[0] = './' + cmd[0] cmd = ' '.join(cmd) env = os.environ.copy() for k, v in pass_env.items(): env[k] = str(v) env['DMLC...
python
def exec_cmd(cmd, role, taskid, pass_env): """Execute the command line command.""" if cmd[0].find('/') == -1 and os.path.exists(cmd[0]) and os.name != 'nt': cmd[0] = './' + cmd[0] cmd = ' '.join(cmd) env = os.environ.copy() for k, v in pass_env.items(): env[k] = str(v) env['DMLC...
[ "def", "exec_cmd", "(", "cmd", ",", "role", ",", "taskid", ",", "pass_env", ")", ":", "if", "cmd", "[", "0", "]", ".", "find", "(", "'/'", ")", "==", "-", "1", "and", "os", ".", "path", ".", "exists", "(", "cmd", "[", "0", "]", ")", "and", ...
Execute the command line command.
[ "Execute", "the", "command", "line", "command", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/reinforcement-learning/a3c/launcher.py#L46-L77
23,968
apache/incubator-mxnet
example/reinforcement-learning/a3c/launcher.py
submit
def submit(args): gpus = args.gpus.strip().split(',') """Submit function of local jobs.""" def mthread_submit(nworker, nserver, envs): """ customized submit script, that submit nslave jobs, each must contain args as parameter note this can be a lambda function containing additional p...
python
def submit(args): gpus = args.gpus.strip().split(',') """Submit function of local jobs.""" def mthread_submit(nworker, nserver, envs): """ customized submit script, that submit nslave jobs, each must contain args as parameter note this can be a lambda function containing additional p...
[ "def", "submit", "(", "args", ")", ":", "gpus", "=", "args", ".", "gpus", ".", "strip", "(", ")", ".", "split", "(", "','", ")", "def", "mthread_submit", "(", "nworker", ",", "nserver", ",", "envs", ")", ":", "\"\"\"\n customized submit script, that...
Submit function of local jobs.
[ "Submit", "function", "of", "local", "jobs", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/reinforcement-learning/a3c/launcher.py#L79-L106
23,969
apache/incubator-mxnet
example/ctc/ctc_metrics.py
CtcMetrics._remove_blank
def _remove_blank(l): """ Removes trailing zeros in the list of integers and returns a new list of integers""" ret = [] for i, _ in enumerate(l): if l[i] == 0: break ret.append(l[i]) return ret
python
def _remove_blank(l): """ Removes trailing zeros in the list of integers and returns a new list of integers""" ret = [] for i, _ in enumerate(l): if l[i] == 0: break ret.append(l[i]) return ret
[ "def", "_remove_blank", "(", "l", ")", ":", "ret", "=", "[", "]", "for", "i", ",", "_", "in", "enumerate", "(", "l", ")", ":", "if", "l", "[", "i", "]", "==", "0", ":", "break", "ret", ".", "append", "(", "l", "[", "i", "]", ")", "return", ...
Removes trailing zeros in the list of integers and returns a new list of integers
[ "Removes", "trailing", "zeros", "in", "the", "list", "of", "integers", "and", "returns", "a", "new", "list", "of", "integers" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/ctc/ctc_metrics.py#L54-L61
23,970
apache/incubator-mxnet
example/sparse/matrix_factorization/data.py
get_movielens_iter
def get_movielens_iter(filename, batch_size): """Not particularly fast code to parse the text file and load into NDArrays. return two data iters, one for train, the other for validation. """ logging.info("Preparing data iterators for " + filename + " ... ") user = [] item = [] score = [] ...
python
def get_movielens_iter(filename, batch_size): """Not particularly fast code to parse the text file and load into NDArrays. return two data iters, one for train, the other for validation. """ logging.info("Preparing data iterators for " + filename + " ... ") user = [] item = [] score = [] ...
[ "def", "get_movielens_iter", "(", "filename", ",", "batch_size", ")", ":", "logging", ".", "info", "(", "\"Preparing data iterators for \"", "+", "filename", "+", "\" ... \"", ")", "user", "=", "[", "]", "item", "=", "[", "]", "score", "=", "[", "]", "with...
Not particularly fast code to parse the text file and load into NDArrays. return two data iters, one for train, the other for validation.
[ "Not", "particularly", "fast", "code", "to", "parse", "the", "text", "file", "and", "load", "into", "NDArrays", ".", "return", "two", "data", "iters", "one", "for", "train", "the", "other", "for", "validation", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/sparse/matrix_factorization/data.py#L29-L56
23,971
apache/incubator-mxnet
plugin/opencv/opencv.py
imdecode
def imdecode(str_img, flag=1): """Decode image from str buffer. Wrapper for cv2.imdecode that uses mx.nd.NDArray Parameters ---------- str_img : str str buffer read from image file flag : int same as flag for cv2.imdecode Returns ------- img : NDArray decoded...
python
def imdecode(str_img, flag=1): """Decode image from str buffer. Wrapper for cv2.imdecode that uses mx.nd.NDArray Parameters ---------- str_img : str str buffer read from image file flag : int same as flag for cv2.imdecode Returns ------- img : NDArray decoded...
[ "def", "imdecode", "(", "str_img", ",", "flag", "=", "1", ")", ":", "hdl", "=", "NDArrayHandle", "(", ")", "check_call", "(", "_LIB", ".", "MXCVImdecode", "(", "ctypes", ".", "c_char_p", "(", "str_img", ")", ",", "mx_uint", "(", "len", "(", "str_img", ...
Decode image from str buffer. Wrapper for cv2.imdecode that uses mx.nd.NDArray Parameters ---------- str_img : str str buffer read from image file flag : int same as flag for cv2.imdecode Returns ------- img : NDArray decoded image in (width, height, channels) ...
[ "Decode", "image", "from", "str", "buffer", ".", "Wrapper", "for", "cv2", ".", "imdecode", "that", "uses", "mx", ".", "nd", ".", "NDArray" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/plugin/opencv/opencv.py#L29-L49
23,972
apache/incubator-mxnet
plugin/opencv/opencv.py
resize
def resize(src, size, interpolation=cv2.INTER_LINEAR): """Decode image from str buffer. Wrapper for cv2.imresize that uses mx.nd.NDArray Parameters ---------- src : NDArray image in (width, height, channels) size : tuple target size in (width, height) interpolation : int ...
python
def resize(src, size, interpolation=cv2.INTER_LINEAR): """Decode image from str buffer. Wrapper for cv2.imresize that uses mx.nd.NDArray Parameters ---------- src : NDArray image in (width, height, channels) size : tuple target size in (width, height) interpolation : int ...
[ "def", "resize", "(", "src", ",", "size", ",", "interpolation", "=", "cv2", ".", "INTER_LINEAR", ")", ":", "hdl", "=", "NDArrayHandle", "(", ")", "check_call", "(", "_LIB", ".", "MXCVResize", "(", "src", ".", "handle", ",", "mx_uint", "(", "size", "[",...
Decode image from str buffer. Wrapper for cv2.imresize that uses mx.nd.NDArray Parameters ---------- src : NDArray image in (width, height, channels) size : tuple target size in (width, height) interpolation : int same as interpolation for cv2.imresize Returns -...
[ "Decode", "image", "from", "str", "buffer", ".", "Wrapper", "for", "cv2", ".", "imresize", "that", "uses", "mx", ".", "nd", ".", "NDArray" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/plugin/opencv/opencv.py#L51-L72
23,973
apache/incubator-mxnet
plugin/opencv/opencv.py
copyMakeBorder
def copyMakeBorder(src, top, bot, left, right, border_type=cv2.BORDER_CONSTANT, value=0): """Pad image border Wrapper for cv2.copyMakeBorder that uses mx.nd.NDArray Parameters ---------- src : NDArray Image in (width, height, channels). Others are the same with cv2.copyMakeBorder ...
python
def copyMakeBorder(src, top, bot, left, right, border_type=cv2.BORDER_CONSTANT, value=0): """Pad image border Wrapper for cv2.copyMakeBorder that uses mx.nd.NDArray Parameters ---------- src : NDArray Image in (width, height, channels). Others are the same with cv2.copyMakeBorder ...
[ "def", "copyMakeBorder", "(", "src", ",", "top", ",", "bot", ",", "left", ",", "right", ",", "border_type", "=", "cv2", ".", "BORDER_CONSTANT", ",", "value", "=", "0", ")", ":", "hdl", "=", "NDArrayHandle", "(", ")", "check_call", "(", "_LIB", ".", "...
Pad image border Wrapper for cv2.copyMakeBorder that uses mx.nd.NDArray Parameters ---------- src : NDArray Image in (width, height, channels). Others are the same with cv2.copyMakeBorder Returns ------- img : NDArray padded image
[ "Pad", "image", "border", "Wrapper", "for", "cv2", ".", "copyMakeBorder", "that", "uses", "mx", ".", "nd", ".", "NDArray" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/plugin/opencv/opencv.py#L74-L94
23,974
apache/incubator-mxnet
plugin/opencv/opencv.py
random_crop
def random_crop(src, size): """Randomly crop src with size. Upsample result if src is smaller than size""" h, w, _ = src.shape new_w, new_h = scale_down((w, h), size) x0 = random.randint(0, w - new_w) y0 = random.randint(0, h - new_h) out = fixed_crop(src, x0, y0, new_w, new_h, size) retur...
python
def random_crop(src, size): """Randomly crop src with size. Upsample result if src is smaller than size""" h, w, _ = src.shape new_w, new_h = scale_down((w, h), size) x0 = random.randint(0, w - new_w) y0 = random.randint(0, h - new_h) out = fixed_crop(src, x0, y0, new_w, new_h, size) retur...
[ "def", "random_crop", "(", "src", ",", "size", ")", ":", "h", ",", "w", ",", "_", "=", "src", ".", "shape", "new_w", ",", "new_h", "=", "scale_down", "(", "(", "w", ",", "h", ")", ",", "size", ")", "x0", "=", "random", ".", "randint", "(", "0...
Randomly crop src with size. Upsample result if src is smaller than size
[ "Randomly", "crop", "src", "with", "size", ".", "Upsample", "result", "if", "src", "is", "smaller", "than", "size" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/plugin/opencv/opencv.py#L114-L123
23,975
apache/incubator-mxnet
plugin/opencv/opencv.py
random_size_crop
def random_size_crop(src, size, min_area=0.25, ratio=(3.0/4.0, 4.0/3.0)): """Randomly crop src with size. Randomize area and aspect ratio""" h, w, _ = src.shape area = w*h for _ in range(10): new_area = random.uniform(min_area, 1.0) * area new_ratio = random.uniform(*ratio) new_w...
python
def random_size_crop(src, size, min_area=0.25, ratio=(3.0/4.0, 4.0/3.0)): """Randomly crop src with size. Randomize area and aspect ratio""" h, w, _ = src.shape area = w*h for _ in range(10): new_area = random.uniform(min_area, 1.0) * area new_ratio = random.uniform(*ratio) new_w...
[ "def", "random_size_crop", "(", "src", ",", "size", ",", "min_area", "=", "0.25", ",", "ratio", "=", "(", "3.0", "/", "4.0", ",", "4.0", "/", "3.0", ")", ")", ":", "h", ",", "w", ",", "_", "=", "src", ".", "shape", "area", "=", "w", "*", "h",...
Randomly crop src with size. Randomize area and aspect ratio
[ "Randomly", "crop", "src", "with", "size", ".", "Randomize", "area", "and", "aspect", "ratio" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/plugin/opencv/opencv.py#L131-L153
23,976
apache/incubator-mxnet
plugin/opencv/opencv.py
ImageListIter.next
def next(self): """Move iterator position forward""" batch = mx.nd.zeros((self.batch_size, self.size[1], self.size[0], 3)) i = self.cur for i in range(self.cur, min(len(self.list), self.cur+self.batch_size)): str_img = open(self.root+self.list[i]+'.jpg').read() im...
python
def next(self): """Move iterator position forward""" batch = mx.nd.zeros((self.batch_size, self.size[1], self.size[0], 3)) i = self.cur for i in range(self.cur, min(len(self.list), self.cur+self.batch_size)): str_img = open(self.root+self.list[i]+'.jpg').read() im...
[ "def", "next", "(", "self", ")", ":", "batch", "=", "mx", ".", "nd", ".", "zeros", "(", "(", "self", ".", "batch_size", ",", "self", ".", "size", "[", "1", "]", ",", "self", ".", "size", "[", "0", "]", ",", "3", ")", ")", "i", "=", "self", ...
Move iterator position forward
[ "Move", "iterator", "position", "forward" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/plugin/opencv/opencv.py#L173-L188
23,977
apache/incubator-mxnet
example/speech_recognition/stt_metric.py
check_label_shapes
def check_label_shapes(labels, preds, shape=0): """Check to see if the two arrays are the same size.""" if shape == 0: label_shape, pred_shape = len(labels), len(preds) else: label_shape, pred_shape = labels.shape, preds.shape if label_shape != pred_shape: raise ValueError("Sha...
python
def check_label_shapes(labels, preds, shape=0): """Check to see if the two arrays are the same size.""" if shape == 0: label_shape, pred_shape = len(labels), len(preds) else: label_shape, pred_shape = labels.shape, preds.shape if label_shape != pred_shape: raise ValueError("Sha...
[ "def", "check_label_shapes", "(", "labels", ",", "preds", ",", "shape", "=", "0", ")", ":", "if", "shape", "==", "0", ":", "label_shape", ",", "pred_shape", "=", "len", "(", "labels", ")", ",", "len", "(", "preds", ")", "else", ":", "label_shape", ",...
Check to see if the two arrays are the same size.
[ "Check", "to", "see", "if", "the", "two", "arrays", "are", "the", "same", "size", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/speech_recognition/stt_metric.py#L25-L35
23,978
apache/incubator-mxnet
python/mxnet/contrib/onnx/onnx2mx/import_to_gluon.py
import_to_gluon
def import_to_gluon(model_file, ctx): """ Imports the ONNX model files, passed as a parameter, into Gluon SymbolBlock object. Parameters ---------- model_file : str ONNX model file name ctx : Context or list of Context Loads the model into one or many context(s). Returns ...
python
def import_to_gluon(model_file, ctx): """ Imports the ONNX model files, passed as a parameter, into Gluon SymbolBlock object. Parameters ---------- model_file : str ONNX model file name ctx : Context or list of Context Loads the model into one or many context(s). Returns ...
[ "def", "import_to_gluon", "(", "model_file", ",", "ctx", ")", ":", "graph", "=", "GraphProto", "(", ")", "try", ":", "import", "onnx", "except", "ImportError", ":", "raise", "ImportError", "(", "\"Onnx and protobuf need to be installed. Instructions to\"", "+", "\" ...
Imports the ONNX model files, passed as a parameter, into Gluon SymbolBlock object. Parameters ---------- model_file : str ONNX model file name ctx : Context or list of Context Loads the model into one or many context(s). Returns ------- sym_block : :class:`~mxnet.gluon.Sym...
[ "Imports", "the", "ONNX", "model", "files", "passed", "as", "a", "parameter", "into", "Gluon", "SymbolBlock", "object", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/contrib/onnx/onnx2mx/import_to_gluon.py#L24-L53
23,979
apache/incubator-mxnet
example/gluon/image_classification.py
get_model
def get_model(model, ctx, opt): """Model initialization.""" kwargs = {'ctx': ctx, 'pretrained': opt.use_pretrained, 'classes': classes} if model.startswith('resnet'): kwargs['thumbnail'] = opt.use_thumbnail elif model.startswith('vgg'): kwargs['batch_norm'] = opt.batch_norm net = mo...
python
def get_model(model, ctx, opt): """Model initialization.""" kwargs = {'ctx': ctx, 'pretrained': opt.use_pretrained, 'classes': classes} if model.startswith('resnet'): kwargs['thumbnail'] = opt.use_thumbnail elif model.startswith('vgg'): kwargs['batch_norm'] = opt.batch_norm net = mo...
[ "def", "get_model", "(", "model", ",", "ctx", ",", "opt", ")", ":", "kwargs", "=", "{", "'ctx'", ":", "ctx", ",", "'pretrained'", ":", "opt", ".", "use_pretrained", ",", "'classes'", ":", "classes", "}", "if", "model", ".", "startswith", "(", "'resnet'...
Model initialization.
[ "Model", "initialization", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/gluon/image_classification.py#L117-L134
23,980
apache/incubator-mxnet
example/gluon/image_classification.py
get_data_iters
def get_data_iters(dataset, batch_size, opt): """get dataset iterators""" if dataset == 'mnist': train_data, val_data = get_mnist_iterator(batch_size, (1, 28, 28), num_parts=kv.num_workers, part_index=kv.rank) elif dataset == 'cifar10': train...
python
def get_data_iters(dataset, batch_size, opt): """get dataset iterators""" if dataset == 'mnist': train_data, val_data = get_mnist_iterator(batch_size, (1, 28, 28), num_parts=kv.num_workers, part_index=kv.rank) elif dataset == 'cifar10': train...
[ "def", "get_data_iters", "(", "dataset", ",", "batch_size", ",", "opt", ")", ":", "if", "dataset", "==", "'mnist'", ":", "train_data", ",", "val_data", "=", "get_mnist_iterator", "(", "batch_size", ",", "(", "1", ",", "28", ",", "28", ")", ",", "num_part...
get dataset iterators
[ "get", "dataset", "iterators" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/gluon/image_classification.py#L138-L160
23,981
apache/incubator-mxnet
example/gluon/image_classification.py
update_learning_rate
def update_learning_rate(lr, trainer, epoch, ratio, steps): """Set the learning rate to the initial value decayed by ratio every N epochs.""" new_lr = lr * (ratio ** int(np.sum(np.array(steps) < epoch))) trainer.set_learning_rate(new_lr) return trainer
python
def update_learning_rate(lr, trainer, epoch, ratio, steps): """Set the learning rate to the initial value decayed by ratio every N epochs.""" new_lr = lr * (ratio ** int(np.sum(np.array(steps) < epoch))) trainer.set_learning_rate(new_lr) return trainer
[ "def", "update_learning_rate", "(", "lr", ",", "trainer", ",", "epoch", ",", "ratio", ",", "steps", ")", ":", "new_lr", "=", "lr", "*", "(", "ratio", "**", "int", "(", "np", ".", "sum", "(", "np", ".", "array", "(", "steps", ")", "<", "epoch", ")...
Set the learning rate to the initial value decayed by ratio every N epochs.
[ "Set", "the", "learning", "rate", "to", "the", "initial", "value", "decayed", "by", "ratio", "every", "N", "epochs", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/gluon/image_classification.py#L174-L178
23,982
apache/incubator-mxnet
python/mxnet/random.py
seed
def seed(seed_state, ctx="all"): """Seeds the random number generators in MXNet. This affects the behavior of modules in MXNet that uses random number generators, like the dropout operator and `NDArray`'s random sampling operators. Parameters ---------- seed_state : int The random numb...
python
def seed(seed_state, ctx="all"): """Seeds the random number generators in MXNet. This affects the behavior of modules in MXNet that uses random number generators, like the dropout operator and `NDArray`'s random sampling operators. Parameters ---------- seed_state : int The random numb...
[ "def", "seed", "(", "seed_state", ",", "ctx", "=", "\"all\"", ")", ":", "if", "not", "isinstance", "(", "seed_state", ",", "integer_types", ")", ":", "raise", "ValueError", "(", "'seed_state must be int'", ")", "seed_state", "=", "ctypes", ".", "c_int", "(",...
Seeds the random number generators in MXNet. This affects the behavior of modules in MXNet that uses random number generators, like the dropout operator and `NDArray`'s random sampling operators. Parameters ---------- seed_state : int The random number seed. ctx : Context The ...
[ "Seeds", "the", "random", "number", "generators", "in", "MXNet", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/random.py#L30-L100
23,983
apache/incubator-mxnet
python/mxnet/contrib/onnx/onnx2mx/_op_translations.py
random_uniform
def random_uniform(attrs, inputs, proto_obj): """Draw random samples from a uniform distribtuion.""" try: from onnx.mapping import TENSOR_TYPE_TO_NP_TYPE except ImportError: raise ImportError("Onnx and protobuf need to be installed. " "Instructions to install - http...
python
def random_uniform(attrs, inputs, proto_obj): """Draw random samples from a uniform distribtuion.""" try: from onnx.mapping import TENSOR_TYPE_TO_NP_TYPE except ImportError: raise ImportError("Onnx and protobuf need to be installed. " "Instructions to install - http...
[ "def", "random_uniform", "(", "attrs", ",", "inputs", ",", "proto_obj", ")", ":", "try", ":", "from", "onnx", ".", "mapping", "import", "TENSOR_TYPE_TO_NP_TYPE", "except", "ImportError", ":", "raise", "ImportError", "(", "\"Onnx and protobuf need to be installed. \"",...
Draw random samples from a uniform distribtuion.
[ "Draw", "random", "samples", "from", "a", "uniform", "distribtuion", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/contrib/onnx/onnx2mx/_op_translations.py#L30-L39
23,984
apache/incubator-mxnet
python/mxnet/contrib/onnx/onnx2mx/_op_translations.py
random_normal
def random_normal(attrs, inputs, proto_obj): """Draw random samples from a Gaussian distribution.""" try: from onnx.mapping import TENSOR_TYPE_TO_NP_TYPE except ImportError: raise ImportError("Onnx and protobuf need to be installed. " "Instructions to install - http...
python
def random_normal(attrs, inputs, proto_obj): """Draw random samples from a Gaussian distribution.""" try: from onnx.mapping import TENSOR_TYPE_TO_NP_TYPE except ImportError: raise ImportError("Onnx and protobuf need to be installed. " "Instructions to install - http...
[ "def", "random_normal", "(", "attrs", ",", "inputs", ",", "proto_obj", ")", ":", "try", ":", "from", "onnx", ".", "mapping", "import", "TENSOR_TYPE_TO_NP_TYPE", "except", "ImportError", ":", "raise", "ImportError", "(", "\"Onnx and protobuf need to be installed. \"", ...
Draw random samples from a Gaussian distribution.
[ "Draw", "random", "samples", "from", "a", "Gaussian", "distribution", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/contrib/onnx/onnx2mx/_op_translations.py#L41-L51
23,985
apache/incubator-mxnet
python/mxnet/contrib/onnx/onnx2mx/_op_translations.py
add
def add(attrs, inputs, proto_obj): """Adding two tensors""" new_attr = {} if 'broadcast' in attrs and attrs['broadcast'] == 1: broadcast_axis = attrs['axis'] op_value = translation_utils._fix_broadcast('broadcast_add', inputs, broadcast_ax...
python
def add(attrs, inputs, proto_obj): """Adding two tensors""" new_attr = {} if 'broadcast' in attrs and attrs['broadcast'] == 1: broadcast_axis = attrs['axis'] op_value = translation_utils._fix_broadcast('broadcast_add', inputs, broadcast_ax...
[ "def", "add", "(", "attrs", ",", "inputs", ",", "proto_obj", ")", ":", "new_attr", "=", "{", "}", "if", "'broadcast'", "in", "attrs", "and", "attrs", "[", "'broadcast'", "]", "==", "1", ":", "broadcast_axis", "=", "attrs", "[", "'axis'", "]", "op_value...
Adding two tensors
[ "Adding", "two", "tensors" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/contrib/onnx/onnx2mx/_op_translations.py#L66-L75
23,986
apache/incubator-mxnet
python/mxnet/contrib/onnx/onnx2mx/_op_translations.py
mean
def mean(attrs, inputs, proto_obj): """Mean of all the input tensors.""" concat_input = [symbol.expand_dims(op_input, axis=0) for op_input in inputs] concat_sym = symbol.concat(*concat_input, dim=0) mean_sym = symbol.mean(concat_sym, axis=0) return mean_sym, attrs, inputs
python
def mean(attrs, inputs, proto_obj): """Mean of all the input tensors.""" concat_input = [symbol.expand_dims(op_input, axis=0) for op_input in inputs] concat_sym = symbol.concat(*concat_input, dim=0) mean_sym = symbol.mean(concat_sym, axis=0) return mean_sym, attrs, inputs
[ "def", "mean", "(", "attrs", ",", "inputs", ",", "proto_obj", ")", ":", "concat_input", "=", "[", "symbol", ".", "expand_dims", "(", "op_input", ",", "axis", "=", "0", ")", "for", "op_input", "in", "inputs", "]", "concat_sym", "=", "symbol", ".", "conc...
Mean of all the input tensors.
[ "Mean", "of", "all", "the", "input", "tensors", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/contrib/onnx/onnx2mx/_op_translations.py#L110-L115
23,987
apache/incubator-mxnet
python/mxnet/contrib/onnx/onnx2mx/_op_translations.py
argmax
def argmax(attrs, inputs, proto_obj): """Returns indices of the maximum values along an axis""" axis = attrs.get('axis', 0) keepdims = attrs.get('keepdims', 1) argmax_op = symbol.argmax(inputs[0], axis=axis, keepdims=keepdims) # onnx argmax operator always expects int64 as output type cast_attrs...
python
def argmax(attrs, inputs, proto_obj): """Returns indices of the maximum values along an axis""" axis = attrs.get('axis', 0) keepdims = attrs.get('keepdims', 1) argmax_op = symbol.argmax(inputs[0], axis=axis, keepdims=keepdims) # onnx argmax operator always expects int64 as output type cast_attrs...
[ "def", "argmax", "(", "attrs", ",", "inputs", ",", "proto_obj", ")", ":", "axis", "=", "attrs", ".", "get", "(", "'axis'", ",", "0", ")", "keepdims", "=", "attrs", ".", "get", "(", "'keepdims'", ",", "1", ")", "argmax_op", "=", "symbol", ".", "argm...
Returns indices of the maximum values along an axis
[ "Returns", "indices", "of", "the", "maximum", "values", "along", "an", "axis" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/contrib/onnx/onnx2mx/_op_translations.py#L146-L153
23,988
apache/incubator-mxnet
python/mxnet/contrib/onnx/onnx2mx/_op_translations.py
argmin
def argmin(attrs, inputs, proto_obj): """Returns indices of the minimum values along an axis.""" axis = attrs.get('axis', 0) keepdims = attrs.get('keepdims', 1) argmin_op = symbol.argmin(inputs[0], axis=axis, keepdims=keepdims) # onnx argmax operator always expects int64 as output type cast_attr...
python
def argmin(attrs, inputs, proto_obj): """Returns indices of the minimum values along an axis.""" axis = attrs.get('axis', 0) keepdims = attrs.get('keepdims', 1) argmin_op = symbol.argmin(inputs[0], axis=axis, keepdims=keepdims) # onnx argmax operator always expects int64 as output type cast_attr...
[ "def", "argmin", "(", "attrs", ",", "inputs", ",", "proto_obj", ")", ":", "axis", "=", "attrs", ".", "get", "(", "'axis'", ",", "0", ")", "keepdims", "=", "attrs", ".", "get", "(", "'keepdims'", ",", "1", ")", "argmin_op", "=", "symbol", ".", "argm...
Returns indices of the minimum values along an axis.
[ "Returns", "indices", "of", "the", "minimum", "values", "along", "an", "axis", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/contrib/onnx/onnx2mx/_op_translations.py#L155-L162
23,989
apache/incubator-mxnet
python/mxnet/contrib/onnx/onnx2mx/_op_translations.py
maximum
def maximum(attrs, inputs, proto_obj): """ Elementwise maximum of arrays. MXNet maximum compares only two symbols at a time. ONNX can send more than two to compare. Breaking into multiple mxnet ops to compare two symbols at a time """ if len(inputs) > 1: mxnet_op = symbol.maximum(inp...
python
def maximum(attrs, inputs, proto_obj): """ Elementwise maximum of arrays. MXNet maximum compares only two symbols at a time. ONNX can send more than two to compare. Breaking into multiple mxnet ops to compare two symbols at a time """ if len(inputs) > 1: mxnet_op = symbol.maximum(inp...
[ "def", "maximum", "(", "attrs", ",", "inputs", ",", "proto_obj", ")", ":", "if", "len", "(", "inputs", ")", ">", "1", ":", "mxnet_op", "=", "symbol", ".", "maximum", "(", "inputs", "[", "0", "]", ",", "inputs", "[", "1", "]", ")", "for", "op_inpu...
Elementwise maximum of arrays. MXNet maximum compares only two symbols at a time. ONNX can send more than two to compare. Breaking into multiple mxnet ops to compare two symbols at a time
[ "Elementwise", "maximum", "of", "arrays", ".", "MXNet", "maximum", "compares", "only", "two", "symbols", "at", "a", "time", ".", "ONNX", "can", "send", "more", "than", "two", "to", "compare", ".", "Breaking", "into", "multiple", "mxnet", "ops", "to", "comp...
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/contrib/onnx/onnx2mx/_op_translations.py#L164-L177
23,990
apache/incubator-mxnet
python/mxnet/contrib/onnx/onnx2mx/_op_translations.py
minimum
def minimum(attrs, inputs, proto_obj): """Elementwise minimum of arrays.""" # MXNet minimum compares only two symbols at a time. # ONNX can send more than two to compare. # Breaking into multiple mxnet ops to compare two symbols at a time if len(inputs) > 1: mxnet_op = symbol.minimum(inputs[...
python
def minimum(attrs, inputs, proto_obj): """Elementwise minimum of arrays.""" # MXNet minimum compares only two symbols at a time. # ONNX can send more than two to compare. # Breaking into multiple mxnet ops to compare two symbols at a time if len(inputs) > 1: mxnet_op = symbol.minimum(inputs[...
[ "def", "minimum", "(", "attrs", ",", "inputs", ",", "proto_obj", ")", ":", "# MXNet minimum compares only two symbols at a time.", "# ONNX can send more than two to compare.", "# Breaking into multiple mxnet ops to compare two symbols at a time", "if", "len", "(", "inputs", ")", ...
Elementwise minimum of arrays.
[ "Elementwise", "minimum", "of", "arrays", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/contrib/onnx/onnx2mx/_op_translations.py#L179-L190
23,991
apache/incubator-mxnet
python/mxnet/contrib/onnx/onnx2mx/_op_translations.py
concat
def concat(attrs, inputs, proto_obj): """ Joins input arrays along a given axis. """ new_attrs = translation_utils._fix_attribute_names(attrs, {'axis': 'dim'}) return 'concat', new_attrs, inputs
python
def concat(attrs, inputs, proto_obj): """ Joins input arrays along a given axis. """ new_attrs = translation_utils._fix_attribute_names(attrs, {'axis': 'dim'}) return 'concat', new_attrs, inputs
[ "def", "concat", "(", "attrs", ",", "inputs", ",", "proto_obj", ")", ":", "new_attrs", "=", "translation_utils", ".", "_fix_attribute_names", "(", "attrs", ",", "{", "'axis'", ":", "'dim'", "}", ")", "return", "'concat'", ",", "new_attrs", ",", "inputs" ]
Joins input arrays along a given axis.
[ "Joins", "input", "arrays", "along", "a", "given", "axis", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/contrib/onnx/onnx2mx/_op_translations.py#L219-L222
23,992
apache/incubator-mxnet
python/mxnet/contrib/onnx/onnx2mx/_op_translations.py
pad
def pad(attrs, inputs, proto_obj): """ Add padding to input tensor""" new_attrs = translation_utils._fix_attribute_names(attrs, {'pads' : 'pad_width', 'value' : 'constant_value' }) n...
python
def pad(attrs, inputs, proto_obj): """ Add padding to input tensor""" new_attrs = translation_utils._fix_attribute_names(attrs, {'pads' : 'pad_width', 'value' : 'constant_value' }) n...
[ "def", "pad", "(", "attrs", ",", "inputs", ",", "proto_obj", ")", ":", "new_attrs", "=", "translation_utils", ".", "_fix_attribute_names", "(", "attrs", ",", "{", "'pads'", ":", "'pad_width'", ",", "'value'", ":", "'constant_value'", "}", ")", "new_attrs", "...
Add padding to input tensor
[ "Add", "padding", "to", "input", "tensor" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/contrib/onnx/onnx2mx/_op_translations.py#L241-L247
23,993
apache/incubator-mxnet
python/mxnet/contrib/onnx/onnx2mx/_op_translations.py
instance_norm
def instance_norm(attrs, inputs, proto_obj): """Instance Normalization.""" new_attrs = translation_utils._fix_attribute_names(attrs, {'epsilon' : 'eps'}) new_attrs['eps'] = attrs.get('epsilon', 1e-5) return 'InstanceNorm', new_attrs, inputs
python
def instance_norm(attrs, inputs, proto_obj): """Instance Normalization.""" new_attrs = translation_utils._fix_attribute_names(attrs, {'epsilon' : 'eps'}) new_attrs['eps'] = attrs.get('epsilon', 1e-5) return 'InstanceNorm', new_attrs, inputs
[ "def", "instance_norm", "(", "attrs", ",", "inputs", ",", "proto_obj", ")", ":", "new_attrs", "=", "translation_utils", ".", "_fix_attribute_names", "(", "attrs", ",", "{", "'epsilon'", ":", "'eps'", "}", ")", "new_attrs", "[", "'eps'", "]", "=", "attrs", ...
Instance Normalization.
[ "Instance", "Normalization", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/contrib/onnx/onnx2mx/_op_translations.py#L268-L272
23,994
apache/incubator-mxnet
python/mxnet/contrib/onnx/onnx2mx/_op_translations.py
leaky_relu
def leaky_relu(attrs, inputs, proto_obj): """Leaky Relu function""" if 'alpha' in attrs: new_attrs = translation_utils._fix_attribute_names(attrs, {'alpha' : 'slope'}) else: new_attrs = translation_utils._add_extra_attributes(attrs, {'slope': 0.01}) return 'LeakyReLU', new_attrs, inputs
python
def leaky_relu(attrs, inputs, proto_obj): """Leaky Relu function""" if 'alpha' in attrs: new_attrs = translation_utils._fix_attribute_names(attrs, {'alpha' : 'slope'}) else: new_attrs = translation_utils._add_extra_attributes(attrs, {'slope': 0.01}) return 'LeakyReLU', new_attrs, inputs
[ "def", "leaky_relu", "(", "attrs", ",", "inputs", ",", "proto_obj", ")", ":", "if", "'alpha'", "in", "attrs", ":", "new_attrs", "=", "translation_utils", ".", "_fix_attribute_names", "(", "attrs", ",", "{", "'alpha'", ":", "'slope'", "}", ")", "else", ":",...
Leaky Relu function
[ "Leaky", "Relu", "function" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/contrib/onnx/onnx2mx/_op_translations.py#L274-L280
23,995
apache/incubator-mxnet
python/mxnet/contrib/onnx/onnx2mx/_op_translations.py
softmax
def softmax(attrs, inputs, proto_obj): """Softmax function.""" if 'axis' not in attrs: attrs = translation_utils._add_extra_attributes(attrs, {'axis': 1}) return 'softmax', attrs, inputs
python
def softmax(attrs, inputs, proto_obj): """Softmax function.""" if 'axis' not in attrs: attrs = translation_utils._add_extra_attributes(attrs, {'axis': 1}) return 'softmax', attrs, inputs
[ "def", "softmax", "(", "attrs", ",", "inputs", ",", "proto_obj", ")", ":", "if", "'axis'", "not", "in", "attrs", ":", "attrs", "=", "translation_utils", ".", "_add_extra_attributes", "(", "attrs", ",", "{", "'axis'", ":", "1", "}", ")", "return", "'softm...
Softmax function.
[ "Softmax", "function", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/contrib/onnx/onnx2mx/_op_translations.py#L301-L305
23,996
apache/incubator-mxnet
python/mxnet/contrib/onnx/onnx2mx/_op_translations.py
softplus
def softplus(attrs, inputs, proto_obj): """Applies the sofplus activation function element-wise to the input.""" new_attrs = translation_utils._add_extra_attributes(attrs, {'act_type' : 'softrelu'}) return 'Activation', new_attrs, inputs
python
def softplus(attrs, inputs, proto_obj): """Applies the sofplus activation function element-wise to the input.""" new_attrs = translation_utils._add_extra_attributes(attrs, {'act_type' : 'softrelu'}) return 'Activation', new_attrs, inputs
[ "def", "softplus", "(", "attrs", ",", "inputs", ",", "proto_obj", ")", ":", "new_attrs", "=", "translation_utils", ".", "_add_extra_attributes", "(", "attrs", ",", "{", "'act_type'", ":", "'softrelu'", "}", ")", "return", "'Activation'", ",", "new_attrs", ",",...
Applies the sofplus activation function element-wise to the input.
[ "Applies", "the", "sofplus", "activation", "function", "element", "-", "wise", "to", "the", "input", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/contrib/onnx/onnx2mx/_op_translations.py#L312-L315
23,997
apache/incubator-mxnet
python/mxnet/contrib/onnx/onnx2mx/_op_translations.py
deconv
def deconv(attrs, inputs, proto_obj): """Computes transposed convolution of the input tensor.""" new_attrs = translation_utils._fix_attribute_names(attrs, {'kernel_shape' : 'kernel', 'strides' : 'stride', ...
python
def deconv(attrs, inputs, proto_obj): """Computes transposed convolution of the input tensor.""" new_attrs = translation_utils._fix_attribute_names(attrs, {'kernel_shape' : 'kernel', 'strides' : 'stride', ...
[ "def", "deconv", "(", "attrs", ",", "inputs", ",", "proto_obj", ")", ":", "new_attrs", "=", "translation_utils", ".", "_fix_attribute_names", "(", "attrs", ",", "{", "'kernel_shape'", ":", "'kernel'", ",", "'strides'", ":", "'stride'", ",", "'pads'", ":", "'...
Computes transposed convolution of the input tensor.
[ "Computes", "transposed", "convolution", "of", "the", "input", "tensor", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/contrib/onnx/onnx2mx/_op_translations.py#L348-L377
23,998
apache/incubator-mxnet
python/mxnet/contrib/onnx/onnx2mx/_op_translations.py
global_maxpooling
def global_maxpooling(attrs, inputs, proto_obj): """Performs max pooling on the input.""" new_attrs = translation_utils._add_extra_attributes(attrs, {'global_pool': True, 'kernel': (1, 1), ...
python
def global_maxpooling(attrs, inputs, proto_obj): """Performs max pooling on the input.""" new_attrs = translation_utils._add_extra_attributes(attrs, {'global_pool': True, 'kernel': (1, 1), ...
[ "def", "global_maxpooling", "(", "attrs", ",", "inputs", ",", "proto_obj", ")", ":", "new_attrs", "=", "translation_utils", ".", "_add_extra_attributes", "(", "attrs", ",", "{", "'global_pool'", ":", "True", ",", "'kernel'", ":", "(", "1", ",", "1", ")", "...
Performs max pooling on the input.
[ "Performs", "max", "pooling", "on", "the", "input", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/contrib/onnx/onnx2mx/_op_translations.py#L390-L395
23,999
apache/incubator-mxnet
python/mxnet/contrib/onnx/onnx2mx/_op_translations.py
global_avgpooling
def global_avgpooling(attrs, inputs, proto_obj): """Performs avg pooling on the input.""" new_attrs = translation_utils._add_extra_attributes(attrs, {'global_pool': True, 'kernel': (1, 1), ...
python
def global_avgpooling(attrs, inputs, proto_obj): """Performs avg pooling on the input.""" new_attrs = translation_utils._add_extra_attributes(attrs, {'global_pool': True, 'kernel': (1, 1), ...
[ "def", "global_avgpooling", "(", "attrs", ",", "inputs", ",", "proto_obj", ")", ":", "new_attrs", "=", "translation_utils", ".", "_add_extra_attributes", "(", "attrs", ",", "{", "'global_pool'", ":", "True", ",", "'kernel'", ":", "(", "1", ",", "1", ")", "...
Performs avg pooling on the input.
[ "Performs", "avg", "pooling", "on", "the", "input", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/contrib/onnx/onnx2mx/_op_translations.py#L398-L403