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", "=", "lambda", "x", ":", "x", ".", "prTotal", "*", "x", ".", "prText", ")", "return", "[", "x", ".", "labeling", "for", "x", "in", "sortedBeams", "]" ]
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') loc = mx.symbol.Pooling(data=loc, kernel=(2, 2), stride=(2, 2), pool_type='max') loc = mx.symbol.Convolution(data=loc, num_filter=60, kernel=(3, 3), stride=(1,1), pad=(1, 1)) loc = mx.symbol.Activation(data = loc, act_type='relu') loc = mx.symbol.Pooling(data=loc, global_pool=True, kernel=(2, 2), pool_type='avg') loc = mx.symbol.Flatten(data=loc) loc = mx.symbol.FullyConnected(data=loc, num_hidden=6, name="stn_loc", attr=attr) return loc
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') loc = mx.symbol.Pooling(data=loc, kernel=(2, 2), stride=(2, 2), pool_type='max') loc = mx.symbol.Convolution(data=loc, num_filter=60, kernel=(3, 3), stride=(1,1), pad=(1, 1)) loc = mx.symbol.Activation(data = loc, act_type='relu') loc = mx.symbol.Pooling(data=loc, global_pool=True, kernel=(2, 2), pool_type='avg') loc = mx.symbol.Flatten(data=loc) loc = mx.symbol.FullyConnected(data=loc, num_hidden=6, name="stn_loc", attr=attr) return loc
[ "def", "get_loc", "(", "data", ",", "attr", "=", "{", "'lr_mult'", ":", "'0.01'", "}", ")", ":", "loc", "=", "mx", ".", "symbol", ".", "Convolution", "(", "data", "=", "data", ",", "num_filter", "=", "30", ",", "kernel", "=", "(", "5", ",", "5", ")", ",", "stride", "=", "(", "2", ",", "2", ")", ")", "loc", "=", "mx", ".", "symbol", ".", "Activation", "(", "data", "=", "loc", ",", "act_type", "=", "'relu'", ")", "loc", "=", "mx", ".", "symbol", ".", "Pooling", "(", "data", "=", "loc", ",", "kernel", "=", "(", "2", ",", "2", ")", ",", "stride", "=", "(", "2", ",", "2", ")", ",", "pool_type", "=", "'max'", ")", "loc", "=", "mx", ".", "symbol", ".", "Convolution", "(", "data", "=", "loc", ",", "num_filter", "=", "60", ",", "kernel", "=", "(", "3", ",", "3", ")", ",", "stride", "=", "(", "1", ",", "1", ")", ",", "pad", "=", "(", "1", ",", "1", ")", ")", "loc", "=", "mx", ".", "symbol", ".", "Activation", "(", "data", "=", "loc", ",", "act_type", "=", "'relu'", ")", "loc", "=", "mx", ".", "symbol", ".", "Pooling", "(", "data", "=", "loc", ",", "global_pool", "=", "True", ",", "kernel", "=", "(", "2", ",", "2", ")", ",", "pool_type", "=", "'avg'", ")", "loc", "=", "mx", ".", "symbol", ".", "Flatten", "(", "data", "=", "loc", ")", "loc", "=", "mx", ".", "symbol", ".", "FullyConnected", "(", "data", "=", "loc", ",", "num_hidden", "=", "6", ",", "name", "=", "\"stn_loc\"", ",", "attr", "=", "attr", ")", "return", "loc" ]
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 load model epoch data_shape : int resize image shape mean_pixels : tuple (float, float, float) mean pixel values (R, G, B) ctx : mx.ctx running context, mx.cpu() or mx.gpu(?) num_class : int number of classes nms_thresh : float non-maximum suppression threshold force_nms : bool force suppress different categories """ if net is not None: if isinstance(data_shape, tuple): data_shape = data_shape[0] net = get_symbol(net, data_shape, num_classes=num_class, nms_thresh=nms_thresh, force_nms=force_nms, nms_topk=nms_topk) detector = Detector(net, prefix, epoch, data_shape, mean_pixels, ctx=ctx) return detector
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 load model epoch data_shape : int resize image shape mean_pixels : tuple (float, float, float) mean pixel values (R, G, B) ctx : mx.ctx running context, mx.cpu() or mx.gpu(?) num_class : int number of classes nms_thresh : float non-maximum suppression threshold force_nms : bool force suppress different categories """ if net is not None: if isinstance(data_shape, tuple): data_shape = data_shape[0] net = get_symbol(net, data_shape, num_classes=num_class, nms_thresh=nms_thresh, force_nms=force_nms, nms_topk=nms_topk) detector = Detector(net, prefix, epoch, data_shape, mean_pixels, ctx=ctx) return detector
[ "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", "not", "None", ":", "if", "isinstance", "(", "data_shape", ",", "tuple", ")", ":", "data_shape", "=", "data_shape", "[", "0", "]", "net", "=", "get_symbol", "(", "net", ",", "data_shape", ",", "num_classes", "=", "num_class", ",", "nms_thresh", "=", "nms_thresh", ",", "force_nms", "=", "force_nms", ",", "nms_topk", "=", "nms_topk", ")", "detector", "=", "Detector", "(", "net", ",", "prefix", ",", "epoch", ",", "data_shape", ",", "mean_pixels", ",", "ctx", "=", "ctx", ")", "return", "detector" ]
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) ctx : mx.ctx running context, mx.cpu() or mx.gpu(?) num_class : int number of classes nms_thresh : float non-maximum suppression threshold force_nms : bool force suppress different categories
[ "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", data_shape_str) return data_shape
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", data_shape_str) return data_shape
[ "def", "parse_data_shape", "(", "data_shape_str", ")", ":", "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\"", ",", "data_shape_str", ")", "return", "data_shape" ]
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) net = mx.sym.Convolution(source, kernel=(5, 5), num_filter=40) net = mx.sym.BatchNorm(net, fix_gamma=True) net = mx.sym.Activation(net, act_type="relu") net = mx.sym.Pooling(net, pool_type="max", kernel=(2,2), stride=(2,2)) net = mx.sym.Convolution(net, kernel=(3, 3), num_filter=40) net = mx.sym.BatchNorm(net, fix_gamma=True) net = mx.sym.Activation(net, act_type="relu") net = mx.sym.Pooling(net, pool_type="max", kernel=(2,2), stride=(2,2)) # first fullc flatten = mx.symbol.Flatten(net) flatten = mx.symbol.Dropout(flatten) fc1 = mx.symbol.FullyConnected(data=flatten, num_hidden=600) # Name the final layer as softmax so it auto matches the naming of data iterator # Otherwise we can also change the provide_data in the data iter return mx.symbol.LogisticRegressionOutput(data=fc1, name='softmax')
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) net = mx.sym.Convolution(source, kernel=(5, 5), num_filter=40) net = mx.sym.BatchNorm(net, fix_gamma=True) net = mx.sym.Activation(net, act_type="relu") net = mx.sym.Pooling(net, pool_type="max", kernel=(2,2), stride=(2,2)) net = mx.sym.Convolution(net, kernel=(3, 3), num_filter=40) net = mx.sym.BatchNorm(net, fix_gamma=True) net = mx.sym.Activation(net, act_type="relu") net = mx.sym.Pooling(net, pool_type="max", kernel=(2,2), stride=(2,2)) # first fullc flatten = mx.symbol.Flatten(net) flatten = mx.symbol.Dropout(flatten) fc1 = mx.symbol.FullyConnected(data=flatten, num_hidden=600) # Name the final layer as softmax so it auto matches the naming of data iterator # Otherwise we can also change the provide_data in the data iter return mx.symbol.LogisticRegressionOutput(data=fc1, name='softmax')
[ "def", "get_lenet", "(", ")", ":", "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", ")", "net", "=", "mx", ".", "sym", ".", "Convolution", "(", "source", ",", "kernel", "=", "(", "5", ",", "5", ")", ",", "num_filter", "=", "40", ")", "net", "=", "mx", ".", "sym", ".", "BatchNorm", "(", "net", ",", "fix_gamma", "=", "True", ")", "net", "=", "mx", ".", "sym", ".", "Activation", "(", "net", ",", "act_type", "=", "\"relu\"", ")", "net", "=", "mx", ".", "sym", ".", "Pooling", "(", "net", ",", "pool_type", "=", "\"max\"", ",", "kernel", "=", "(", "2", ",", "2", ")", ",", "stride", "=", "(", "2", ",", "2", ")", ")", "net", "=", "mx", ".", "sym", ".", "Convolution", "(", "net", ",", "kernel", "=", "(", "3", ",", "3", ")", ",", "num_filter", "=", "40", ")", "net", "=", "mx", ".", "sym", ".", "BatchNorm", "(", "net", ",", "fix_gamma", "=", "True", ")", "net", "=", "mx", ".", "sym", ".", "Activation", "(", "net", ",", "act_type", "=", "\"relu\"", ")", "net", "=", "mx", ".", "sym", ".", "Pooling", "(", "net", ",", "pool_type", "=", "\"max\"", ",", "kernel", "=", "(", "2", ",", "2", ")", ",", "stride", "=", "(", "2", ",", "2", ")", ")", "# first fullc", "flatten", "=", "mx", ".", "symbol", ".", "Flatten", "(", "net", ")", "flatten", "=", "mx", ".", "symbol", ".", "Dropout", "(", "flatten", ")", "fc1", "=", "mx", ".", "symbol", ".", "FullyConnected", "(", "data", "=", "flatten", ",", "num_hidden", "=", "600", ")", "# Name the final layer as softmax so it auto matches the naming of data iterator", "# Otherwise we can also change the provide_data in the data iter", "return", "mx", ".", "symbol", ".", "LogisticRegressionOutput", "(", "data", "=", "fc1", ",", "name", "=", "'softmax'", ")" ]
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", "[", "i", ",", "j", "]", ">", "pred", "[", "i", ",", "j", "+", "1", "]", ":", "pred", "[", "i", ",", "j", "+", "1", "]", "=", "pred", "[", "i", ",", "j", "]", "return", "np", ".", "sum", "(", "np", ".", "square", "(", "label", "-", "pred", ")", ")", "/", "label", ".", "size" ]
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 < np.arange(600)) for x in diastole ], dtype=np.uint8) return systole_encode, diastole_encode
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 < np.arange(600)) for x in diastole ], dtype=np.uint8) return systole_encode, diastole_encode
[ "def", "encode_label", "(", "label_data", ")", ":", "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", "<", "np", ".", "arange", "(", "600", ")", ")", "for", "x", "in", "diastole", "]", ",", "dtype", "=", "np", ".", "uint8", ")", "return", "systole_encode", ",", "diastole_encode" ]
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 two arguments as input and outputs a tuple of two elements, as illustrated below:: out, states = body(data1, states) data1 can be either an NDArray or a list of NDArrays. If data is an NDArray, data1 is an NDArray. Otherwise, data1 is a list of NDArrays and has the same size as data. states is a list of NDArrays and have the same size as init_states. Similarly, out can be either an NDArray or a list of NDArrays, which are concatenated as the first output of foreach; states from the last execution of body are the second output of foreach. The computation done by this operator is equivalent to the pseudo code below when the input data is NDArray:: states = init_states outs = [] for i in data.shape[0]: s = data[i] out, states = body(s, states) outs.append(out) outs = stack(*outs) Parameters ---------- body : a Python function. Define computation in an iteration. data: an NDArray or a list of NDArrays. The input data. init_states: an NDArray or nested lists of NDArrays. The initial values of the loop states. name: string. The name of the operator. Returns ------- outputs: an NDArray or nested lists of NDArrays. The output data concatenated from the output of all iterations. states: an NDArray or nested lists of NDArrays. The loop states in the last iteration. Examples -------- >>> step = lambda data, states: (data + states[0], [states[0] * 2]) >>> data = mx.nd.random.uniform(shape=(2, 10)) >>> states = [mx.nd.random.uniform(shape=(10))] >>> outs, states = mx.nd.contrib.foreach(step, data, states) """ def check_input(inputs, in_type, msg): is_NDArray_or_list = True if isinstance(inputs, list): for i in inputs: if not isinstance(i, in_type): is_NDArray_or_list = False break else: is_NDArray_or_list = isinstance(inputs, in_type) assert is_NDArray_or_list, msg flatten, _ = _flatten(data, "foreach input") check_input(flatten, ndarray.NDArray, "data should be an NDArray or a nested list of NDArrays") flatten, _ = _flatten(init_states, "foreach states") check_input(flatten, ndarray.NDArray, "init_states should be an NDArray or a nested list of NDArrays") not_data_list = isinstance(data, ndarray.NDArray) num_iters = data.shape[0] if not_data_list else data[0].shape[0] states = init_states outputs = [] for i in range(num_iters): if not_data_list: eles = data[i] else: eles = [d[i] for d in data] outs, states = body(eles, states) outs, out_fmt = _flatten(outs, "foreach output") outputs.append(outs) outputs = zip(*outputs) tmp_outputs = [] for out in outputs: tmp_outputs.append(ndarray.op.stack(*out)) outputs = tmp_outputs outputs, _ = _regroup(outputs, out_fmt) return (outputs, states)
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 two arguments as input and outputs a tuple of two elements, as illustrated below:: out, states = body(data1, states) data1 can be either an NDArray or a list of NDArrays. If data is an NDArray, data1 is an NDArray. Otherwise, data1 is a list of NDArrays and has the same size as data. states is a list of NDArrays and have the same size as init_states. Similarly, out can be either an NDArray or a list of NDArrays, which are concatenated as the first output of foreach; states from the last execution of body are the second output of foreach. The computation done by this operator is equivalent to the pseudo code below when the input data is NDArray:: states = init_states outs = [] for i in data.shape[0]: s = data[i] out, states = body(s, states) outs.append(out) outs = stack(*outs) Parameters ---------- body : a Python function. Define computation in an iteration. data: an NDArray or a list of NDArrays. The input data. init_states: an NDArray or nested lists of NDArrays. The initial values of the loop states. name: string. The name of the operator. Returns ------- outputs: an NDArray or nested lists of NDArrays. The output data concatenated from the output of all iterations. states: an NDArray or nested lists of NDArrays. The loop states in the last iteration. Examples -------- >>> step = lambda data, states: (data + states[0], [states[0] * 2]) >>> data = mx.nd.random.uniform(shape=(2, 10)) >>> states = [mx.nd.random.uniform(shape=(10))] >>> outs, states = mx.nd.contrib.foreach(step, data, states) """ def check_input(inputs, in_type, msg): is_NDArray_or_list = True if isinstance(inputs, list): for i in inputs: if not isinstance(i, in_type): is_NDArray_or_list = False break else: is_NDArray_or_list = isinstance(inputs, in_type) assert is_NDArray_or_list, msg flatten, _ = _flatten(data, "foreach input") check_input(flatten, ndarray.NDArray, "data should be an NDArray or a nested list of NDArrays") flatten, _ = _flatten(init_states, "foreach states") check_input(flatten, ndarray.NDArray, "init_states should be an NDArray or a nested list of NDArrays") not_data_list = isinstance(data, ndarray.NDArray) num_iters = data.shape[0] if not_data_list else data[0].shape[0] states = init_states outputs = [] for i in range(num_iters): if not_data_list: eles = data[i] else: eles = [d[i] for d in data] outs, states = body(eles, states) outs, out_fmt = _flatten(outs, "foreach output") outputs.append(outs) outputs = zip(*outputs) tmp_outputs = [] for out in outputs: tmp_outputs.append(ndarray.op.stack(*out)) outputs = tmp_outputs outputs, _ = _regroup(outputs, out_fmt) return (outputs, states)
[ "def", "foreach", "(", "body", ",", "data", ",", "init_states", ")", ":", "def", "check_input", "(", "inputs", ",", "in_type", ",", "msg", ")", ":", "is_NDArray_or_list", "=", "True", "if", "isinstance", "(", "inputs", ",", "list", ")", ":", "for", "i", "in", "inputs", ":", "if", "not", "isinstance", "(", "i", ",", "in_type", ")", ":", "is_NDArray_or_list", "=", "False", "break", "else", ":", "is_NDArray_or_list", "=", "isinstance", "(", "inputs", ",", "in_type", ")", "assert", "is_NDArray_or_list", ",", "msg", "flatten", ",", "_", "=", "_flatten", "(", "data", ",", "\"foreach input\"", ")", "check_input", "(", "flatten", ",", "ndarray", ".", "NDArray", ",", "\"data should be an NDArray or a nested list of NDArrays\"", ")", "flatten", ",", "_", "=", "_flatten", "(", "init_states", ",", "\"foreach states\"", ")", "check_input", "(", "flatten", ",", "ndarray", ".", "NDArray", ",", "\"init_states should be an NDArray or a nested list of NDArrays\"", ")", "not_data_list", "=", "isinstance", "(", "data", ",", "ndarray", ".", "NDArray", ")", "num_iters", "=", "data", ".", "shape", "[", "0", "]", "if", "not_data_list", "else", "data", "[", "0", "]", ".", "shape", "[", "0", "]", "states", "=", "init_states", "outputs", "=", "[", "]", "for", "i", "in", "range", "(", "num_iters", ")", ":", "if", "not_data_list", ":", "eles", "=", "data", "[", "i", "]", "else", ":", "eles", "=", "[", "d", "[", "i", "]", "for", "d", "in", "data", "]", "outs", ",", "states", "=", "body", "(", "eles", ",", "states", ")", "outs", ",", "out_fmt", "=", "_flatten", "(", "outs", ",", "\"foreach output\"", ")", "outputs", ".", "append", "(", "outs", ")", "outputs", "=", "zip", "(", "*", "outputs", ")", "tmp_outputs", "=", "[", "]", "for", "out", "in", "outputs", ":", "tmp_outputs", ".", "append", "(", "ndarray", ".", "op", ".", "stack", "(", "*", "out", ")", ")", "outputs", "=", "tmp_outputs", "outputs", ",", "_", "=", "_regroup", "(", "outputs", ",", "out_fmt", ")", "return", "(", "outputs", ",", "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 two arguments as input and outputs a tuple of two elements, as illustrated below:: out, states = body(data1, states) data1 can be either an NDArray or a list of NDArrays. If data is an NDArray, data1 is an NDArray. Otherwise, data1 is a list of NDArrays and has the same size as data. states is a list of NDArrays and have the same size as init_states. Similarly, out can be either an NDArray or a list of NDArrays, which are concatenated as the first output of foreach; states from the last execution of body are the second output of foreach. The computation done by this operator is equivalent to the pseudo code below when the input data is NDArray:: states = init_states outs = [] for i in data.shape[0]: s = data[i] out, states = body(s, states) outs.append(out) outs = stack(*outs) Parameters ---------- body : a Python function. Define computation in an iteration. data: an NDArray or a list of NDArrays. The input data. init_states: an NDArray or nested lists of NDArrays. The initial values of the loop states. name: string. The name of the operator. Returns ------- outputs: an NDArray or nested lists of NDArrays. The output data concatenated from the output of all iterations. states: an NDArray or nested lists of NDArrays. The loop states in the last iteration. Examples -------- >>> step = lambda data, states: (data + states[0], [states[0] * 2]) >>> data = mx.nd.random.uniform(shape=(2, 10)) >>> states = [mx.nd.random.uniform(shape=(10))] >>> outs, states = mx.nd.contrib.foreach(step, data, states)
[ "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 the array element is finite i.e. not equal to positive or negative infinity and 0 in places where it is positive or negative infinity. Examples -------- >>> data = mx.nd.array([np.inf, -np.inf, np.NINF, -1]) >>> output = mx.nd.contrib.isfinite(data) >>> output [0. 0. 0. 1.] <NDArray 4 @cpu(0)> """ 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_nan)
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 the array element is finite i.e. not equal to positive or negative infinity and 0 in places where it is positive or negative infinity. Examples -------- >>> data = mx.nd.array([np.inf, -np.inf, np.NINF, -1]) >>> output = mx.nd.contrib.isfinite(data) >>> output [0. 0. 0. 1.] <NDArray 4 @cpu(0)> """ 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_nan)
[ "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_nan", ")" ]
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 finite i.e. not equal to positive or negative infinity and 0 in places where it is positive or negative infinity. Examples -------- >>> data = mx.nd.array([np.inf, -np.inf, np.NINF, -1]) >>> output = mx.nd.contrib.isfinite(data) >>> output [0. 0. 0. 1.] <NDArray 4 @cpu(0)>
[ "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", "(", ")", "-", "(", "2.0", "*", "nd", ".", "dot", "(", "x", ",", "x", ".", "transpose", "(", ")", ")", ")", "return", "nd", ".", "sqrt", "(", "distance_square", ")" ]
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 in range(emb.shape[0]): d_mat[i, i] = 1e10 nns = argpartition(d_mat[i], k)[:k] if any(labels[i] == labels[nn] for nn in nns): correct += 1 cnt += 1 accs.append(correct/cnt) return names, accs
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 in range(emb.shape[0]): d_mat[i, i] = 1e10 nns = argpartition(d_mat[i], k)[:k] if any(labels[i] == labels[nn] for nn in nns): correct += 1 cnt += 1 accs.append(correct/cnt) return names, accs
[ "def", "evaluate_emb", "(", "emb", ",", "labels", ")", ":", "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", "in", "range", "(", "emb", ".", "shape", "[", "0", "]", ")", ":", "d_mat", "[", "i", ",", "i", "]", "=", "1e10", "nns", "=", "argpartition", "(", "d_mat", "[", "i", "]", ",", "k", ")", "[", ":", "k", "]", "if", "any", "(", "labels", "[", "i", "]", "==", "labels", "[", "nn", "]", "for", "nn", "in", "nns", ")", ":", "correct", "+=", "1", "cnt", "+=", "1", "accs", ".", "append", "(", "correct", "/", "cnt", ")", "return", "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=num_label, input_length=seq_len)
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=num_label, input_length=seq_len)
[ "def", "_add_warp_ctc_loss", "(", "pred", ",", "seq_len", ",", "num_label", ",", "label", ")", ":", "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", "=", "num_label", ",", "input_length", "=", "seq_len", ")" ]
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_class = mx.symbol.SoftmaxActivation(data=pred) softmax_loss = mx.sym.MakeLoss(softmax_class) softmax_loss = mx.sym.BlockGrad(softmax_loss) return mx.sym.Group([softmax_loss, ctc_loss])
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_class = mx.symbol.SoftmaxActivation(data=pred) softmax_loss = mx.sym.MakeLoss(softmax_class) softmax_loss = mx.sym.BlockGrad(softmax_loss) return mx.sym.Group([softmax_loss, ctc_loss])
[ "def", "_add_mxnet_ctc_loss", "(", "pred", ",", "seq_len", ",", "label", ")", ":", "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_class", "=", "mx", ".", "symbol", ".", "SoftmaxActivation", "(", "data", "=", "pred", ")", "softmax_loss", "=", "mx", ".", "sym", ".", "MakeLoss", "(", "softmax_class", ")", "softmax_loss", "=", "mx", ".", "sym", ".", "BlockGrad", "(", "softmax_loss", ")", "return", "mx", ".", "sym", ".", "Group", "(", "[", "softmax_loss", ",", "ctc_loss", "]", ")" ]
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: print("Using MXNet CTC Loss") assert loss_type == 'ctc' sm = _add_mxnet_ctc_loss(pred, seq_len, label) return sm
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: print("Using MXNet CTC Loss") assert loss_type == 'ctc' sm = _add_mxnet_ctc_loss(pred, seq_len, label) return sm
[ "def", "_add_ctc_loss", "(", "pred", ",", "seq_len", ",", "num_label", ",", "loss_type", ")", ":", "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", ":", "print", "(", "\"Using MXNet CTC Loss\"", ")", "assert", "loss_type", "==", "'ctc'", "sm", "=", "_add_mxnet_ctc_loss", "(", "pred", ",", "seq_len", ",", "label", ")", "return", "sm" ]
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 seq_len: int num_hidden: int num_label: int loss_type: str 'ctc' or 'warpctc' Returns ------- mxnet.symbol.symbol.Symbol """ # Create the base (shared between training and inference) and add loss to the end pred = _lstm_unroll_base(num_lstm_layer, seq_len, num_hidden) if loss_type: # Training mode, add loss return _add_ctc_loss(pred, seq_len, num_label, loss_type) else: # Inference mode, add softmax return mx.sym.softmax(data=pred, name='softmax')
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 seq_len: int num_hidden: int num_label: int loss_type: str 'ctc' or 'warpctc' Returns ------- mxnet.symbol.symbol.Symbol """ # Create the base (shared between training and inference) and add loss to the end pred = _lstm_unroll_base(num_lstm_layer, seq_len, num_hidden) if loss_type: # Training mode, add loss return _add_ctc_loss(pred, seq_len, num_label, loss_type) else: # Inference mode, add softmax return mx.sym.softmax(data=pred, name='softmax')
[ "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_layer", ",", "seq_len", ",", "num_hidden", ")", "if", "loss_type", ":", "# Training mode, add loss", "return", "_add_ctc_loss", "(", "pred", ",", "seq_len", ",", "num_label", ",", "loss_type", ")", "else", ":", "# Inference mode, add softmax", "return", "mx", ".", "sym", ".", "softmax", "(", "data", "=", "pred", ",", "name", "=", "'softmax'", ")" ]
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 'warpctc' Returns ------- mxnet.symbol.symbol.Symbol
[ "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 of int and int """ init_c = [('l%d_init_c' % l, (batch_size, num_hidden)) for l in range(num_lstm_layer)] init_h = [('l%d_init_h' % l, (batch_size, num_hidden)) for l in range(num_lstm_layer)] return init_c + init_h
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 of int and int """ init_c = [('l%d_init_c' % l, (batch_size, num_hidden)) for l in range(num_lstm_layer)] init_h = [('l%d_init_h' % l, (batch_size, num_hidden)) for l in range(num_lstm_layer)] return init_c + init_h
[ "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", ")", "]", "init_h", "=", "[", "(", "'l%d_init_h'", "%", "l", ",", "(", "batch_size", ",", "num_hidden", ")", ")", "for", "l", "in", "range", "(", "num_lstm_layer", ")", "]", "return", "init_c", "+", "init_h" ]
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(out) output_vars = ctypes.cast(output_vars, ctypes.POINTER(NDArrayHandle)) else: original_output = None output_vars = ctypes.POINTER(NDArrayHandle)() num_output = ctypes.c_int(0) # return output stypes to avoid the c_api call for checking # a handle's stype in _ndarray_cls out_stypes = ctypes.POINTER(ctypes.c_int)() check_call(_LIB.MXImperativeInvokeEx( ctypes.c_void_p(handle), ctypes.c_int(len(ndargs)), c_handle_array(ndargs), ctypes.byref(num_output), ctypes.byref(output_vars), ctypes.c_int(len(keys)), c_str_array(keys), c_str_array([str(s) for s in vals]), ctypes.byref(out_stypes))) if original_output is not None: return original_output if num_output.value == 1: return _ndarray_cls(ctypes.cast(output_vars[0], NDArrayHandle), stype=out_stypes[0]) else: return [_ndarray_cls(ctypes.cast(output_vars[i], NDArrayHandle), stype=out_stypes[i]) for i in range(num_output.value)]
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(out) output_vars = ctypes.cast(output_vars, ctypes.POINTER(NDArrayHandle)) else: original_output = None output_vars = ctypes.POINTER(NDArrayHandle)() num_output = ctypes.c_int(0) # return output stypes to avoid the c_api call for checking # a handle's stype in _ndarray_cls out_stypes = ctypes.POINTER(ctypes.c_int)() check_call(_LIB.MXImperativeInvokeEx( ctypes.c_void_p(handle), ctypes.c_int(len(ndargs)), c_handle_array(ndargs), ctypes.byref(num_output), ctypes.byref(output_vars), ctypes.c_int(len(keys)), c_str_array(keys), c_str_array([str(s) for s in vals]), ctypes.byref(out_stypes))) if original_output is not None: return original_output if num_output.value == 1: return _ndarray_cls(ctypes.cast(output_vars[0], NDArrayHandle), stype=out_stypes[0]) else: return [_ndarray_cls(ctypes.cast(output_vars[i], NDArrayHandle), stype=out_stypes[i]) for i in range(num_output.value)]
[ "def", "_imperative_invoke", "(", "handle", ",", "ndargs", ",", "keys", ",", "vals", ",", "out", ")", ":", "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", "(", "out", ")", "output_vars", "=", "ctypes", ".", "cast", "(", "output_vars", ",", "ctypes", ".", "POINTER", "(", "NDArrayHandle", ")", ")", "else", ":", "original_output", "=", "None", "output_vars", "=", "ctypes", ".", "POINTER", "(", "NDArrayHandle", ")", "(", ")", "num_output", "=", "ctypes", ".", "c_int", "(", "0", ")", "# return output stypes to avoid the c_api call for checking", "# a handle's stype in _ndarray_cls", "out_stypes", "=", "ctypes", ".", "POINTER", "(", "ctypes", ".", "c_int", ")", "(", ")", "check_call", "(", "_LIB", ".", "MXImperativeInvokeEx", "(", "ctypes", ".", "c_void_p", "(", "handle", ")", ",", "ctypes", ".", "c_int", "(", "len", "(", "ndargs", ")", ")", ",", "c_handle_array", "(", "ndargs", ")", ",", "ctypes", ".", "byref", "(", "num_output", ")", ",", "ctypes", ".", "byref", "(", "output_vars", ")", ",", "ctypes", ".", "c_int", "(", "len", "(", "keys", ")", ")", ",", "c_str_array", "(", "keys", ")", ",", "c_str_array", "(", "[", "str", "(", "s", ")", "for", "s", "in", "vals", "]", ")", ",", "ctypes", ".", "byref", "(", "out_stypes", ")", ")", ")", "if", "original_output", "is", "not", "None", ":", "return", "original_output", "if", "num_output", ".", "value", "==", "1", ":", "return", "_ndarray_cls", "(", "ctypes", ".", "cast", "(", "output_vars", "[", "0", "]", ",", "NDArrayHandle", ")", ",", "stype", "=", "out_stypes", "[", "0", "]", ")", "else", ":", "return", "[", "_ndarray_cls", "(", "ctypes", ".", "cast", "(", "output_vars", "[", "i", "]", ",", "NDArrayHandle", ")", ",", "stype", "=", "out_stypes", "[", "i", "]", ")", "for", "i", "in", "range", "(", "num_output", ".", "value", ")", "]" ]
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 NDArrays" if out_grads is None: check_call(_LIB.MXAutogradBackward( len(outputs), c_handle_array(outputs), ctypes.c_void_p(0), ctypes.c_int(retain_graph))) return ograd_handles = [] for arr in out_grads: if arr is not None: ograd_handles.append(arr.handle) else: ograd_handles.append(NDArrayHandle(0)) assert len(ograd_handles) == len(outputs), \ "outputs and out_grads must have the same length" check_call(_LIB.MXAutogradBackward( len(outputs), c_handle_array(outputs), c_array(NDArrayHandle, ograd_handles), ctypes.c_int(retain_graph)))
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 NDArrays" if out_grads is None: check_call(_LIB.MXAutogradBackward( len(outputs), c_handle_array(outputs), ctypes.c_void_p(0), ctypes.c_int(retain_graph))) return ograd_handles = [] for arr in out_grads: if arr is not None: ograd_handles.append(arr.handle) else: ograd_handles.append(NDArrayHandle(0)) assert len(ograd_handles) == len(outputs), \ "outputs and out_grads must have the same length" check_call(_LIB.MXAutogradBackward( len(outputs), c_handle_array(outputs), c_array(NDArrayHandle, ograd_handles), ctypes.c_int(retain_graph)))
[ "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_grads", "is", "None", ":", "check_call", "(", "_LIB", ".", "MXAutogradBackward", "(", "len", "(", "outputs", ")", ",", "c_handle_array", "(", "outputs", ")", ",", "ctypes", ".", "c_void_p", "(", "0", ")", ",", "ctypes", ".", "c_int", "(", "retain_graph", ")", ")", ")", "return", "ograd_handles", "=", "[", "]", "for", "arr", "in", "out_grads", ":", "if", "arr", "is", "not", "None", ":", "ograd_handles", ".", "append", "(", "arr", ".", "handle", ")", "else", ":", "ograd_handles", ".", "append", "(", "NDArrayHandle", "(", "0", ")", ")", "assert", "len", "(", "ograd_handles", ")", "==", "len", "(", "outputs", ")", ",", "\"outputs and out_grads must have the same length\"", "check_call", "(", "_LIB", ".", "MXAutogradBackward", "(", "len", "(", "outputs", ")", ",", "c_handle_array", "(", "outputs", ")", ",", "c_array", "(", "NDArrayHandle", ",", "ograd_handles", ")", ",", "ctypes", ".", "c_int", "(", "retain_graph", ")", ")", ")" ]
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 ------- grad_and_loss_func: a python function A function that would compute both the gradient of arguments and loss value. """ @functools.wraps(func) def wrapped(*args): """Wrapped function.""" variables = args if argnum is not None: argnum_ = argnum if isinstance(argnum, list) else [argnum] variables = [args[i] for i in argnum_] for x in variables: assert isinstance(x, NDArray), "type of autograd input should NDArray." grads = [zeros_like(x) for x in variables] mark_variables(variables, grads) with train_section(): outputs = func(*args) compute_gradient([outputs] if isinstance(outputs, NDArray) else outputs) return grads, outputs return wrapped
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 ------- grad_and_loss_func: a python function A function that would compute both the gradient of arguments and loss value. """ @functools.wraps(func) def wrapped(*args): """Wrapped function.""" variables = args if argnum is not None: argnum_ = argnum if isinstance(argnum, list) else [argnum] variables = [args[i] for i in argnum_] for x in variables: assert isinstance(x, NDArray), "type of autograd input should NDArray." grads = [zeros_like(x) for x in variables] mark_variables(variables, grads) with train_section(): outputs = func(*args) compute_gradient([outputs] if isinstance(outputs, NDArray) else outputs) return grads, outputs return wrapped
[ "def", "grad_and_loss", "(", "func", ",", "argnum", "=", "None", ")", ":", "@", "functools", ".", "wraps", "(", "func", ")", "def", "wrapped", "(", "*", "args", ")", ":", "\"\"\"Wrapped function.\"\"\"", "variables", "=", "args", "if", "argnum", "is", "not", "None", ":", "argnum_", "=", "argnum", "if", "isinstance", "(", "argnum", ",", "list", ")", "else", "[", "argnum", "]", "variables", "=", "[", "args", "[", "i", "]", "for", "i", "in", "argnum_", "]", "for", "x", "in", "variables", ":", "assert", "isinstance", "(", "x", ",", "NDArray", ")", ",", "\"type of autograd input should NDArray.\"", "grads", "=", "[", "zeros_like", "(", "x", ")", "for", "x", "in", "variables", "]", "mark_variables", "(", "variables", ",", "grads", ")", "with", "train_section", "(", ")", ":", "outputs", "=", "func", "(", "*", "args", ")", "compute_gradient", "(", "[", "outputs", "]", "if", "isinstance", "(", "outputs", ",", "NDArray", ")", "else", "outputs", ")", "return", "grads", ",", "outputs", "return", "wrapped" ]
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 function A function that would compute both the gradient of arguments and loss value.
[ "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 function A function that would compute the gradient of arguments. Examples -------- >>> # autograd supports dynamic graph which is changed >>> # every instance >>> def func(x): >>> r = random.randint(0, 1) >>> if r % 2: >>> return x**2 >>> else: >>> return x/3 >>> # use `grad(func)` to get the gradient function >>> for x in range(10): >>> grad_func = grad(func) >>> inputs = nd.array([[1, 2, 3], [4, 5, 6]]) >>> grad_vals = grad_func(inputs) """ grad_with_loss_func = grad_and_loss(func, argnum) @functools.wraps(grad_with_loss_func) def wrapped(*args): return grad_with_loss_func(*args)[0] return wrapped
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 python function A function that would compute the gradient of arguments. Examples -------- >>> # autograd supports dynamic graph which is changed >>> # every instance >>> def func(x): >>> r = random.randint(0, 1) >>> if r % 2: >>> return x**2 >>> else: >>> return x/3 >>> # use `grad(func)` to get the gradient function >>> for x in range(10): >>> grad_func = grad(func) >>> inputs = nd.array([[1, 2, 3], [4, 5, 6]]) >>> grad_vals = grad_func(inputs) """ grad_with_loss_func = grad_and_loss(func, argnum) @functools.wraps(grad_with_loss_func) def wrapped(*args): return grad_with_loss_func(*args)[0] return wrapped
[ "def", "grad", "(", "func", ",", "argnum", "=", "None", ")", ":", "grad_with_loss_func", "=", "grad_and_loss", "(", "func", ",", "argnum", ")", "@", "functools", ".", "wraps", "(", "grad_with_loss_func", ")", "def", "wrapped", "(", "*", "args", ")", ":", "return", "grad_with_loss_func", "(", "*", "args", ")", "[", "0", "]", "return", "wrapped" ]
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 that would compute the gradient of arguments. Examples -------- >>> # autograd supports dynamic graph which is changed >>> # every instance >>> def func(x): >>> r = random.randint(0, 1) >>> if r % 2: >>> return x**2 >>> else: >>> return x/3 >>> # use `grad(func)` to get the gradient function >>> for x in range(10): >>> grad_func = grad(func) >>> inputs = nd.array([[1, 2, 3], [4, 5, 6]]) >>> grad_vals = grad_func(inputs)
[ "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 (not nan or inf). This requires a blocking .asscalar() call. Returns ------- NDArray or float Total norm. Return type is NDArray of shape (1,) if check_isfinite is False. Otherwise a float is returned. """ def _norm(array): if array.stype == 'default': x = array.reshape((-1,)) return ndarray.dot(x, x) return array.norm().square() assert len(arrays) > 0 ctx = arrays[0].context total_norm = ndarray.add_n(*[_norm(arr).as_in_context(ctx) for arr in arrays]) total_norm = ndarray.sqrt(total_norm) if check_isfinite: if not np.isfinite(total_norm.asscalar()): warnings.warn( UserWarning('nan or inf is detected. ' 'Clipping results will be undefined.'), stacklevel=2) scale = max_norm / (total_norm + 1e-8) scale = ndarray.min(ndarray.concat(scale, ndarray.ones(1, ctx=ctx), dim=0)) for arr in arrays: arr *= scale.as_in_context(arr.context) if check_isfinite: return total_norm.asscalar() else: return total_norm
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 (not nan or inf). This requires a blocking .asscalar() call. Returns ------- NDArray or float Total norm. Return type is NDArray of shape (1,) if check_isfinite is False. Otherwise a float is returned. """ def _norm(array): if array.stype == 'default': x = array.reshape((-1,)) return ndarray.dot(x, x) return array.norm().square() assert len(arrays) > 0 ctx = arrays[0].context total_norm = ndarray.add_n(*[_norm(arr).as_in_context(ctx) for arr in arrays]) total_norm = ndarray.sqrt(total_norm) if check_isfinite: if not np.isfinite(total_norm.asscalar()): warnings.warn( UserWarning('nan or inf is detected. ' 'Clipping results will be undefined.'), stacklevel=2) scale = max_norm / (total_norm + 1e-8) scale = ndarray.min(ndarray.concat(scale, ndarray.ones(1, ctx=ctx), dim=0)) for arr in arrays: arr *= scale.as_in_context(arr.context) if check_isfinite: return total_norm.asscalar() else: return total_norm
[ "def", "clip_global_norm", "(", "arrays", ",", "max_norm", ",", "check_isfinite", "=", "True", ")", ":", "def", "_norm", "(", "array", ")", ":", "if", "array", ".", "stype", "==", "'default'", ":", "x", "=", "array", ".", "reshape", "(", "(", "-", "1", ",", ")", ")", "return", "ndarray", ".", "dot", "(", "x", ",", "x", ")", "return", "array", ".", "norm", "(", ")", ".", "square", "(", ")", "assert", "len", "(", "arrays", ")", ">", "0", "ctx", "=", "arrays", "[", "0", "]", ".", "context", "total_norm", "=", "ndarray", ".", "add_n", "(", "*", "[", "_norm", "(", "arr", ")", ".", "as_in_context", "(", "ctx", ")", "for", "arr", "in", "arrays", "]", ")", "total_norm", "=", "ndarray", ".", "sqrt", "(", "total_norm", ")", "if", "check_isfinite", ":", "if", "not", "np", ".", "isfinite", "(", "total_norm", ".", "asscalar", "(", ")", ")", ":", "warnings", ".", "warn", "(", "UserWarning", "(", "'nan or inf is detected. '", "'Clipping results will be undefined.'", ")", ",", "stacklevel", "=", "2", ")", "scale", "=", "max_norm", "/", "(", "total_norm", "+", "1e-8", ")", "scale", "=", "ndarray", ".", "min", "(", "ndarray", ".", "concat", "(", "scale", ",", "ndarray", ".", "ones", "(", "1", ",", "ctx", "=", "ctx", ")", ",", "dim", "=", "0", ")", ")", "for", "arr", "in", "arrays", ":", "arr", "*=", "scale", ".", "as_in_context", "(", "arr", ".", "context", ")", "if", "check_isfinite", ":", "return", "total_norm", ".", "asscalar", "(", ")", "else", ":", "return", "total_norm" ]
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() call. Returns ------- NDArray or float Total norm. Return type is NDArray of shape (1,) if check_isfinite is False. Otherwise a float is returned.
[ "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 file content matches the expected hash. """ sha1 = hashlib.sha1() with open(filename, 'rb') as f: while True: data = f.read(1048576) if not data: break sha1.update(data) return sha1.hexdigest() == sha1_hash
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 file content matches the expected hash. """ sha1 = hashlib.sha1() with open(filename, 'rb') as f: while True: data = f.read(1048576) if not data: break sha1.update(data) return sha1.hexdigest() == sha1_hash
[ "def", "check_sha1", "(", "filename", ",", "sha1_hash", ")", ":", "sha1", "=", "hashlib", ".", "sha1", "(", ")", "with", "open", "(", "filename", ",", "'rb'", ")", "as", "f", ":", "while", "True", ":", "data", "=", "f", ".", "read", "(", "1048576", ")", "if", "not", "data", ":", "break", "sha1", ".", "update", "(", "data", ")", "return", "sha1", ".", "hexdigest", "(", ")", "==", "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 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 same name as in url. overwrite : bool, optional Whether to overwrite destination file if already exists. sha1_hash : str, optional Expected sha1 hash in hexadecimal digits. Will ignore existing file when hash is specified but doesn't match. retries : integer, default 5 The number of times to attempt the download in case of failure or non 200 return codes verify_ssl : bool, default True Verify SSL certificates. Returns ------- str The file path of the downloaded file. """ if path is None: fname = url.split('/')[-1] # Empty filenames are invalid assert fname, 'Can\'t construct file-name from this URL. ' \ 'Please set the `path` option manually.' else: path = os.path.expanduser(path) if os.path.isdir(path): fname = os.path.join(path, url.split('/')[-1]) else: fname = path assert retries >= 0, "Number of retries should be at least 0, currently it's {}".format( retries) if not verify_ssl: warnings.warn( 'Unverified HTTPS request is being made (verify_ssl=False). ' 'Adding certificate verification is strongly advised.') if overwrite or not os.path.exists(fname) or (sha1_hash and not check_sha1(fname, sha1_hash)): dirname = os.path.dirname(os.path.abspath(os.path.expanduser(fname))) if not os.path.exists(dirname): os.makedirs(dirname) while retries + 1 > 0: # Disable pyling too broad Exception # pylint: disable=W0703 try: print('Downloading {} from {}...'.format(fname, url)) r = requests.get(url, stream=True, verify=verify_ssl) if r.status_code != 200: raise RuntimeError('Failed downloading url {}'.format(url)) # create uuid for temporary files random_uuid = str(uuid.uuid4()) with open('{}.{}'.format(fname, random_uuid), 'wb') as f: for chunk in r.iter_content(chunk_size=1024): if chunk: # filter out keep-alive new chunks f.write(chunk) # if the target file exists(created by other processes) # and have the same hash with target file # delete the temporary file if not os.path.exists(fname) or (sha1_hash and not check_sha1(fname, sha1_hash)): # atmoic operation in the same file system _replace_atomic('{}.{}'.format(fname, random_uuid), fname) else: try: os.remove('{}.{}'.format(fname, random_uuid)) except OSError: pass finally: warnings.warn( 'File {} exists in file system so the downloaded file is deleted'.format(fname)) if sha1_hash and not check_sha1(fname, sha1_hash): raise UserWarning( 'File {} is downloaded but the content hash does not match.' ' The repo may be outdated or download may be incomplete. ' 'If the "repo_url" is overridden, consider switching to ' 'the default repo.'.format(fname)) break except Exception as e: retries -= 1 if retries <= 0: raise e else: print('download failed due to {}, retrying, {} attempt{} left' .format(repr(e), retries, 's' if retries > 1 else '')) return fname
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 same name as in url. overwrite : bool, optional Whether to overwrite destination file if already exists. sha1_hash : str, optional Expected sha1 hash in hexadecimal digits. Will ignore existing file when hash is specified but doesn't match. retries : integer, default 5 The number of times to attempt the download in case of failure or non 200 return codes verify_ssl : bool, default True Verify SSL certificates. Returns ------- str The file path of the downloaded file. """ if path is None: fname = url.split('/')[-1] # Empty filenames are invalid assert fname, 'Can\'t construct file-name from this URL. ' \ 'Please set the `path` option manually.' else: path = os.path.expanduser(path) if os.path.isdir(path): fname = os.path.join(path, url.split('/')[-1]) else: fname = path assert retries >= 0, "Number of retries should be at least 0, currently it's {}".format( retries) if not verify_ssl: warnings.warn( 'Unverified HTTPS request is being made (verify_ssl=False). ' 'Adding certificate verification is strongly advised.') if overwrite or not os.path.exists(fname) or (sha1_hash and not check_sha1(fname, sha1_hash)): dirname = os.path.dirname(os.path.abspath(os.path.expanduser(fname))) if not os.path.exists(dirname): os.makedirs(dirname) while retries + 1 > 0: # Disable pyling too broad Exception # pylint: disable=W0703 try: print('Downloading {} from {}...'.format(fname, url)) r = requests.get(url, stream=True, verify=verify_ssl) if r.status_code != 200: raise RuntimeError('Failed downloading url {}'.format(url)) # create uuid for temporary files random_uuid = str(uuid.uuid4()) with open('{}.{}'.format(fname, random_uuid), 'wb') as f: for chunk in r.iter_content(chunk_size=1024): if chunk: # filter out keep-alive new chunks f.write(chunk) # if the target file exists(created by other processes) # and have the same hash with target file # delete the temporary file if not os.path.exists(fname) or (sha1_hash and not check_sha1(fname, sha1_hash)): # atmoic operation in the same file system _replace_atomic('{}.{}'.format(fname, random_uuid), fname) else: try: os.remove('{}.{}'.format(fname, random_uuid)) except OSError: pass finally: warnings.warn( 'File {} exists in file system so the downloaded file is deleted'.format(fname)) if sha1_hash and not check_sha1(fname, sha1_hash): raise UserWarning( 'File {} is downloaded but the content hash does not match.' ' The repo may be outdated or download may be incomplete. ' 'If the "repo_url" is overridden, consider switching to ' 'the default repo.'.format(fname)) break except Exception as e: retries -= 1 if retries <= 0: raise e else: print('download failed due to {}, retrying, {} attempt{} left' .format(repr(e), retries, 's' if retries > 1 else '')) return fname
[ "def", "download", "(", "url", ",", "path", "=", "None", ",", "overwrite", "=", "False", ",", "sha1_hash", "=", "None", ",", "retries", "=", "5", ",", "verify_ssl", "=", "True", ")", ":", "if", "path", "is", "None", ":", "fname", "=", "url", ".", "split", "(", "'/'", ")", "[", "-", "1", "]", "# Empty filenames are invalid", "assert", "fname", ",", "'Can\\'t construct file-name from this URL. '", "'Please set the `path` option manually.'", "else", ":", "path", "=", "os", ".", "path", ".", "expanduser", "(", "path", ")", "if", "os", ".", "path", ".", "isdir", "(", "path", ")", ":", "fname", "=", "os", ".", "path", ".", "join", "(", "path", ",", "url", ".", "split", "(", "'/'", ")", "[", "-", "1", "]", ")", "else", ":", "fname", "=", "path", "assert", "retries", ">=", "0", ",", "\"Number of retries should be at least 0, currently it's {}\"", ".", "format", "(", "retries", ")", "if", "not", "verify_ssl", ":", "warnings", ".", "warn", "(", "'Unverified HTTPS request is being made (verify_ssl=False). '", "'Adding certificate verification is strongly advised.'", ")", "if", "overwrite", "or", "not", "os", ".", "path", ".", "exists", "(", "fname", ")", "or", "(", "sha1_hash", "and", "not", "check_sha1", "(", "fname", ",", "sha1_hash", ")", ")", ":", "dirname", "=", "os", ".", "path", ".", "dirname", "(", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "expanduser", "(", "fname", ")", ")", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "dirname", ")", ":", "os", ".", "makedirs", "(", "dirname", ")", "while", "retries", "+", "1", ">", "0", ":", "# Disable pyling too broad Exception", "# pylint: disable=W0703", "try", ":", "print", "(", "'Downloading {} from {}...'", ".", "format", "(", "fname", ",", "url", ")", ")", "r", "=", "requests", ".", "get", "(", "url", ",", "stream", "=", "True", ",", "verify", "=", "verify_ssl", ")", "if", "r", ".", "status_code", "!=", "200", ":", "raise", "RuntimeError", "(", "'Failed downloading url {}'", ".", "format", "(", "url", ")", ")", "# create uuid for temporary files", "random_uuid", "=", "str", "(", "uuid", ".", "uuid4", "(", ")", ")", "with", "open", "(", "'{}.{}'", ".", "format", "(", "fname", ",", "random_uuid", ")", ",", "'wb'", ")", "as", "f", ":", "for", "chunk", "in", "r", ".", "iter_content", "(", "chunk_size", "=", "1024", ")", ":", "if", "chunk", ":", "# filter out keep-alive new chunks", "f", ".", "write", "(", "chunk", ")", "# if the target file exists(created by other processes)", "# and have the same hash with target file", "# delete the temporary file", "if", "not", "os", ".", "path", ".", "exists", "(", "fname", ")", "or", "(", "sha1_hash", "and", "not", "check_sha1", "(", "fname", ",", "sha1_hash", ")", ")", ":", "# atmoic operation in the same file system", "_replace_atomic", "(", "'{}.{}'", ".", "format", "(", "fname", ",", "random_uuid", ")", ",", "fname", ")", "else", ":", "try", ":", "os", ".", "remove", "(", "'{}.{}'", ".", "format", "(", "fname", ",", "random_uuid", ")", ")", "except", "OSError", ":", "pass", "finally", ":", "warnings", ".", "warn", "(", "'File {} exists in file system so the downloaded file is deleted'", ".", "format", "(", "fname", ")", ")", "if", "sha1_hash", "and", "not", "check_sha1", "(", "fname", ",", "sha1_hash", ")", ":", "raise", "UserWarning", "(", "'File {} is downloaded but the content hash does not match.'", "' The repo may be outdated or download may be incomplete. '", "'If the \"repo_url\" is overridden, consider switching to '", "'the default repo.'", ".", "format", "(", "fname", ")", ")", "break", "except", "Exception", "as", "e", ":", "retries", "-=", "1", "if", "retries", "<=", "0", ":", "raise", "e", "else", ":", "print", "(", "'download failed due to {}, retrying, {} attempt{} left'", ".", "format", "(", "repr", "(", "e", ")", ",", "retries", ",", "'s'", "if", "retries", ">", "1", "else", "''", ")", ")", "return", "fname" ]
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 if already exists. sha1_hash : str, optional Expected sha1 hash in hexadecimal digits. Will ignore existing file when hash is specified but doesn't match. retries : integer, default 5 The number of times to attempt the download in case of failure or non 200 return codes verify_ssl : bool, default True Verify SSL certificates. Returns ------- str The file path of the downloaded 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", "]", "!=", "'/'", ":", "repo_url", "=", "repo_url", "+", "'/'", "return", "repo_url" ]
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(), namespace=namespace, filename=filename)
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(), namespace=namespace, filename=filename)
[ "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", "]", ",", "limit", ")", "+", "', ..., '", "+", "_brief_print_list", "(", "lst", "[", "-", "limit", "//", "2", ":", "]", ",", "limit", ")", "return", "', '", ".", "join", "(", "[", "\"'%s'\"", "%", "str", "(", "i", ")", "for", "i", "in", "lst", "]", ")" ]
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_function.__name__ = func_name symbol_function.__doc__ = doc_str symbol_function.__module__ = 'mxnet.symbol' return symbol_function
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_function.__name__ = func_name symbol_function.__doc__ = doc_str symbol_function.__module__ = 'mxnet.symbol' return symbol_function
[ "def", "_make_symbol_function", "(", "handle", ",", "name", ",", "func_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_function", ".", "__name__", "=", "func_name", "symbol_function", ".", "__doc__", "=", "doc_str", "symbol_function", ".", "__module__", "=", "'mxnet.symbol'", "return", "symbol_function" ]
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", ")", ",", "'item_weight'", ":", "item", ".", "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", ",", "MOVIELENS", "[", "'max_movie'", "]", ",", "dtype", "=", "'int64'", ")", "return", "{", "'user_weight'", ":", "all_users", ",", "'item_weight'", ":", "all_movies", "}" ]
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] * arg_shapes for dtype in type_list: ndarray_arg = [] numpy_arg = [] for s in arg_shapes: npy = np.random.uniform(rmin, 10, s).astype(dtype) narr = mx.nd.array(npy, dtype=dtype) ndarray_arg.append(narr) numpy_arg.append(npy) out1 = uf(*ndarray_arg) if npuf is None: out2 = uf(*numpy_arg).astype(dtype) else: out2 = npuf(*numpy_arg).astype(dtype) assert out1.shape == out2.shape if isinstance(out1, mx.nd.NDArray): out1 = out1.asnumpy() if dtype == np.float16: assert reldiff(out1, out2) < 2e-3 else: assert reldiff(out1, out2) < 1e-6
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] * arg_shapes for dtype in type_list: ndarray_arg = [] numpy_arg = [] for s in arg_shapes: npy = np.random.uniform(rmin, 10, s).astype(dtype) narr = mx.nd.array(npy, dtype=dtype) ndarray_arg.append(narr) numpy_arg.append(npy) out1 = uf(*ndarray_arg) if npuf is None: out2 = uf(*numpy_arg).astype(dtype) else: out2 = npuf(*numpy_arg).astype(dtype) assert out1.shape == out2.shape if isinstance(out1, mx.nd.NDArray): out1 = out1.asnumpy() if dtype == np.float16: assert reldiff(out1, out2) < 2e-3 else: assert reldiff(out1, out2) < 1e-6
[ "def", "check_with_uniform", "(", "uf", ",", "arg_shapes", ",", "dim", "=", "None", ",", "npuf", "=", "None", ",", "rmin", "=", "-", "10", ",", "type_list", "=", "[", "np", ".", "float32", "]", ")", ":", "if", "isinstance", "(", "arg_shapes", ",", "int", ")", ":", "assert", "dim", "shape", "=", "tuple", "(", "np", ".", "random", ".", "randint", "(", "1", ",", "int", "(", "1000", "**", "(", "1.0", "/", "dim", ")", ")", ",", "size", "=", "dim", ")", ")", "arg_shapes", "=", "[", "shape", "]", "*", "arg_shapes", "for", "dtype", "in", "type_list", ":", "ndarray_arg", "=", "[", "]", "numpy_arg", "=", "[", "]", "for", "s", "in", "arg_shapes", ":", "npy", "=", "np", ".", "random", ".", "uniform", "(", "rmin", ",", "10", ",", "s", ")", ".", "astype", "(", "dtype", ")", "narr", "=", "mx", ".", "nd", ".", "array", "(", "npy", ",", "dtype", "=", "dtype", ")", "ndarray_arg", ".", "append", "(", "narr", ")", "numpy_arg", ".", "append", "(", "npy", ")", "out1", "=", "uf", "(", "*", "ndarray_arg", ")", "if", "npuf", "is", "None", ":", "out2", "=", "uf", "(", "*", "numpy_arg", ")", ".", "astype", "(", "dtype", ")", "else", ":", "out2", "=", "npuf", "(", "*", "numpy_arg", ")", ".", "astype", "(", "dtype", ")", "assert", "out1", ".", "shape", "==", "out2", ".", "shape", "if", "isinstance", "(", "out1", ",", "mx", ".", "nd", ".", "NDArray", ")", ":", "out1", "=", "out1", ".", "asnumpy", "(", ")", "if", "dtype", "==", "np", ".", "float16", ":", "assert", "reldiff", "(", "out1", ",", "out2", ")", "<", "2e-3", "else", ":", "assert", "reldiff", "(", "out1", ",", "out2", ")", "<", "1e-6" ]
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'", "]", ")", "]", "num_after", "=", "len", "(", "self", ".", "_roidb", ")", "logger", ".", "info", "(", "'filter roidb: {} -> {}'", ".", "format", "(", "num_roidb", ",", "num_after", ")", ")" ]
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 = boxes[:, 0].copy() oldx2 = boxes[:, 2].copy() boxes[:, 0] = roi_rec['width'] - oldx2 - 1 boxes[:, 2] = roi_rec['width'] - oldx1 - 1 assert (boxes[:, 2] >= boxes[:, 0]).all() roi_rec_flipped = roi_rec.copy() roi_rec_flipped['boxes'] = boxes roi_rec_flipped['flipped'] = True roidb_flipped.append(roi_rec_flipped) self._roidb.extend(roidb_flipped)
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 = boxes[:, 0].copy() oldx2 = boxes[:, 2].copy() boxes[:, 0] = roi_rec['width'] - oldx2 - 1 boxes[:, 2] = roi_rec['width'] - oldx1 - 1 assert (boxes[:, 2] >= boxes[:, 0]).all() roi_rec_flipped = roi_rec.copy() roi_rec_flipped['boxes'] = boxes roi_rec_flipped['flipped'] = True roidb_flipped.append(roi_rec_flipped) self._roidb.extend(roidb_flipped)
[ "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_rec", "[", "'boxes'", "]", ".", "copy", "(", ")", "oldx1", "=", "boxes", "[", ":", ",", "0", "]", ".", "copy", "(", ")", "oldx2", "=", "boxes", "[", ":", ",", "2", "]", ".", "copy", "(", ")", "boxes", "[", ":", ",", "0", "]", "=", "roi_rec", "[", "'width'", "]", "-", "oldx2", "-", "1", "boxes", "[", ":", ",", "2", "]", "=", "roi_rec", "[", "'width'", "]", "-", "oldx1", "-", "1", "assert", "(", "boxes", "[", ":", ",", "2", "]", ">=", "boxes", "[", ":", ",", "0", "]", ")", ".", "all", "(", ")", "roi_rec_flipped", "=", "roi_rec", ".", "copy", "(", ")", "roi_rec_flipped", "[", "'boxes'", "]", "=", "boxes", "roi_rec_flipped", "[", "'flipped'", "]", "=", "True", "roidb_flipped", ".", "append", "(", "roi_rec_flipped", ")", "self", ".", "_roidb", ".", "extend", "(", "roidb_flipped", ")" ]
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 ---------- name : str Name of the model. root : str, default $MXNET_HOME/models Location for keeping the model parameters. Returns ------- file_path Path to the requested pretrained model file. """ file_name = '{name}-{short_hash}'.format(name=name, short_hash=short_hash(name)) root = os.path.expanduser(root) file_path = os.path.join(root, file_name+'.params') sha1_hash = _model_sha1[name] if os.path.exists(file_path): if check_sha1(file_path, sha1_hash): return file_path else: logging.warning('Mismatch in the content of model file detected. Downloading again.') else: logging.info('Model file not found. Downloading to %s.', file_path) util.makedirs(root) zip_file_path = os.path.join(root, file_name+'.zip') repo_url = os.environ.get('MXNET_GLUON_REPO', apache_repo_url) if repo_url[-1] != '/': repo_url = repo_url + '/' download(_url_format.format(repo_url=repo_url, file_name=file_name), path=zip_file_path, overwrite=True) with zipfile.ZipFile(zip_file_path) as zf: zf.extractall(root) os.remove(zip_file_path) if check_sha1(file_path, sha1_hash): return file_path else: raise ValueError('Downloaded file has different hash. Please try again.')
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 ---------- name : str Name of the model. root : str, default $MXNET_HOME/models Location for keeping the model parameters. Returns ------- file_path Path to the requested pretrained model file. """ file_name = '{name}-{short_hash}'.format(name=name, short_hash=short_hash(name)) root = os.path.expanduser(root) file_path = os.path.join(root, file_name+'.params') sha1_hash = _model_sha1[name] if os.path.exists(file_path): if check_sha1(file_path, sha1_hash): return file_path else: logging.warning('Mismatch in the content of model file detected. Downloading again.') else: logging.info('Model file not found. Downloading to %s.', file_path) util.makedirs(root) zip_file_path = os.path.join(root, file_name+'.zip') repo_url = os.environ.get('MXNET_GLUON_REPO', apache_repo_url) if repo_url[-1] != '/': repo_url = repo_url + '/' download(_url_format.format(repo_url=repo_url, file_name=file_name), path=zip_file_path, overwrite=True) with zipfile.ZipFile(zip_file_path) as zf: zf.extractall(root) os.remove(zip_file_path) if check_sha1(file_path, sha1_hash): return file_path else: raise ValueError('Downloaded file has different hash. Please try again.')
[ "def", "get_model_file", "(", "name", ",", "root", "=", "os", ".", "path", ".", "join", "(", "base", ".", "data_dir", "(", ")", ",", "'models'", ")", ")", ":", "file_name", "=", "'{name}-{short_hash}'", ".", "format", "(", "name", "=", "name", ",", "short_hash", "=", "short_hash", "(", "name", ")", ")", "root", "=", "os", ".", "path", ".", "expanduser", "(", "root", ")", "file_path", "=", "os", ".", "path", ".", "join", "(", "root", ",", "file_name", "+", "'.params'", ")", "sha1_hash", "=", "_model_sha1", "[", "name", "]", "if", "os", ".", "path", ".", "exists", "(", "file_path", ")", ":", "if", "check_sha1", "(", "file_path", ",", "sha1_hash", ")", ":", "return", "file_path", "else", ":", "logging", ".", "warning", "(", "'Mismatch in the content of model file detected. Downloading again.'", ")", "else", ":", "logging", ".", "info", "(", "'Model file not found. Downloading to %s.'", ",", "file_path", ")", "util", ".", "makedirs", "(", "root", ")", "zip_file_path", "=", "os", ".", "path", ".", "join", "(", "root", ",", "file_name", "+", "'.zip'", ")", "repo_url", "=", "os", ".", "environ", ".", "get", "(", "'MXNET_GLUON_REPO'", ",", "apache_repo_url", ")", "if", "repo_url", "[", "-", "1", "]", "!=", "'/'", ":", "repo_url", "=", "repo_url", "+", "'/'", "download", "(", "_url_format", ".", "format", "(", "repo_url", "=", "repo_url", ",", "file_name", "=", "file_name", ")", ",", "path", "=", "zip_file_path", ",", "overwrite", "=", "True", ")", "with", "zipfile", ".", "ZipFile", "(", "zip_file_path", ")", "as", "zf", ":", "zf", ".", "extractall", "(", "root", ")", "os", ".", "remove", "(", "zip_file_path", ")", "if", "check_sha1", "(", "file_path", ",", "sha1_hash", ")", ":", "return", "file_path", "else", ":", "raise", "ValueError", "(", "'Downloaded file has different hash. Please try again.'", ")" ]
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 $MXNET_HOME/models Location for keeping the model parameters. Returns ------- file_path Path to the requested pretrained model file.
[ "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) for f in files: if f.endswith(".params"): os.remove(os.path.join(root, f))
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) for f in files: if f.endswith(".params"): os.remove(os.path.join(root, f))
[ "def", "purge", "(", "root", "=", "os", ".", "path", ".", "join", "(", "base", ".", "data_dir", "(", ")", ",", "'models'", ")", ")", ":", "root", "=", "os", ".", "path", ".", "expanduser", "(", "root", ")", "files", "=", "os", ".", "listdir", "(", "root", ")", "for", "f", "in", "files", ":", "if", "f", ".", "endswith", "(", "\".params\"", ")", ":", "os", ".", "remove", "(", "os", ".", "path", ".", "join", "(", "root", ",", "f", ")", ")" ]
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 = [] labels = [] coco = COCO(anno_file) img_ids = coco.getImgIds() # deal with class names cats = [cat['name'] for cat in coco.loadCats(coco.getCatIds())] class_to_coco_ind = dict(zip(cats, coco.getCatIds())) class_to_ind = dict(zip(self.classes, range(len(self.classes)))) coco_ind_to_class_ind = dict([(class_to_coco_ind[cls], class_to_ind[cls]) for cls in self.classes[0:]]) for img_id in img_ids: # filename image_info = coco.loadImgs(img_id)[0] filename = image_info["file_name"] subdir = filename.split('_')[1] height = image_info["height"] width = image_info["width"] # label anno_ids = coco.getAnnIds(imgIds=img_id) annos = coco.loadAnns(anno_ids) label = [] for anno in annos: cat_id = coco_ind_to_class_ind[anno['category_id']] bbox = anno["bbox"] assert len(bbox) == 4 xmin = float(bbox[0]) / width ymin = float(bbox[1]) / height xmax = xmin + float(bbox[2]) / width ymax = ymin + float(bbox[3]) / height label.append([cat_id, xmin, ymin, xmax, ymax, 0]) if label: labels.append(np.array(label)) image_set_index.append(os.path.join(subdir, filename)) if shuffle: import random indices = list(range(len(image_set_index))) random.shuffle(indices) image_set_index = [image_set_index[i] for i in indices] labels = [labels[i] for i in indices] # store the results self.image_set_index = image_set_index self.labels = labels
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 = [] labels = [] coco = COCO(anno_file) img_ids = coco.getImgIds() # deal with class names cats = [cat['name'] for cat in coco.loadCats(coco.getCatIds())] class_to_coco_ind = dict(zip(cats, coco.getCatIds())) class_to_ind = dict(zip(self.classes, range(len(self.classes)))) coco_ind_to_class_ind = dict([(class_to_coco_ind[cls], class_to_ind[cls]) for cls in self.classes[0:]]) for img_id in img_ids: # filename image_info = coco.loadImgs(img_id)[0] filename = image_info["file_name"] subdir = filename.split('_')[1] height = image_info["height"] width = image_info["width"] # label anno_ids = coco.getAnnIds(imgIds=img_id) annos = coco.loadAnns(anno_ids) label = [] for anno in annos: cat_id = coco_ind_to_class_ind[anno['category_id']] bbox = anno["bbox"] assert len(bbox) == 4 xmin = float(bbox[0]) / width ymin = float(bbox[1]) / height xmax = xmin + float(bbox[2]) / width ymax = ymin + float(bbox[3]) / height label.append([cat_id, xmin, ymin, xmax, ymax, 0]) if label: labels.append(np.array(label)) image_set_index.append(os.path.join(subdir, filename)) if shuffle: import random indices = list(range(len(image_set_index))) random.shuffle(indices) image_set_index = [image_set_index[i] for i in indices] labels = [labels[i] for i in indices] # store the results self.image_set_index = image_set_index self.labels = labels
[ "def", "_load_all", "(", "self", ",", "anno_file", ",", "shuffle", ")", ":", "image_set_index", "=", "[", "]", "labels", "=", "[", "]", "coco", "=", "COCO", "(", "anno_file", ")", "img_ids", "=", "coco", ".", "getImgIds", "(", ")", "# deal with class names", "cats", "=", "[", "cat", "[", "'name'", "]", "for", "cat", "in", "coco", ".", "loadCats", "(", "coco", ".", "getCatIds", "(", ")", ")", "]", "class_to_coco_ind", "=", "dict", "(", "zip", "(", "cats", ",", "coco", ".", "getCatIds", "(", ")", ")", ")", "class_to_ind", "=", "dict", "(", "zip", "(", "self", ".", "classes", ",", "range", "(", "len", "(", "self", ".", "classes", ")", ")", ")", ")", "coco_ind_to_class_ind", "=", "dict", "(", "[", "(", "class_to_coco_ind", "[", "cls", "]", ",", "class_to_ind", "[", "cls", "]", ")", "for", "cls", "in", "self", ".", "classes", "[", "0", ":", "]", "]", ")", "for", "img_id", "in", "img_ids", ":", "# filename", "image_info", "=", "coco", ".", "loadImgs", "(", "img_id", ")", "[", "0", "]", "filename", "=", "image_info", "[", "\"file_name\"", "]", "subdir", "=", "filename", ".", "split", "(", "'_'", ")", "[", "1", "]", "height", "=", "image_info", "[", "\"height\"", "]", "width", "=", "image_info", "[", "\"width\"", "]", "# label", "anno_ids", "=", "coco", ".", "getAnnIds", "(", "imgIds", "=", "img_id", ")", "annos", "=", "coco", ".", "loadAnns", "(", "anno_ids", ")", "label", "=", "[", "]", "for", "anno", "in", "annos", ":", "cat_id", "=", "coco_ind_to_class_ind", "[", "anno", "[", "'category_id'", "]", "]", "bbox", "=", "anno", "[", "\"bbox\"", "]", "assert", "len", "(", "bbox", ")", "==", "4", "xmin", "=", "float", "(", "bbox", "[", "0", "]", ")", "/", "width", "ymin", "=", "float", "(", "bbox", "[", "1", "]", ")", "/", "height", "xmax", "=", "xmin", "+", "float", "(", "bbox", "[", "2", "]", ")", "/", "width", "ymax", "=", "ymin", "+", "float", "(", "bbox", "[", "3", "]", ")", "/", "height", "label", ".", "append", "(", "[", "cat_id", ",", "xmin", ",", "ymin", ",", "xmax", ",", "ymax", ",", "0", "]", ")", "if", "label", ":", "labels", ".", "append", "(", "np", ".", "array", "(", "label", ")", ")", "image_set_index", ".", "append", "(", "os", ".", "path", ".", "join", "(", "subdir", ",", "filename", ")", ")", "if", "shuffle", ":", "import", "random", "indices", "=", "list", "(", "range", "(", "len", "(", "image_set_index", ")", ")", ")", "random", ".", "shuffle", "(", "indices", ")", "image_set_index", "=", "[", "image_set_index", "[", "i", "]", "for", "i", "in", "indices", "]", "labels", "=", "[", "labels", "[", "i", "]", "for", "i", "in", "indices", "]", "# store the results", "self", ".", "image_set_index", "=", "image_set_index", "self", ".", "labels", "=", "labels" ]
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: if isinstance(self._next_states, (int, float)): self._module.set_states(value=self._next_states) else: self._module.set_states(states=self._next_states) self._module.forward(data_batch, is_train=is_train) outputs = self._module.get_outputs(merge_multi_context=False) self._next_states = outputs[:-1]
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: if isinstance(self._next_states, (int, float)): self._module.set_states(value=self._next_states) else: self._module.set_states(states=self._next_states) self._module.forward(data_batch, is_train=is_train) outputs = self._module.get_outputs(merge_multi_context=False) self._next_states = outputs[:-1]
[ "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", ",", "(", "int", ",", "float", ")", ")", ":", "self", ".", "_module", ".", "set_states", "(", "value", "=", "self", ".", "_next_states", ")", "else", ":", "self", ".", "_module", ".", "set_states", "(", "states", "=", "self", ".", "_next_states", ")", "self", ".", "_module", ".", "forward", "(", "data_batch", ",", "is_train", "=", "is_train", ")", "outputs", "=", "self", ".", "_module", ".", "get_outputs", "(", "merge_multi_context", "=", "False", ")", "self", ".", "_next_states", "=", "outputs", "[", ":", "-", "1", "]" ]
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 If set, clip values of all gradients the ratio of the sum of their norms. """ if max_norm is not None: self._clip_by_global_norm(max_norm) self._module.update()
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 If set, clip values of all gradients the ratio of the sum of their norms. """ if max_norm is not None: self._clip_by_global_norm(max_norm) self._module.update()
[ "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 gradients the ratio of the sum of their norms.
[ "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", "." ]
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 greyscale, repeat 3 times to get RGB image. if data.shape[0] == 1: data = mx.nd.tile(data, (3, 1, 1)) return data, label
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 greyscale, repeat 3 times to get RGB image. if data.shape[0] == 1: data = mx.nd.tile(data, (3, 1, 1)) return data, label
[ "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", ".", "transpose", "(", "data", ",", "(", "2", ",", "0", ",", "1", ")", ")", "# normalize to [-1, 1]", "data", "=", "data", ".", "astype", "(", "np", ".", "float32", ")", "/", "128", "-", "1", "# if image is greyscale, repeat 3 times to get RGB image.", "if", "data", ".", "shape", "[", "0", "]", "==", "1", ":", "data", "=", "mx", ".", "nd", ".", "tile", "(", "data", ",", "(", "3", ",", "1", ",", "1", ")", ")", "return", "data", ",", "label" ]
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')) # state size. (ngf*8) x 4 x 4 netG.add(nn.Conv2DTranspose(ngf * 4, 4, 2, 1, use_bias=False)) netG.add(nn.BatchNorm()) netG.add(nn.Activation('relu')) # state size. (ngf*4) x 8 x 8 netG.add(nn.Conv2DTranspose(ngf * 2, 4, 2, 1, use_bias=False)) netG.add(nn.BatchNorm()) netG.add(nn.Activation('relu')) # state size. (ngf*2) x 16 x 16 netG.add(nn.Conv2DTranspose(ngf, 4, 2, 1, use_bias=False)) netG.add(nn.BatchNorm()) netG.add(nn.Activation('relu')) # state size. (ngf) x 32 x 32 netG.add(nn.Conv2DTranspose(nc, 4, 2, 1, use_bias=False)) netG.add(nn.Activation('tanh')) # state size. (nc) x 64 x 64 return netG
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')) # state size. (ngf*8) x 4 x 4 netG.add(nn.Conv2DTranspose(ngf * 4, 4, 2, 1, use_bias=False)) netG.add(nn.BatchNorm()) netG.add(nn.Activation('relu')) # state size. (ngf*4) x 8 x 8 netG.add(nn.Conv2DTranspose(ngf * 2, 4, 2, 1, use_bias=False)) netG.add(nn.BatchNorm()) netG.add(nn.Activation('relu')) # state size. (ngf*2) x 16 x 16 netG.add(nn.Conv2DTranspose(ngf, 4, 2, 1, use_bias=False)) netG.add(nn.BatchNorm()) netG.add(nn.Activation('relu')) # state size. (ngf) x 32 x 32 netG.add(nn.Conv2DTranspose(nc, 4, 2, 1, use_bias=False)) netG.add(nn.Activation('tanh')) # state size. (nc) x 64 x 64 return netG
[ "def", "get_netG", "(", ")", ":", "# 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'", ")", ")", "# state size. (ngf*8) x 4 x 4", "netG", ".", "add", "(", "nn", ".", "Conv2DTranspose", "(", "ngf", "*", "4", ",", "4", ",", "2", ",", "1", ",", "use_bias", "=", "False", ")", ")", "netG", ".", "add", "(", "nn", ".", "BatchNorm", "(", ")", ")", "netG", ".", "add", "(", "nn", ".", "Activation", "(", "'relu'", ")", ")", "# state size. (ngf*4) x 8 x 8", "netG", ".", "add", "(", "nn", ".", "Conv2DTranspose", "(", "ngf", "*", "2", ",", "4", ",", "2", ",", "1", ",", "use_bias", "=", "False", ")", ")", "netG", ".", "add", "(", "nn", ".", "BatchNorm", "(", ")", ")", "netG", ".", "add", "(", "nn", ".", "Activation", "(", "'relu'", ")", ")", "# state size. (ngf*2) x 16 x 16", "netG", ".", "add", "(", "nn", ".", "Conv2DTranspose", "(", "ngf", ",", "4", ",", "2", ",", "1", ",", "use_bias", "=", "False", ")", ")", "netG", ".", "add", "(", "nn", ".", "BatchNorm", "(", ")", ")", "netG", ".", "add", "(", "nn", ".", "Activation", "(", "'relu'", ")", ")", "# state size. (ngf) x 32 x 32", "netG", ".", "add", "(", "nn", ".", "Conv2DTranspose", "(", "nc", ",", "4", ",", "2", ",", "1", ",", "use_bias", "=", "False", ")", ")", "netG", ".", "add", "(", "nn", ".", "Activation", "(", "'tanh'", ")", ")", "# state size. (nc) x 64 x 64", "return", "netG" ]
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 * 2, 4, 2, 1, use_bias=False)) netD.add(nn.BatchNorm()) netD.add(nn.LeakyReLU(0.2)) # state size. (ndf*2) x 16 x 16 netD.add(nn.Conv2D(ndf * 4, 4, 2, 1, use_bias=False)) netD.add(nn.BatchNorm()) netD.add(nn.LeakyReLU(0.2)) # state size. (ndf*4) x 8 x 8 netD.add(nn.Conv2D(ndf * 8, 4, 2, 1, use_bias=False)) netD.add(nn.BatchNorm()) netD.add(nn.LeakyReLU(0.2)) # state size. (ndf*8) x 4 x 4 netD.add(nn.Conv2D(2, 4, 1, 0, use_bias=False)) # state size. 2 x 1 x 1 return netD
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 * 2, 4, 2, 1, use_bias=False)) netD.add(nn.BatchNorm()) netD.add(nn.LeakyReLU(0.2)) # state size. (ndf*2) x 16 x 16 netD.add(nn.Conv2D(ndf * 4, 4, 2, 1, use_bias=False)) netD.add(nn.BatchNorm()) netD.add(nn.LeakyReLU(0.2)) # state size. (ndf*4) x 8 x 8 netD.add(nn.Conv2D(ndf * 8, 4, 2, 1, use_bias=False)) netD.add(nn.BatchNorm()) netD.add(nn.LeakyReLU(0.2)) # state size. (ndf*8) x 4 x 4 netD.add(nn.Conv2D(2, 4, 1, 0, use_bias=False)) # state size. 2 x 1 x 1 return netD
[ "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", ",", "4", ",", "2", ",", "1", ",", "use_bias", "=", "False", ")", ")", "netD", ".", "add", "(", "nn", ".", "LeakyReLU", "(", "0.2", ")", ")", "# state size. (ndf) x 32 x 32", "netD", ".", "add", "(", "nn", ".", "Conv2D", "(", "ndf", "*", "2", ",", "4", ",", "2", ",", "1", ",", "use_bias", "=", "False", ")", ")", "netD", ".", "add", "(", "nn", ".", "BatchNorm", "(", ")", ")", "netD", ".", "add", "(", "nn", ".", "LeakyReLU", "(", "0.2", ")", ")", "# state size. (ndf*2) x 16 x 16", "netD", ".", "add", "(", "nn", ".", "Conv2D", "(", "ndf", "*", "4", ",", "4", ",", "2", ",", "1", ",", "use_bias", "=", "False", ")", ")", "netD", ".", "add", "(", "nn", ".", "BatchNorm", "(", ")", ")", "netD", ".", "add", "(", "nn", ".", "LeakyReLU", "(", "0.2", ")", ")", "# state size. (ndf*4) x 8 x 8", "netD", ".", "add", "(", "nn", ".", "Conv2D", "(", "ndf", "*", "8", ",", "4", ",", "2", ",", "1", ",", "use_bias", "=", "False", ")", ")", "netD", ".", "add", "(", "nn", ".", "BatchNorm", "(", ")", ")", "netD", ".", "add", "(", "nn", ".", "LeakyReLU", "(", "0.2", ")", ")", "# state size. (ndf*8) x 4 x 4", "netD", ".", "add", "(", "nn", ".", "Conv2D", "(", "2", ",", "4", ",", "1", ",", "0", ",", "use_bias", "=", "False", ")", ")", "# state size. 2 x 1 x 1", "return", "netD" ]
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 and the discriminator trainerG = gluon.Trainer(netG.collect_params(), 'adam', {'learning_rate': opt.lr, 'beta1': opt.beta1}) trainerD = gluon.Trainer(netD.collect_params(), 'adam', {'learning_rate': opt.lr, 'beta1': opt.beta1}) return loss, trainerG, trainerD
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 and the discriminator trainerG = gluon.Trainer(netG.collect_params(), 'adam', {'learning_rate': opt.lr, 'beta1': opt.beta1}) trainerD = gluon.Trainer(netD.collect_params(), 'adam', {'learning_rate': opt.lr, 'beta1': opt.beta1}) return loss, trainerG, trainerD
[ "def", "get_configurations", "(", "netG", ",", "netD", ")", ":", "# 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 and the discriminator", "trainerG", "=", "gluon", ".", "Trainer", "(", "netG", ".", "collect_params", "(", ")", ",", "'adam'", ",", "{", "'learning_rate'", ":", "opt", ".", "lr", ",", "'beta1'", ":", "opt", ".", "beta1", "}", ")", "trainerD", "=", "gluon", ".", "Trainer", "(", "netD", ".", "collect_params", "(", ")", ",", "'adam'", ",", "{", "'learning_rate'", ":", "opt", ".", "lr", ",", "'beta1'", ":", "opt", ".", "beta1", "}", ")", "return", "loss", ",", "trainerG", ",", "trainerD" ]
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", "=", "True", ",", "last_batch", "=", "'discard'", ")" ]
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 : float or Symbol, optional Expectation of interval, should be >= 0. shape : int or tuple of ints, optional The number of samples to draw. If shape is, e.g., `(m, n)` and `lam` is a scalar, output shape will be `(m, n)`. If `lam` is an Symbol with shape, e.g., `(x, y)`, then output will have shape `(x, y, m, n)`, where `m*n` samples are drawn for each entry in `lam`. dtype : {'float16', 'float32', 'float64'}, optional Data type of output samples. Default is 'float32' Returns ------- Symbol If input `shape` has dimensions, e.g., `(m, n)`, and `lam` is a scalar, output shape will be `(m, n)`. If `lam` is an Symbol with shape, e.g., `(x, y)`, then output will have shape `(x, y, m, n)`, where `m*n` samples are drawn for each entry in `lam`. """ return _random_helper(_internal._random_poisson, _internal._sample_poisson, [lam], shape, dtype, kwargs)
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 : float or Symbol, optional Expectation of interval, should be >= 0. shape : int or tuple of ints, optional The number of samples to draw. If shape is, e.g., `(m, n)` and `lam` is a scalar, output shape will be `(m, n)`. If `lam` is an Symbol with shape, e.g., `(x, y)`, then output will have shape `(x, y, m, n)`, where `m*n` samples are drawn for each entry in `lam`. dtype : {'float16', 'float32', 'float64'}, optional Data type of output samples. Default is 'float32' Returns ------- Symbol If input `shape` has dimensions, e.g., `(m, n)`, and `lam` is a scalar, output shape will be `(m, n)`. If `lam` is an Symbol with shape, e.g., `(x, y)`, then output will have shape `(x, y, m, n)`, where `m*n` samples are drawn for each entry in `lam`. """ return _random_helper(_internal._random_poisson, _internal._sample_poisson, [lam], shape, dtype, kwargs)
[ "def", "poisson", "(", "lam", "=", "1", ",", "shape", "=", "_Null", ",", "dtype", "=", "_Null", ",", "*", "*", "kwargs", ")", ":", "return", "_random_helper", "(", "_internal", ".", "_random_poisson", ",", "_internal", ".", "_sample_poisson", ",", "[", "lam", "]", ",", "shape", ",", "dtype", ",", "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 : float or Symbol, optional Expectation of interval, should be >= 0. shape : int or tuple of ints, optional The number of samples to draw. If shape is, e.g., `(m, n)` and `lam` is a scalar, output shape will be `(m, n)`. If `lam` is an Symbol with shape, e.g., `(x, y)`, then output will have shape `(x, y, m, n)`, where `m*n` samples are drawn for each entry in `lam`. dtype : {'float16', 'float32', 'float64'}, optional Data type of output samples. Default is 'float32' Returns ------- Symbol If input `shape` has dimensions, e.g., `(m, n)`, and `lam` is a scalar, output shape will be `(m, n)`. If `lam` is an Symbol with shape, e.g., `(x, y)`, then output will have shape `(x, y, m, n)`, where `m*n` samples are drawn for each entry in `lam`.
[ "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* is defined as *1/k* where *k* is the failure limit of the number of unsuccessful experiments (generalized to real numbers). Samples will always be returned as a floating point data type. Parameters ---------- mu : float or Symbol, optional Mean of the negative binomial distribution. alpha : float or Symbol, optional Alpha (dispersion) parameter of the negative binomial distribution. shape : int or tuple of ints, optional The number of samples to draw. If shape is, e.g., `(m, n)` and `mu` and `alpha` are scalars, output shape will be `(m, n)`. If `mu` and `alpha` are Symbols with shape, e.g., `(x, y)`, then output will have shape `(x, y, m, n)`, where `m*n` samples are drawn for each `[mu, alpha)` pair. dtype : {'float16', 'float32', 'float64'}, optional Data type of output samples. Default is 'float32' Returns ------- Symbol If input `shape` has dimensions, e.g., `(m, n)`, and `mu` and `alpha` are scalars, returned Symbol will resolve to shape `(m, n)`. If `mu` and `alpha` are Symbols with shape, e.g., `(x, y)`, returned Symbol will resolve to shape `(x, y, m, n)`, where `m*n` samples are drawn for each `[mu, alpha)` pair. """ return _random_helper(_internal._random_generalized_negative_binomial, _internal._sample_generalized_negative_binomial, [mu, alpha], shape, dtype, kwargs)
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* is defined as *1/k* where *k* is the failure limit of the number of unsuccessful experiments (generalized to real numbers). Samples will always be returned as a floating point data type. Parameters ---------- mu : float or Symbol, optional Mean of the negative binomial distribution. alpha : float or Symbol, optional Alpha (dispersion) parameter of the negative binomial distribution. shape : int or tuple of ints, optional The number of samples to draw. If shape is, e.g., `(m, n)` and `mu` and `alpha` are scalars, output shape will be `(m, n)`. If `mu` and `alpha` are Symbols with shape, e.g., `(x, y)`, then output will have shape `(x, y, m, n)`, where `m*n` samples are drawn for each `[mu, alpha)` pair. dtype : {'float16', 'float32', 'float64'}, optional Data type of output samples. Default is 'float32' Returns ------- Symbol If input `shape` has dimensions, e.g., `(m, n)`, and `mu` and `alpha` are scalars, returned Symbol will resolve to shape `(m, n)`. If `mu` and `alpha` are Symbols with shape, e.g., `(x, y)`, returned Symbol will resolve to shape `(x, y, m, n)`, where `m*n` samples are drawn for each `[mu, alpha)` pair. """ return _random_helper(_internal._random_generalized_negative_binomial, _internal._sample_generalized_negative_binomial, [mu, alpha], shape, dtype, kwargs)
[ "def", "generalized_negative_binomial", "(", "mu", "=", "1", ",", "alpha", "=", "1", ",", "shape", "=", "_Null", ",", "dtype", "=", "_Null", ",", "*", "*", "kwargs", ")", ":", "return", "_random_helper", "(", "_internal", ".", "_random_generalized_negative_binomial", ",", "_internal", ".", "_sample_generalized_negative_binomial", ",", "[", "mu", ",", "alpha", "]", ",", "shape", ",", "dtype", ",", "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* is defined as *1/k* where *k* is the failure limit of the number of unsuccessful experiments (generalized to real numbers). Samples will always be returned as a floating point data type. Parameters ---------- mu : float or Symbol, optional Mean of the negative binomial distribution. alpha : float or Symbol, optional Alpha (dispersion) parameter of the negative binomial distribution. shape : int or tuple of ints, optional The number of samples to draw. If shape is, e.g., `(m, n)` and `mu` and `alpha` are scalars, output shape will be `(m, n)`. If `mu` and `alpha` are Symbols with shape, e.g., `(x, y)`, then output will have shape `(x, y, m, n)`, where `m*n` samples are drawn for each `[mu, alpha)` pair. dtype : {'float16', 'float32', 'float64'}, optional Data type of output samples. Default is 'float32' Returns ------- Symbol If input `shape` has dimensions, e.g., `(m, n)`, and `mu` and `alpha` are scalars, returned Symbol will resolve to shape `(m, n)`. If `mu` and `alpha` are Symbols with shape, e.g., `(x, y)`, returned Symbol will resolve to shape `(x, y, m, n)`, where `m*n` samples are drawn for each `[mu, alpha)` pair.
[ "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 optionally "prefix-xxxx.states", where xxxx is the epoch number. epoch : int epoch to load. load_optimizer_states : bool whether to load optimizer states. Checkpoint needs to have been made with save_optimizer_states=True. data_names : list of str Default is `('data')` for a typical model used in image classification. label_names : list of str Default is `('softmax_label')` for a typical model used in image classification. logger : Logger Default is `logging`. context : Context or list of Context Default is ``cpu()``. work_load_list : list of number Default ``None``, indicating uniform workload. fixed_param_names: list of str Default ``None``, indicating no network parameters are fixed. """ sym, args, auxs = load_checkpoint(prefix, epoch) mod = Module(symbol=sym, **kwargs) mod._arg_params = args mod._aux_params = auxs mod.params_initialized = True if load_optimizer_states: mod._preload_opt_states = '%s-%04d.states'%(prefix, epoch) return mod
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 optionally "prefix-xxxx.states", where xxxx is the epoch number. epoch : int epoch to load. load_optimizer_states : bool whether to load optimizer states. Checkpoint needs to have been made with save_optimizer_states=True. data_names : list of str Default is `('data')` for a typical model used in image classification. label_names : list of str Default is `('softmax_label')` for a typical model used in image classification. logger : Logger Default is `logging`. context : Context or list of Context Default is ``cpu()``. work_load_list : list of number Default ``None``, indicating uniform workload. fixed_param_names: list of str Default ``None``, indicating no network parameters are fixed. """ sym, args, auxs = load_checkpoint(prefix, epoch) mod = Module(symbol=sym, **kwargs) mod._arg_params = args mod._aux_params = auxs mod.params_initialized = True if load_optimizer_states: mod._preload_opt_states = '%s-%04d.states'%(prefix, epoch) return mod
[ "def", "load", "(", "prefix", ",", "epoch", ",", "load_optimizer_states", "=", "False", ",", "*", "*", "kwargs", ")", ":", "sym", ",", "args", ",", "auxs", "=", "load_checkpoint", "(", "prefix", ",", "epoch", ")", "mod", "=", "Module", "(", "symbol", "=", "sym", ",", "*", "*", "kwargs", ")", "mod", ".", "_arg_params", "=", "args", "mod", ".", "_aux_params", "=", "auxs", "mod", ".", "params_initialized", "=", "True", "if", "load_optimizer_states", ":", "mod", ".", "_preload_opt_states", "=", "'%s-%04d.states'", "%", "(", "prefix", ",", "epoch", ")", "return", "mod" ]
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. epoch : int epoch to load. load_optimizer_states : bool whether to load optimizer states. Checkpoint needs to have been made with save_optimizer_states=True. data_names : list of str Default is `('data')` for a typical model used in image classification. label_names : list of str Default is `('softmax_label')` for a typical model used in image classification. logger : Logger Default is `logging`. context : Context or list of Context Default is ``cpu()``. work_load_list : list of number Default ``None``, indicating uniform workload. fixed_param_names: list of str Default ``None``, indicating no network parameters are fixed.
[ "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. epoch : int The current epoch number. save_optimizer_states : bool Whether to save optimizer states to continue training. """ self._symbol.save('%s-symbol.json'%prefix) param_name = '%s-%04d.params' % (prefix, epoch) self.save_params(param_name) logging.info('Saved checkpoint to \"%s\"', param_name) if save_optimizer_states: state_name = '%s-%04d.states' % (prefix, epoch) self.save_optimizer_states(state_name) logging.info('Saved optimizer state to \"%s\"', state_name)
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. epoch : int The current epoch number. save_optimizer_states : bool Whether to save optimizer states to continue training. """ self._symbol.save('%s-symbol.json'%prefix) param_name = '%s-%04d.params' % (prefix, epoch) self.save_params(param_name) logging.info('Saved checkpoint to \"%s\"', param_name) if save_optimizer_states: state_name = '%s-%04d.states' % (prefix, epoch) self.save_optimizer_states(state_name) logging.info('Saved optimizer state to \"%s\"', state_name)
[ "def", "save_checkpoint", "(", "self", ",", "prefix", ",", "epoch", ",", "save_optimizer_states", "=", "False", ")", ":", "self", ".", "_symbol", ".", "save", "(", "'%s-symbol.json'", "%", "prefix", ")", "param_name", "=", "'%s-%04d.params'", "%", "(", "prefix", ",", "epoch", ")", "self", ".", "save_params", "(", "param_name", ")", "logging", ".", "info", "(", "'Saved checkpoint to \\\"%s\\\"'", ",", "param_name", ")", "if", "save_optimizer_states", ":", "state_name", "=", "'%s-%04d.states'", "%", "(", "prefix", ",", "epoch", ")", "self", ".", "save_optimizer_states", "(", "state_name", ")", "logging", ".", "info", "(", "'Saved optimizer state to \\\"%s\\\"'", ",", "state_name", ")" ]
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_states : bool Whether to save optimizer states to continue training.
[ "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.provide_label``. """ assert self.binded self._data_shapes, self._label_shapes = _parse_data_desc( self.data_names, self.label_names, data_shapes, label_shapes) self._exec_group.reshape(self._data_shapes, self._label_shapes)
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.provide_label``. """ assert self.binded self._data_shapes, self._label_shapes = _parse_data_desc( self.data_names, self.label_names, data_shapes, label_shapes) self._exec_group.reshape(self._data_shapes, self._label_shapes)
[ "def", "reshape", "(", "self", ",", "data_shapes", ",", "label_shapes", "=", "None", ")", ":", "assert", "self", ".", "binded", "self", ".", "_data_shapes", ",", "self", ".", "_label_shapes", "=", "_parse_data_desc", "(", "self", ".", "data_names", ",", "self", ".", "label_names", ",", "data_shapes", ",", "label_shapes", ")", "self", ".", "_exec_group", ".", "reshape", "(", "self", ".", "_data_shapes", ",", "self", ".", "_label_shapes", ")" ]
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 switching from training to predicting, module rebinding is required. See Also ---------- :meth:`BaseModule.forward`. Parameters ---------- data_batch : DataBatch Could be anything with similar API implemented. is_train : bool Default is ``None``, which means ``is_train`` takes the value of ``self.for_training``. """ assert self.binded and self.params_initialized curr_data_shapes = tuple(i.shape for i in self._data_shapes) if isinstance(data_batch, list): assert data_batch is not None, "Encountered empty data batch" new_data_shapes = [] for i in range(len(data_batch[0].data)): shape = data_batch[0].data[i].shape for db in data_batch: assert shape == db.data[i].shape, \ "All data batches in a list need to have the same shape" new_batch_size = len(data_batch) * shape[0] new_data_shapes.append((new_batch_size,) + shape[1:]) new_data_shapes = tuple(new_data_shapes) else: new_data_shapes = tuple(i.shape for i in data_batch.data) if curr_data_shapes != new_data_shapes: if hasattr(data_batch, "provide_data") and data_batch.provide_data: new_dshape = data_batch.provide_data else: new_dshape = [DataDesc(i.name, shape, i.dtype, i.layout) \ for i, shape in zip(self._data_shapes, new_data_shapes)] if hasattr(data_batch, "provide_label") and data_batch.provide_label: new_lshape = data_batch.provide_label elif hasattr(data_batch, "label") and data_batch.label: new_lshape = [DataDesc(i.name, j.shape, i.dtype, i.layout) \ for i, j in zip(self._label_shapes, data_batch.label)] else: new_lshape = None self.reshape(new_dshape, new_lshape) self._exec_group.forward(data_batch, is_train)
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 switching from training to predicting, module rebinding is required. See Also ---------- :meth:`BaseModule.forward`. Parameters ---------- data_batch : DataBatch Could be anything with similar API implemented. is_train : bool Default is ``None``, which means ``is_train`` takes the value of ``self.for_training``. """ assert self.binded and self.params_initialized curr_data_shapes = tuple(i.shape for i in self._data_shapes) if isinstance(data_batch, list): assert data_batch is not None, "Encountered empty data batch" new_data_shapes = [] for i in range(len(data_batch[0].data)): shape = data_batch[0].data[i].shape for db in data_batch: assert shape == db.data[i].shape, \ "All data batches in a list need to have the same shape" new_batch_size = len(data_batch) * shape[0] new_data_shapes.append((new_batch_size,) + shape[1:]) new_data_shapes = tuple(new_data_shapes) else: new_data_shapes = tuple(i.shape for i in data_batch.data) if curr_data_shapes != new_data_shapes: if hasattr(data_batch, "provide_data") and data_batch.provide_data: new_dshape = data_batch.provide_data else: new_dshape = [DataDesc(i.name, shape, i.dtype, i.layout) \ for i, shape in zip(self._data_shapes, new_data_shapes)] if hasattr(data_batch, "provide_label") and data_batch.provide_label: new_lshape = data_batch.provide_label elif hasattr(data_batch, "label") and data_batch.label: new_lshape = [DataDesc(i.name, j.shape, i.dtype, i.layout) \ for i, j in zip(self._label_shapes, data_batch.label)] else: new_lshape = None self.reshape(new_dshape, new_lshape) self._exec_group.forward(data_batch, is_train)
[ "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", ".", "_data_shapes", ")", "if", "isinstance", "(", "data_batch", ",", "list", ")", ":", "assert", "data_batch", "is", "not", "None", ",", "\"Encountered empty data batch\"", "new_data_shapes", "=", "[", "]", "for", "i", "in", "range", "(", "len", "(", "data_batch", "[", "0", "]", ".", "data", ")", ")", ":", "shape", "=", "data_batch", "[", "0", "]", ".", "data", "[", "i", "]", ".", "shape", "for", "db", "in", "data_batch", ":", "assert", "shape", "==", "db", ".", "data", "[", "i", "]", ".", "shape", ",", "\"All data batches in a list need to have the same shape\"", "new_batch_size", "=", "len", "(", "data_batch", ")", "*", "shape", "[", "0", "]", "new_data_shapes", ".", "append", "(", "(", "new_batch_size", ",", ")", "+", "shape", "[", "1", ":", "]", ")", "new_data_shapes", "=", "tuple", "(", "new_data_shapes", ")", "else", ":", "new_data_shapes", "=", "tuple", "(", "i", ".", "shape", "for", "i", "in", "data_batch", ".", "data", ")", "if", "curr_data_shapes", "!=", "new_data_shapes", ":", "if", "hasattr", "(", "data_batch", ",", "\"provide_data\"", ")", "and", "data_batch", ".", "provide_data", ":", "new_dshape", "=", "data_batch", ".", "provide_data", "else", ":", "new_dshape", "=", "[", "DataDesc", "(", "i", ".", "name", ",", "shape", ",", "i", ".", "dtype", ",", "i", ".", "layout", ")", "for", "i", ",", "shape", "in", "zip", "(", "self", ".", "_data_shapes", ",", "new_data_shapes", ")", "]", "if", "hasattr", "(", "data_batch", ",", "\"provide_label\"", ")", "and", "data_batch", ".", "provide_label", ":", "new_lshape", "=", "data_batch", ".", "provide_label", "elif", "hasattr", "(", "data_batch", ",", "\"label\"", ")", "and", "data_batch", ".", "label", ":", "new_lshape", "=", "[", "DataDesc", "(", "i", ".", "name", ",", "j", ".", "shape", ",", "i", ".", "dtype", ",", "i", ".", "layout", ")", "for", "i", ",", "j", "in", "zip", "(", "self", ".", "_label_shapes", ",", "data_batch", ".", "label", ")", "]", "else", ":", "new_lshape", "=", "None", "self", ".", "reshape", "(", "new_dshape", ",", "new_lshape", ")", "self", ".", "_exec_group", ".", "forward", "(", "data_batch", ",", "is_train", ")" ]
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 rebinding is required. See Also ---------- :meth:`BaseModule.forward`. Parameters ---------- data_batch : DataBatch Could be anything with similar API implemented. is_train : bool Default is ``None``, which means ``is_train`` takes the value of ``self.for_training``.
[ "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", "rebinding", "is", "required", "." ]
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 for `row_sparse` parameters, this function does update the copy of parameters in KVStore, but doesn't broadcast the updated parameters to all devices / machines. Please call `prepare` to broadcast `row_sparse` parameters with the next batch of data. See Also ---------- :meth:`BaseModule.update`. """ assert self.binded and self.params_initialized and self.optimizer_initialized self._params_dirty = True if self._update_on_kvstore: _update_params_on_kvstore(self._exec_group.param_arrays, self._exec_group.grad_arrays, self._kvstore, self._exec_group.param_names) else: _update_params(self._exec_group.param_arrays, self._exec_group.grad_arrays, updater=self._updater, num_device=len(self._context), kvstore=self._kvstore, param_names=self._exec_group.param_names)
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 for `row_sparse` parameters, this function does update the copy of parameters in KVStore, but doesn't broadcast the updated parameters to all devices / machines. Please call `prepare` to broadcast `row_sparse` parameters with the next batch of data. See Also ---------- :meth:`BaseModule.update`. """ assert self.binded and self.params_initialized and self.optimizer_initialized self._params_dirty = True if self._update_on_kvstore: _update_params_on_kvstore(self._exec_group.param_arrays, self._exec_group.grad_arrays, self._kvstore, self._exec_group.param_names) else: _update_params(self._exec_group.param_arrays, self._exec_group.grad_arrays, updater=self._updater, num_device=len(self._context), kvstore=self._kvstore, param_names=self._exec_group.param_names)
[ "def", "update", "(", "self", ")", ":", "assert", "self", ".", "binded", "and", "self", ".", "params_initialized", "and", "self", ".", "optimizer_initialized", "self", ".", "_params_dirty", "=", "True", "if", "self", ".", "_update_on_kvstore", ":", "_update_params_on_kvstore", "(", "self", ".", "_exec_group", ".", "param_arrays", ",", "self", ".", "_exec_group", ".", "grad_arrays", ",", "self", ".", "_kvstore", ",", "self", ".", "_exec_group", ".", "param_names", ")", "else", ":", "_update_params", "(", "self", ".", "_exec_group", ".", "param_arrays", ",", "self", ".", "_exec_group", ".", "grad_arrays", ",", "updater", "=", "self", ".", "_updater", ",", "num_device", "=", "len", "(", "self", ".", "_context", ")", ",", "kvstore", "=", "self", ".", "_kvstore", ",", "param_names", "=", "self", ".", "_exec_group", ".", "param_names", ")" ]
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, this function does update the copy of parameters in KVStore, but doesn't broadcast the updated parameters to all devices / machines. Please call `prepare` to broadcast `row_sparse` parameters with the next batch of data. See Also ---------- :meth:`BaseModule.update`.
[ "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`. When `merge_multi_context` is `False`, those `NDArray` might live on different devices. Parameters ---------- merge_multi_context : bool Default is ``True``. In the case when data-parallelism is used, the outputs will be collected from multiple devices. A ``True`` value indicate that we should merge the collected results so that they look like from a single executor. Returns ------- list of NDArray or list of list of NDArray Output. """ assert self.binded and self.params_initialized return self._exec_group.get_outputs(merge_multi_context=merge_multi_context)
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`. When `merge_multi_context` is `False`, those `NDArray` might live on different devices. Parameters ---------- merge_multi_context : bool Default is ``True``. In the case when data-parallelism is used, the outputs will be collected from multiple devices. A ``True`` value indicate that we should merge the collected results so that they look like from a single executor. Returns ------- list of NDArray or list of list of NDArray Output. """ assert self.binded and self.params_initialized return self._exec_group.get_outputs(merge_multi_context=merge_multi_context)
[ "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_multi_context", ")" ]
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` might live on different devices. Parameters ---------- merge_multi_context : bool Default is ``True``. In the case when data-parallelism is used, the outputs will be collected from multiple devices. A ``True`` value indicate that we should merge the collected results so that they look like from a single executor. Returns ------- list of NDArray or list of list of NDArray Output.
[ "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_sparse parameters on devices, ther are pulled from KVStore with all row ids. """ self._exec_group.get_params(self._arg_params, self._aux_params) if self._kvstore and self._update_on_kvstore: for param_name, param_val in sorted(self._arg_params.items()): if param_val.stype == 'row_sparse': row_ids = nd.arange(0, param_val.shape[0], dtype='int64') self._kvstore.row_sparse_pull(param_name, param_val, row_ids=row_ids) self._params_dirty = False
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_sparse parameters on devices, ther are pulled from KVStore with all row ids. """ self._exec_group.get_params(self._arg_params, self._aux_params) if self._kvstore and self._update_on_kvstore: for param_name, param_val in sorted(self._arg_params.items()): if param_val.stype == 'row_sparse': row_ids = nd.arange(0, param_val.shape[0], dtype='int64') self._kvstore.row_sparse_pull(param_name, param_val, row_ids=row_ids) self._params_dirty = False
[ "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", ":", "for", "param_name", ",", "param_val", "in", "sorted", "(", "self", ".", "_arg_params", ".", "items", "(", ")", ")", ":", "if", "param_val", ".", "stype", "==", "'row_sparse'", ":", "row_ids", "=", "nd", ".", "arange", "(", "0", ",", "param_val", ".", "shape", "[", "0", "]", ",", "dtype", "=", "'int64'", ")", "self", ".", "_kvstore", ".", "row_sparse_pull", "(", "param_name", ",", "param_val", ",", "row_ids", "=", "row_ids", ")", "self", ".", "_params_dirty", "=", "False" ]
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 KVStore with all row ids.
[ "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", "." ]
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 NDArray, optional Lower boundary of the output interval. All values generated will be greater than or equal to low. The default value is 0. high : float or NDArray, optional Upper boundary of the output interval. All values generated will be less than high. The default value is 1.0. shape : int or tuple of ints, optional The number of samples to draw. If shape is, e.g., `(m, n)` and `low` and `high` are scalars, output shape will be `(m, n)`. If `low` and `high` are NDArrays with shape, e.g., `(x, y)`, then output will have shape `(x, y, m, n)`, where `m*n` samples are drawn for each `[low, high)` pair. dtype : {'float16', 'float32', 'float64'}, optional Data type of output samples. Default is 'float32' ctx : Context, optional Device context of output. Default is current context. Overridden by `low.context` when `low` is an NDArray. out : NDArray, optional Store output to an existing NDArray. Returns ------- NDArray An NDArray of type `dtype`. If input `shape` has shape, e.g., `(m, n)` and `low` and `high` are scalars, output shape will be `(m, n)`. If `low` and `high` are NDArrays with shape, e.g., `(x, y)`, then the return NDArray will have shape `(x, y, m, n)`, where `m*n` uniformly distributed samples are drawn for each `[low, high)` pair. Examples -------- >>> mx.nd.random.uniform(0, 1) [ 0.54881352] <NDArray 1 @cpu(0) >>> mx.nd.random.uniform(0, 1, ctx=mx.gpu(0)) [ 0.92514056] <NDArray 1 @gpu(0)> >>> mx.nd.random.uniform(-1, 1, shape=(2,)) [ 0.71589124 0.08976638] <NDArray 2 @cpu(0)> >>> low = mx.nd.array([1,2,3]) >>> high = mx.nd.array([2,3,4]) >>> mx.nd.random.uniform(low, high, shape=2) [[ 1.78653979 1.93707538] [ 2.01311183 2.37081361] [ 3.30491424 3.69977832]] <NDArray 3x2 @cpu(0)> """ return _random_helper(_internal._random_uniform, _internal._sample_uniform, [low, high], shape, dtype, ctx, out, kwargs)
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 NDArray, optional Lower boundary of the output interval. All values generated will be greater than or equal to low. The default value is 0. high : float or NDArray, optional Upper boundary of the output interval. All values generated will be less than high. The default value is 1.0. shape : int or tuple of ints, optional The number of samples to draw. If shape is, e.g., `(m, n)` and `low` and `high` are scalars, output shape will be `(m, n)`. If `low` and `high` are NDArrays with shape, e.g., `(x, y)`, then output will have shape `(x, y, m, n)`, where `m*n` samples are drawn for each `[low, high)` pair. dtype : {'float16', 'float32', 'float64'}, optional Data type of output samples. Default is 'float32' ctx : Context, optional Device context of output. Default is current context. Overridden by `low.context` when `low` is an NDArray. out : NDArray, optional Store output to an existing NDArray. Returns ------- NDArray An NDArray of type `dtype`. If input `shape` has shape, e.g., `(m, n)` and `low` and `high` are scalars, output shape will be `(m, n)`. If `low` and `high` are NDArrays with shape, e.g., `(x, y)`, then the return NDArray will have shape `(x, y, m, n)`, where `m*n` uniformly distributed samples are drawn for each `[low, high)` pair. Examples -------- >>> mx.nd.random.uniform(0, 1) [ 0.54881352] <NDArray 1 @cpu(0) >>> mx.nd.random.uniform(0, 1, ctx=mx.gpu(0)) [ 0.92514056] <NDArray 1 @gpu(0)> >>> mx.nd.random.uniform(-1, 1, shape=(2,)) [ 0.71589124 0.08976638] <NDArray 2 @cpu(0)> >>> low = mx.nd.array([1,2,3]) >>> high = mx.nd.array([2,3,4]) >>> mx.nd.random.uniform(low, high, shape=2) [[ 1.78653979 1.93707538] [ 2.01311183 2.37081361] [ 3.30491424 3.69977832]] <NDArray 3x2 @cpu(0)> """ return _random_helper(_internal._random_uniform, _internal._sample_uniform, [low, high], shape, dtype, ctx, out, kwargs)
[ "def", "uniform", "(", "low", "=", "0", ",", "high", "=", "1", ",", "shape", "=", "_Null", ",", "dtype", "=", "_Null", ",", "ctx", "=", "None", ",", "out", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "_random_helper", "(", "_internal", ".", "_random_uniform", ",", "_internal", ".", "_sample_uniform", ",", "[", "low", ",", "high", "]", ",", "shape", ",", "dtype", ",", "ctx", ",", "out", ",", "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 NDArray, optional Lower boundary of the output interval. All values generated will be greater than or equal to low. The default value is 0. high : float or NDArray, optional Upper boundary of the output interval. All values generated will be less than high. The default value is 1.0. shape : int or tuple of ints, optional The number of samples to draw. If shape is, e.g., `(m, n)` and `low` and `high` are scalars, output shape will be `(m, n)`. If `low` and `high` are NDArrays with shape, e.g., `(x, y)`, then output will have shape `(x, y, m, n)`, where `m*n` samples are drawn for each `[low, high)` pair. dtype : {'float16', 'float32', 'float64'}, optional Data type of output samples. Default is 'float32' ctx : Context, optional Device context of output. Default is current context. Overridden by `low.context` when `low` is an NDArray. out : NDArray, optional Store output to an existing NDArray. Returns ------- NDArray An NDArray of type `dtype`. If input `shape` has shape, e.g., `(m, n)` and `low` and `high` are scalars, output shape will be `(m, n)`. If `low` and `high` are NDArrays with shape, e.g., `(x, y)`, then the return NDArray will have shape `(x, y, m, n)`, where `m*n` uniformly distributed samples are drawn for each `[low, high)` pair. Examples -------- >>> mx.nd.random.uniform(0, 1) [ 0.54881352] <NDArray 1 @cpu(0) >>> mx.nd.random.uniform(0, 1, ctx=mx.gpu(0)) [ 0.92514056] <NDArray 1 @gpu(0)> >>> mx.nd.random.uniform(-1, 1, shape=(2,)) [ 0.71589124 0.08976638] <NDArray 2 @cpu(0)> >>> low = mx.nd.array([1,2,3]) >>> high = mx.nd.array([2,3,4]) >>> mx.nd.random.uniform(low, high, shape=2) [[ 1.78653979 1.93707538] [ 2.01311183 2.37081361] [ 3.30491424 3.69977832]] <NDArray 3x2 @cpu(0)>
[ "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, which is the inverse of the rate parameter \lambda = 1/\beta. Parameters ---------- scale : float or NDArray, optional The scale parameter, \beta = 1/\lambda. shape : int or tuple of ints, optional The number of samples to draw. If shape is, e.g., `(m, n)` and `scale` is a scalar, output shape will be `(m, n)`. If `scale` is an NDArray with shape, e.g., `(x, y)`, then output will have shape `(x, y, m, n)`, where `m*n` samples are drawn for each entry in `scale`. dtype : {'float16', 'float32', 'float64'}, optional Data type of output samples. Default is 'float32' ctx : Context, optional Device context of output. Default is current context. Overridden by `scale.context` when `scale` is an NDArray. out : NDArray, optional Store output to an existing NDArray. Returns ------- NDArray If input `shape` has shape, e.g., `(m, n)` and `scale` is a scalar, output shape will be `(m, n)`. If `scale` is an NDArray with shape, e.g., `(x, y)`, then `output` will have shape `(x, y, m, n)`, where `m*n` samples are drawn for each entry in scale. Examples -------- >>> mx.nd.random.exponential(1) [ 0.79587454] <NDArray 1 @cpu(0)> >>> mx.nd.random.exponential(1, shape=(2,)) [ 0.89856035 1.25593066] <NDArray 2 @cpu(0)> >>> scale = mx.nd.array([1,2,3]) >>> mx.nd.random.exponential(scale, shape=2) [[ 0.41063145 0.42140478] [ 2.59407091 10.12439728] [ 2.42544937 1.14260709]] <NDArray 3x2 @cpu(0)> """ return _random_helper(_internal._random_exponential, _internal._sample_exponential, [1.0/scale], shape, dtype, ctx, out, kwargs)
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, which is the inverse of the rate parameter \lambda = 1/\beta. Parameters ---------- scale : float or NDArray, optional The scale parameter, \beta = 1/\lambda. shape : int or tuple of ints, optional The number of samples to draw. If shape is, e.g., `(m, n)` and `scale` is a scalar, output shape will be `(m, n)`. If `scale` is an NDArray with shape, e.g., `(x, y)`, then output will have shape `(x, y, m, n)`, where `m*n` samples are drawn for each entry in `scale`. dtype : {'float16', 'float32', 'float64'}, optional Data type of output samples. Default is 'float32' ctx : Context, optional Device context of output. Default is current context. Overridden by `scale.context` when `scale` is an NDArray. out : NDArray, optional Store output to an existing NDArray. Returns ------- NDArray If input `shape` has shape, e.g., `(m, n)` and `scale` is a scalar, output shape will be `(m, n)`. If `scale` is an NDArray with shape, e.g., `(x, y)`, then `output` will have shape `(x, y, m, n)`, where `m*n` samples are drawn for each entry in scale. Examples -------- >>> mx.nd.random.exponential(1) [ 0.79587454] <NDArray 1 @cpu(0)> >>> mx.nd.random.exponential(1, shape=(2,)) [ 0.89856035 1.25593066] <NDArray 2 @cpu(0)> >>> scale = mx.nd.array([1,2,3]) >>> mx.nd.random.exponential(scale, shape=2) [[ 0.41063145 0.42140478] [ 2.59407091 10.12439728] [ 2.42544937 1.14260709]] <NDArray 3x2 @cpu(0)> """ return _random_helper(_internal._random_exponential, _internal._sample_exponential, [1.0/scale], shape, dtype, ctx, out, kwargs)
[ "def", "exponential", "(", "scale", "=", "1", ",", "shape", "=", "_Null", ",", "dtype", "=", "_Null", ",", "ctx", "=", "None", ",", "out", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "_random_helper", "(", "_internal", ".", "_random_exponential", ",", "_internal", ".", "_sample_exponential", ",", "[", "1.0", "/", "scale", "]", ",", "shape", ",", "dtype", ",", "ctx", ",", "out", ",", "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, which is the inverse of the rate parameter \lambda = 1/\beta. Parameters ---------- scale : float or NDArray, optional The scale parameter, \beta = 1/\lambda. shape : int or tuple of ints, optional The number of samples to draw. If shape is, e.g., `(m, n)` and `scale` is a scalar, output shape will be `(m, n)`. If `scale` is an NDArray with shape, e.g., `(x, y)`, then output will have shape `(x, y, m, n)`, where `m*n` samples are drawn for each entry in `scale`. dtype : {'float16', 'float32', 'float64'}, optional Data type of output samples. Default is 'float32' ctx : Context, optional Device context of output. Default is current context. Overridden by `scale.context` when `scale` is an NDArray. out : NDArray, optional Store output to an existing NDArray. Returns ------- NDArray If input `shape` has shape, e.g., `(m, n)` and `scale` is a scalar, output shape will be `(m, n)`. If `scale` is an NDArray with shape, e.g., `(x, y)`, then `output` will have shape `(x, y, m, n)`, where `m*n` samples are drawn for each entry in scale. Examples -------- >>> mx.nd.random.exponential(1) [ 0.79587454] <NDArray 1 @cpu(0)> >>> mx.nd.random.exponential(1, shape=(2,)) [ 0.89856035 1.25593066] <NDArray 2 @cpu(0)> >>> scale = mx.nd.array([1,2,3]) >>> mx.nd.random.exponential(scale, shape=2) [[ 0.41063145 0.42140478] [ 2.59407091 10.12439728] [ 2.42544937 1.14260709]] <NDArray 3x2 @cpu(0)>
[ "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, optional The shape of the gamma distribution. Should be greater than zero. beta : float or NDArray, optional The scale of the gamma distribution. Should be greater than zero. Default is equal to 1. shape : int or tuple of ints, optional The number of samples to draw. If shape is, e.g., `(m, n)` and `alpha` and `beta` are scalars, output shape will be `(m, n)`. If `alpha` and `beta` are NDArrays with shape, e.g., `(x, y)`, then output will have shape `(x, y, m, n)`, where `m*n` samples are drawn for each `[alpha, beta)` pair. dtype : {'float16', 'float32', 'float64'}, optional Data type of output samples. Default is 'float32' ctx : Context, optional Device context of output. Default is current context. Overridden by `alpha.context` when `alpha` is an NDArray. out : NDArray, optional Store output to an existing NDArray. Returns ------- NDArray If input `shape` has shape, e.g., `(m, n)` and `alpha` and `beta` are scalars, output shape will be `(m, n)`. If `alpha` and `beta` are NDArrays with shape, e.g., `(x, y)`, then output will have shape `(x, y, m, n)`, where `m*n` samples are drawn for each `[alpha, beta)` pair. Examples -------- >>> mx.nd.random.gamma(1, 1) [ 1.93308783] <NDArray 1 @cpu(0)> >>> mx.nd.random.gamma(1, 1, shape=(2,)) [ 0.48216391 2.09890771] <NDArray 2 @cpu(0)> >>> alpha = mx.nd.array([1,2,3]) >>> beta = mx.nd.array([2,3,4]) >>> mx.nd.random.gamma(alpha, beta, shape=2) [[ 3.24343276 0.94137681] [ 3.52734375 0.45568955] [ 14.26264095 14.0170126 ]] <NDArray 3x2 @cpu(0)> """ return _random_helper(_internal._random_gamma, _internal._sample_gamma, [alpha, beta], shape, dtype, ctx, out, kwargs)
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, optional The shape of the gamma distribution. Should be greater than zero. beta : float or NDArray, optional The scale of the gamma distribution. Should be greater than zero. Default is equal to 1. shape : int or tuple of ints, optional The number of samples to draw. If shape is, e.g., `(m, n)` and `alpha` and `beta` are scalars, output shape will be `(m, n)`. If `alpha` and `beta` are NDArrays with shape, e.g., `(x, y)`, then output will have shape `(x, y, m, n)`, where `m*n` samples are drawn for each `[alpha, beta)` pair. dtype : {'float16', 'float32', 'float64'}, optional Data type of output samples. Default is 'float32' ctx : Context, optional Device context of output. Default is current context. Overridden by `alpha.context` when `alpha` is an NDArray. out : NDArray, optional Store output to an existing NDArray. Returns ------- NDArray If input `shape` has shape, e.g., `(m, n)` and `alpha` and `beta` are scalars, output shape will be `(m, n)`. If `alpha` and `beta` are NDArrays with shape, e.g., `(x, y)`, then output will have shape `(x, y, m, n)`, where `m*n` samples are drawn for each `[alpha, beta)` pair. Examples -------- >>> mx.nd.random.gamma(1, 1) [ 1.93308783] <NDArray 1 @cpu(0)> >>> mx.nd.random.gamma(1, 1, shape=(2,)) [ 0.48216391 2.09890771] <NDArray 2 @cpu(0)> >>> alpha = mx.nd.array([1,2,3]) >>> beta = mx.nd.array([2,3,4]) >>> mx.nd.random.gamma(alpha, beta, shape=2) [[ 3.24343276 0.94137681] [ 3.52734375 0.45568955] [ 14.26264095 14.0170126 ]] <NDArray 3x2 @cpu(0)> """ return _random_helper(_internal._random_gamma, _internal._sample_gamma, [alpha, beta], shape, dtype, ctx, out, kwargs)
[ "def", "gamma", "(", "alpha", "=", "1", ",", "beta", "=", "1", ",", "shape", "=", "_Null", ",", "dtype", "=", "_Null", ",", "ctx", "=", "None", ",", "out", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "_random_helper", "(", "_internal", ".", "_random_gamma", ",", "_internal", ".", "_sample_gamma", ",", "[", "alpha", ",", "beta", "]", ",", "shape", ",", "dtype", ",", "ctx", ",", "out", ",", "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, optional The shape of the gamma distribution. Should be greater than zero. beta : float or NDArray, optional The scale of the gamma distribution. Should be greater than zero. Default is equal to 1. shape : int or tuple of ints, optional The number of samples to draw. If shape is, e.g., `(m, n)` and `alpha` and `beta` are scalars, output shape will be `(m, n)`. If `alpha` and `beta` are NDArrays with shape, e.g., `(x, y)`, then output will have shape `(x, y, m, n)`, where `m*n` samples are drawn for each `[alpha, beta)` pair. dtype : {'float16', 'float32', 'float64'}, optional Data type of output samples. Default is 'float32' ctx : Context, optional Device context of output. Default is current context. Overridden by `alpha.context` when `alpha` is an NDArray. out : NDArray, optional Store output to an existing NDArray. Returns ------- NDArray If input `shape` has shape, e.g., `(m, n)` and `alpha` and `beta` are scalars, output shape will be `(m, n)`. If `alpha` and `beta` are NDArrays with shape, e.g., `(x, y)`, then output will have shape `(x, y, m, n)`, where `m*n` samples are drawn for each `[alpha, beta)` pair. Examples -------- >>> mx.nd.random.gamma(1, 1) [ 1.93308783] <NDArray 1 @cpu(0)> >>> mx.nd.random.gamma(1, 1, shape=(2,)) [ 0.48216391 2.09890771] <NDArray 2 @cpu(0)> >>> alpha = mx.nd.array([1,2,3]) >>> beta = mx.nd.array([2,3,4]) >>> mx.nd.random.gamma(alpha, beta, shape=2) [[ 3.24343276 0.94137681] [ 3.52734375 0.45568955] [ 14.26264095 14.0170126 ]] <NDArray 3x2 @cpu(0)>
[ "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* (failure probability in each experiment). Samples will always be returned as a floating point data type. Parameters ---------- k : float or NDArray, optional Limit of unsuccessful experiments, > 0. p : float or NDArray, optional Failure probability in each experiment, >= 0 and <=1. shape : int or tuple of ints, optional The number of samples to draw. If shape is, e.g., `(m, n)` and `k` and `p` are scalars, output shape will be `(m, n)`. If `k` and `p` are NDArrays with shape, e.g., `(x, y)`, then output will have shape `(x, y, m, n)`, where `m*n` samples are drawn for each `[k, p)` pair. dtype : {'float16', 'float32', 'float64'}, optional Data type of output samples. Default is 'float32' ctx : Context, optional Device context of output. Default is current context. Overridden by `k.context` when `k` is an NDArray. out : NDArray, optional Store output to an existing NDArray. Returns ------- NDArray If input `shape` has shape, e.g., `(m, n)` and `k` and `p` are scalars, output shape will be `(m, n)`. If `k` and `p` are NDArrays with shape, e.g., `(x, y)`, then output will have shape `(x, y, m, n)`, where `m*n` samples are drawn for each `[k, p)` pair. Examples -------- >>> mx.nd.random.negative_binomial(10, 0.5) [ 4.] <NDArray 1 @cpu(0)> >>> mx.nd.random.negative_binomial(10, 0.5, shape=(2,)) [ 3. 4.] <NDArray 2 @cpu(0)> >>> k = mx.nd.array([1,2,3]) >>> p = mx.nd.array([0.2,0.4,0.6]) >>> mx.nd.random.negative_binomial(k, p, shape=2) [[ 3. 2.] [ 4. 4.] [ 0. 5.]] <NDArray 3x2 @cpu(0)> """ return _random_helper(_internal._random_negative_binomial, _internal._sample_negative_binomial, [k, p], shape, dtype, ctx, out, kwargs)
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* (failure probability in each experiment). Samples will always be returned as a floating point data type. Parameters ---------- k : float or NDArray, optional Limit of unsuccessful experiments, > 0. p : float or NDArray, optional Failure probability in each experiment, >= 0 and <=1. shape : int or tuple of ints, optional The number of samples to draw. If shape is, e.g., `(m, n)` and `k` and `p` are scalars, output shape will be `(m, n)`. If `k` and `p` are NDArrays with shape, e.g., `(x, y)`, then output will have shape `(x, y, m, n)`, where `m*n` samples are drawn for each `[k, p)` pair. dtype : {'float16', 'float32', 'float64'}, optional Data type of output samples. Default is 'float32' ctx : Context, optional Device context of output. Default is current context. Overridden by `k.context` when `k` is an NDArray. out : NDArray, optional Store output to an existing NDArray. Returns ------- NDArray If input `shape` has shape, e.g., `(m, n)` and `k` and `p` are scalars, output shape will be `(m, n)`. If `k` and `p` are NDArrays with shape, e.g., `(x, y)`, then output will have shape `(x, y, m, n)`, where `m*n` samples are drawn for each `[k, p)` pair. Examples -------- >>> mx.nd.random.negative_binomial(10, 0.5) [ 4.] <NDArray 1 @cpu(0)> >>> mx.nd.random.negative_binomial(10, 0.5, shape=(2,)) [ 3. 4.] <NDArray 2 @cpu(0)> >>> k = mx.nd.array([1,2,3]) >>> p = mx.nd.array([0.2,0.4,0.6]) >>> mx.nd.random.negative_binomial(k, p, shape=2) [[ 3. 2.] [ 4. 4.] [ 0. 5.]] <NDArray 3x2 @cpu(0)> """ return _random_helper(_internal._random_negative_binomial, _internal._sample_negative_binomial, [k, p], shape, dtype, ctx, out, kwargs)
[ "def", "negative_binomial", "(", "k", "=", "1", ",", "p", "=", "1", ",", "shape", "=", "_Null", ",", "dtype", "=", "_Null", ",", "ctx", "=", "None", ",", "out", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "_random_helper", "(", "_internal", ".", "_random_negative_binomial", ",", "_internal", ".", "_sample_negative_binomial", ",", "[", "k", ",", "p", "]", ",", "shape", ",", "dtype", ",", "ctx", ",", "out", ",", "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* (failure probability in each experiment). Samples will always be returned as a floating point data type. Parameters ---------- k : float or NDArray, optional Limit of unsuccessful experiments, > 0. p : float or NDArray, optional Failure probability in each experiment, >= 0 and <=1. shape : int or tuple of ints, optional The number of samples to draw. If shape is, e.g., `(m, n)` and `k` and `p` are scalars, output shape will be `(m, n)`. If `k` and `p` are NDArrays with shape, e.g., `(x, y)`, then output will have shape `(x, y, m, n)`, where `m*n` samples are drawn for each `[k, p)` pair. dtype : {'float16', 'float32', 'float64'}, optional Data type of output samples. Default is 'float32' ctx : Context, optional Device context of output. Default is current context. Overridden by `k.context` when `k` is an NDArray. out : NDArray, optional Store output to an existing NDArray. Returns ------- NDArray If input `shape` has shape, e.g., `(m, n)` and `k` and `p` are scalars, output shape will be `(m, n)`. If `k` and `p` are NDArrays with shape, e.g., `(x, y)`, then output will have shape `(x, y, m, n)`, where `m*n` samples are drawn for each `[k, p)` pair. Examples -------- >>> mx.nd.random.negative_binomial(10, 0.5) [ 4.] <NDArray 1 @cpu(0)> >>> mx.nd.random.negative_binomial(10, 0.5, shape=(2,)) [ 3. 4.] <NDArray 2 @cpu(0)> >>> k = mx.nd.array([1,2,3]) >>> p = mx.nd.array([0.2,0.4,0.6]) >>> mx.nd.random.negative_binomial(k, p, shape=2) [[ 3. 2.] [ 4. 4.] [ 0. 5.]] <NDArray 3x2 @cpu(0)>
[ "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, required Lower boundary of the output interval. All values generated will be greater than or equal to low. high : int, required Upper boundary of the output interval. All values generated will be less than high. shape : int or tuple of ints, optional The number of samples to draw. If shape is, e.g., `(m, n)` and `low` and `high` are scalars, output shape will be `(m, n)`. dtype : {'int32', 'int64'}, optional Data type of output samples. Default is 'int32' ctx : Context, optional Device context of output. Default is current context. Overridden by `low.context` when `low` is an NDArray. out : NDArray, optional Store output to an existing NDArray. Returns ------- NDArray An NDArray of type `dtype`. If input `shape` has shape, e.g., `(m, n)`, the returned NDArray will shape will be `(m, n)`. Contents of the returned NDArray will be samples from the interval `[low, high)`. Examples -------- >>> mx.nd.random.randint(5, 100) [ 90] <NDArray 1 @cpu(0) >>> mx.nd.random.randint(-10, 2, ctx=mx.gpu(0)) [ -8] <NDArray 1 @gpu(0)> >>> mx.nd.random.randint(-10, 10, shape=(2,)) [ -5 4] <NDArray 2 @cpu(0)> """ return _random_helper(_internal._random_randint, None, [low, high], shape, dtype, ctx, out, kwargs)
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, required Lower boundary of the output interval. All values generated will be greater than or equal to low. high : int, required Upper boundary of the output interval. All values generated will be less than high. shape : int or tuple of ints, optional The number of samples to draw. If shape is, e.g., `(m, n)` and `low` and `high` are scalars, output shape will be `(m, n)`. dtype : {'int32', 'int64'}, optional Data type of output samples. Default is 'int32' ctx : Context, optional Device context of output. Default is current context. Overridden by `low.context` when `low` is an NDArray. out : NDArray, optional Store output to an existing NDArray. Returns ------- NDArray An NDArray of type `dtype`. If input `shape` has shape, e.g., `(m, n)`, the returned NDArray will shape will be `(m, n)`. Contents of the returned NDArray will be samples from the interval `[low, high)`. Examples -------- >>> mx.nd.random.randint(5, 100) [ 90] <NDArray 1 @cpu(0) >>> mx.nd.random.randint(-10, 2, ctx=mx.gpu(0)) [ -8] <NDArray 1 @gpu(0)> >>> mx.nd.random.randint(-10, 10, shape=(2,)) [ -5 4] <NDArray 2 @cpu(0)> """ return _random_helper(_internal._random_randint, None, [low, high], shape, dtype, ctx, out, kwargs)
[ "def", "randint", "(", "low", ",", "high", ",", "shape", "=", "_Null", ",", "dtype", "=", "_Null", ",", "ctx", "=", "None", ",", "out", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "_random_helper", "(", "_internal", ".", "_random_randint", ",", "None", ",", "[", "low", ",", "high", "]", ",", "shape", ",", "dtype", ",", "ctx", ",", "out", ",", "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, required Lower boundary of the output interval. All values generated will be greater than or equal to low. high : int, required Upper boundary of the output interval. All values generated will be less than high. shape : int or tuple of ints, optional The number of samples to draw. If shape is, e.g., `(m, n)` and `low` and `high` are scalars, output shape will be `(m, n)`. dtype : {'int32', 'int64'}, optional Data type of output samples. Default is 'int32' ctx : Context, optional Device context of output. Default is current context. Overridden by `low.context` when `low` is an NDArray. out : NDArray, optional Store output to an existing NDArray. Returns ------- NDArray An NDArray of type `dtype`. If input `shape` has shape, e.g., `(m, n)`, the returned NDArray will shape will be `(m, n)`. Contents of the returned NDArray will be samples from the interval `[low, high)`. Examples -------- >>> mx.nd.random.randint(5, 100) [ 90] <NDArray 1 @cpu(0) >>> mx.nd.random.randint(-10, 2, ctx=mx.gpu(0)) [ -8] <NDArray 1 @gpu(0)> >>> mx.nd.random.randint(-10, 10, shape=(2,)) [ -5 4] <NDArray 2 @cpu(0)>
[ "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_to_init = [] if self._kvstore: for param in self._params_to_init: if param._deferred_init: params_to_init.append(param) else: param_arrays = param._check_and_get(param._data, list) idx = self._param2idx[param.name] self._kvstore.init(idx, param_arrays[0]) if param._stype == 'default': self._kvstore.pull(idx, param_arrays, priority=-idx) self._params_to_init = params_to_init
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_to_init = [] if self._kvstore: for param in self._params_to_init: if param._deferred_init: params_to_init.append(param) else: param_arrays = param._check_and_get(param._data, list) idx = self._param2idx[param.name] self._kvstore.init(idx, param_arrays[0]) if param._stype == 'default': self._kvstore.pull(idx, param_arrays, priority=-idx) self._params_to_init = params_to_init
[ "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", "in", "self", ".", "_params_to_init", ":", "if", "param", ".", "_deferred_init", ":", "params_to_init", ".", "append", "(", "param", ")", "else", ":", "param_arrays", "=", "param", ".", "_check_and_get", "(", "param", ".", "_data", ",", "list", ")", "idx", "=", "self", ".", "_param2idx", "[", "param", ".", "name", "]", "self", ".", "_kvstore", ".", "init", "(", "idx", ",", "param_arrays", "[", "0", "]", ")", "if", "param", ".", "_stype", "==", "'default'", ":", "self", ".", "_kvstore", ".", "pull", "(", "idx", ",", "param_arrays", ",", "priority", "=", "-", "idx", ")", "self", ".", "_params_to_init", "=", "params_to_init" ]
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 self._params_to_init = [param for param in self._params]
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 self._params_to_init = [param for param in self._params]
[ "def", "_reset_kvstore", "(", "self", ")", ":", "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", "self", ".", "_params_to_init", "=", "[", "param", "for", "param", "in", "self", ".", "_params", "]" ]
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. # The training loop is the following: # - row_sparse_pull(sparse_weight) # - forward() # - backward() # - push_and_update(grad) # - pull(weight) kvstore, update_on_kvstore = _create_sparse_kvstore(config['kvstore']) self._distributed = 'dist' in kvstore.type # raise err if user provides unsupported configs if config['update_on_kvstore'] is False: raise ValueError("Cannot set update_on_kvstore=False when sparse weights " "are present.") elif self._contains_sparse_grad: # For single node training with dense weight and sparse grad, # we prefer update_on_kvstore=False because this is usually faster. # This means we push and pull sparse gradients, and we do not store weight in kvstore. # The training loop is the following: # - forward() # - backward() # - push(grad) # - pull(grad) # - update(grad, weight) # # For multi-node training with dense weight and sparse grad, # only update_on_kvstore=True is supported, due to the fact that # kv.row_sparse_pull(grad) is not implemented. # Therefore, we push sparse gradients and pull dense weights. # The training loop contains: # - forward() # - backward() # - push_and_update(grad) # - pull(weight) arg_arrays = {param.name: param.data(self._contexts[0]) for param in self._params} kvstore, _ = _create_kvstore(config['kvstore'], len(self._contexts), arg_arrays) self._distributed = 'dist' in kvstore.type if kvstore else False update_on_kvstore = self._distributed # raise err if user provides unsupported configs if config['update_on_kvstore'] is not None: if config['update_on_kvstore'] is False and self._distributed: raise ValueError("Cannot set update_on_kvstore=False on dist kvstore " "when sparse gradients are present.") update_on_kvstore = config['update_on_kvstore'] else: # Training with dense weight and dense gradients. # The only unsupported mode is async with update_on_kvstore=False arg_arrays = {param.name: param.data(self._contexts[0]) for param in self._params} kvstore, update_on_kvstore = _create_kvstore(config['kvstore'], len(self._contexts), arg_arrays) self._distributed = 'dist' in kvstore.type if kvstore else False if self._distributed and 'async' in kvstore.type: update_on_kvstore = True # raise err if user provides unsupported configs if config['update_on_kvstore'] is False: raise ValueError("Please set update_on_kvstore=True " "when training in async mode.") if config['update_on_kvstore'] is not None: update_on_kvstore = config['update_on_kvstore'] # set grad compression and optimizers if kvstore: if self._compression_params: kvstore.set_gradient_compression(self._compression_params) if update_on_kvstore: # optimizer preferably needs to be set before init for multiprecision kvstore.set_optimizer(self._optimizer) self._kvstore = kvstore self._update_on_kvstore = update_on_kvstore else: self._kvstore = None self._update_on_kvstore = None self._kv_initialized = True
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. # The training loop is the following: # - row_sparse_pull(sparse_weight) # - forward() # - backward() # - push_and_update(grad) # - pull(weight) kvstore, update_on_kvstore = _create_sparse_kvstore(config['kvstore']) self._distributed = 'dist' in kvstore.type # raise err if user provides unsupported configs if config['update_on_kvstore'] is False: raise ValueError("Cannot set update_on_kvstore=False when sparse weights " "are present.") elif self._contains_sparse_grad: # For single node training with dense weight and sparse grad, # we prefer update_on_kvstore=False because this is usually faster. # This means we push and pull sparse gradients, and we do not store weight in kvstore. # The training loop is the following: # - forward() # - backward() # - push(grad) # - pull(grad) # - update(grad, weight) # # For multi-node training with dense weight and sparse grad, # only update_on_kvstore=True is supported, due to the fact that # kv.row_sparse_pull(grad) is not implemented. # Therefore, we push sparse gradients and pull dense weights. # The training loop contains: # - forward() # - backward() # - push_and_update(grad) # - pull(weight) arg_arrays = {param.name: param.data(self._contexts[0]) for param in self._params} kvstore, _ = _create_kvstore(config['kvstore'], len(self._contexts), arg_arrays) self._distributed = 'dist' in kvstore.type if kvstore else False update_on_kvstore = self._distributed # raise err if user provides unsupported configs if config['update_on_kvstore'] is not None: if config['update_on_kvstore'] is False and self._distributed: raise ValueError("Cannot set update_on_kvstore=False on dist kvstore " "when sparse gradients are present.") update_on_kvstore = config['update_on_kvstore'] else: # Training with dense weight and dense gradients. # The only unsupported mode is async with update_on_kvstore=False arg_arrays = {param.name: param.data(self._contexts[0]) for param in self._params} kvstore, update_on_kvstore = _create_kvstore(config['kvstore'], len(self._contexts), arg_arrays) self._distributed = 'dist' in kvstore.type if kvstore else False if self._distributed and 'async' in kvstore.type: update_on_kvstore = True # raise err if user provides unsupported configs if config['update_on_kvstore'] is False: raise ValueError("Please set update_on_kvstore=True " "when training in async mode.") if config['update_on_kvstore'] is not None: update_on_kvstore = config['update_on_kvstore'] # set grad compression and optimizers if kvstore: if self._compression_params: kvstore.set_gradient_compression(self._compression_params) if update_on_kvstore: # optimizer preferably needs to be set before init for multiprecision kvstore.set_optimizer(self._optimizer) self._kvstore = kvstore self._update_on_kvstore = update_on_kvstore else: self._kvstore = None self._update_on_kvstore = None self._kv_initialized = True
[ "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 weight must be updated on kvstore.", "# The training loop is the following:", "# - row_sparse_pull(sparse_weight)", "# - forward()", "# - backward()", "# - push_and_update(grad)", "# - pull(weight)", "kvstore", ",", "update_on_kvstore", "=", "_create_sparse_kvstore", "(", "config", "[", "'kvstore'", "]", ")", "self", ".", "_distributed", "=", "'dist'", "in", "kvstore", ".", "type", "# raise err if user provides unsupported configs", "if", "config", "[", "'update_on_kvstore'", "]", "is", "False", ":", "raise", "ValueError", "(", "\"Cannot set update_on_kvstore=False when sparse weights \"", "\"are present.\"", ")", "elif", "self", ".", "_contains_sparse_grad", ":", "# For single node training with dense weight and sparse grad,", "# we prefer update_on_kvstore=False because this is usually faster.", "# This means we push and pull sparse gradients, and we do not store weight in kvstore.", "# The training loop is the following:", "# - forward()", "# - backward()", "# - push(grad)", "# - pull(grad)", "# - update(grad, weight)", "#", "# For multi-node training with dense weight and sparse grad,", "# only update_on_kvstore=True is supported, due to the fact that", "# kv.row_sparse_pull(grad) is not implemented.", "# Therefore, we push sparse gradients and pull dense weights.", "# The training loop contains:", "# - forward()", "# - backward()", "# - push_and_update(grad)", "# - pull(weight)", "arg_arrays", "=", "{", "param", ".", "name", ":", "param", ".", "data", "(", "self", ".", "_contexts", "[", "0", "]", ")", "for", "param", "in", "self", ".", "_params", "}", "kvstore", ",", "_", "=", "_create_kvstore", "(", "config", "[", "'kvstore'", "]", ",", "len", "(", "self", ".", "_contexts", ")", ",", "arg_arrays", ")", "self", ".", "_distributed", "=", "'dist'", "in", "kvstore", ".", "type", "if", "kvstore", "else", "False", "update_on_kvstore", "=", "self", ".", "_distributed", "# raise err if user provides unsupported configs", "if", "config", "[", "'update_on_kvstore'", "]", "is", "not", "None", ":", "if", "config", "[", "'update_on_kvstore'", "]", "is", "False", "and", "self", ".", "_distributed", ":", "raise", "ValueError", "(", "\"Cannot set update_on_kvstore=False on dist kvstore \"", "\"when sparse gradients are present.\"", ")", "update_on_kvstore", "=", "config", "[", "'update_on_kvstore'", "]", "else", ":", "# Training with dense weight and dense gradients.", "# The only unsupported mode is async with update_on_kvstore=False", "arg_arrays", "=", "{", "param", ".", "name", ":", "param", ".", "data", "(", "self", ".", "_contexts", "[", "0", "]", ")", "for", "param", "in", "self", ".", "_params", "}", "kvstore", ",", "update_on_kvstore", "=", "_create_kvstore", "(", "config", "[", "'kvstore'", "]", ",", "len", "(", "self", ".", "_contexts", ")", ",", "arg_arrays", ")", "self", ".", "_distributed", "=", "'dist'", "in", "kvstore", ".", "type", "if", "kvstore", "else", "False", "if", "self", ".", "_distributed", "and", "'async'", "in", "kvstore", ".", "type", ":", "update_on_kvstore", "=", "True", "# raise err if user provides unsupported configs", "if", "config", "[", "'update_on_kvstore'", "]", "is", "False", ":", "raise", "ValueError", "(", "\"Please set update_on_kvstore=True \"", "\"when training in async mode.\"", ")", "if", "config", "[", "'update_on_kvstore'", "]", "is", "not", "None", ":", "update_on_kvstore", "=", "config", "[", "'update_on_kvstore'", "]", "# set grad compression and optimizers", "if", "kvstore", ":", "if", "self", ".", "_compression_params", ":", "kvstore", ".", "set_gradient_compression", "(", "self", ".", "_compression_params", ")", "if", "update_on_kvstore", ":", "# optimizer preferably needs to be set before init for multiprecision", "kvstore", ".", "set_optimizer", "(", "self", ".", "_optimizer", ")", "self", ".", "_kvstore", "=", "kvstore", "self", ".", "_update_on_kvstore", "=", "update_on_kvstore", "else", ":", "self", ".", "_kvstore", "=", "None", "self", ".", "_update_on_kvstore", "=", "None", "self", ".", "_kv_initialized", "=", "True" ]
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 defined before its learning " "rate is mutated.") else: self._optimizer.set_learning_rate(lr)
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 defined before its learning " "rate is mutated.") else: self._optimizer.set_learning_rate(lr)
[ "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.\"", ")", "else", ":", "self", ".", "_optimizer", ".", "set_learning_rate", "(", "lr", ")" ]
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_initialized: self._init_kvstore() if self._params_to_init: self._init_params() idx = self._param2idx[parameter.name] if full_idx and 'dist' not in self._kvstore.type: assert row_id.size == out.shape[0] self._kvstore.pull(idx, out=out, priority=-idx, ignore_sparse=False) else: self._kvstore.row_sparse_pull(idx, out=out, row_ids=row_id, priority=-idx)
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_initialized: self._init_kvstore() if self._params_to_init: self._init_params() idx = self._param2idx[parameter.name] if full_idx and 'dist' not in self._kvstore.type: assert row_id.size == out.shape[0] self._kvstore.pull(idx, out=out, priority=-idx, ignore_sparse=False) else: self._kvstore.row_sparse_pull(idx, out=out, row_ids=row_id, priority=-idx)
[ "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", "(", ")", "if", "self", ".", "_params_to_init", ":", "self", ".", "_init_params", "(", ")", "idx", "=", "self", ".", "_param2idx", "[", "parameter", ".", "name", "]", "if", "full_idx", "and", "'dist'", "not", "in", "self", ".", "_kvstore", ".", "type", ":", "assert", "row_id", ".", "size", "==", "out", ".", "shape", "[", "0", "]", "self", ".", "_kvstore", ".", "pull", "(", "idx", ",", "out", "=", "out", ",", "priority", "=", "-", "idx", ",", "ignore_sparse", "=", "False", ")", "else", ":", "self", ".", "_kvstore", ".", "row_sparse_pull", "(", "idx", ",", "out", "=", "out", ",", "row_ids", "=", "row_id", ",", "priority", "=", "-", "idx", ")" ]
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 `allreduce_grads()` and then `update()`. However, if you need to get the reduced gradients to perform certain transformation, such as in gradient clipping, then you may want to manually call `allreduce_grads()` and `update()` separately. """ if not self._kv_initialized: self._init_kvstore() if self._params_to_init: self._init_params() assert not (self._kvstore and self._update_on_kvstore), \ 'allreduce_grads() when parameters are updated on kvstore ' \ 'is not supported. Try setting `update_on_kvstore` ' \ 'to False when creating trainer.' self._allreduce_grads()
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 `allreduce_grads()` and then `update()`. However, if you need to get the reduced gradients to perform certain transformation, such as in gradient clipping, then you may want to manually call `allreduce_grads()` and `update()` separately. """ if not self._kv_initialized: self._init_kvstore() if self._params_to_init: self._init_params() assert not (self._kvstore and self._update_on_kvstore), \ 'allreduce_grads() when parameters are updated on kvstore ' \ 'is not supported. Try setting `update_on_kvstore` ' \ 'to False when creating trainer.' self._allreduce_grads()
[ "def", "allreduce_grads", "(", "self", ")", ":", "if", "not", "self", ".", "_kv_initialized", ":", "self", ".", "_init_kvstore", "(", ")", "if", "self", ".", "_params_to_init", ":", "self", ".", "_init_params", "(", ")", "assert", "not", "(", "self", ".", "_kvstore", "and", "self", ".", "_update_on_kvstore", ")", ",", "'allreduce_grads() when parameters are updated on kvstore '", "'is not supported. Try setting `update_on_kvstore` '", "'to False when creating trainer.'", "self", ".", "_allreduce_grads", "(", ")" ]
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()`. However, if you need to get the reduced gradients to perform certain transformation, such as in gradient clipping, then you may want to manually call `allreduce_grads()` and `update()` separately.
[ "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 `allreduce_grads()` and then `update()`. However, if you need to get the reduced gradients to perform certain transformation, such as in gradient clipping, then you may want to manually call `allreduce_grads()` and `update()` separately. Parameters ---------- batch_size : int Batch size of data processed. Gradient will be normalized by `1/batch_size`. Set this to 1 if you normalized loss manually with `loss = mean(loss)`. ignore_stale_grad : bool, optional, default=False If true, ignores Parameters with stale gradient (gradient that has not been updated by `backward` after last step) and skip update. """ if not self._kv_initialized: self._init_kvstore() if self._params_to_init: self._init_params() assert not (self._kvstore and self._update_on_kvstore), \ 'update() when parameters are updated on kvstore ' \ 'is not supported. Try setting `update_on_kvstore` ' \ 'to False when creating trainer.' self._check_and_rescale_grad(self._scale / batch_size) self._update(ignore_stale_grad)
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 `allreduce_grads()` and then `update()`. However, if you need to get the reduced gradients to perform certain transformation, such as in gradient clipping, then you may want to manually call `allreduce_grads()` and `update()` separately. Parameters ---------- batch_size : int Batch size of data processed. Gradient will be normalized by `1/batch_size`. Set this to 1 if you normalized loss manually with `loss = mean(loss)`. ignore_stale_grad : bool, optional, default=False If true, ignores Parameters with stale gradient (gradient that has not been updated by `backward` after last step) and skip update. """ if not self._kv_initialized: self._init_kvstore() if self._params_to_init: self._init_params() assert not (self._kvstore and self._update_on_kvstore), \ 'update() when parameters are updated on kvstore ' \ 'is not supported. Try setting `update_on_kvstore` ' \ 'to False when creating trainer.' self._check_and_rescale_grad(self._scale / batch_size) self._update(ignore_stale_grad)
[ "def", "update", "(", "self", ",", "batch_size", ",", "ignore_stale_grad", "=", "False", ")", ":", "if", "not", "self", ".", "_kv_initialized", ":", "self", ".", "_init_kvstore", "(", ")", "if", "self", ".", "_params_to_init", ":", "self", ".", "_init_params", "(", ")", "assert", "not", "(", "self", ".", "_kvstore", "and", "self", ".", "_update_on_kvstore", ")", ",", "'update() when parameters are updated on kvstore '", "'is not supported. Try setting `update_on_kvstore` '", "'to False when creating trainer.'", "self", ".", "_check_and_rescale_grad", "(", "self", ".", "_scale", "/", "batch_size", ")", "self", ".", "_update", "(", "ignore_stale_grad", ")" ]
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 to get the reduced gradients to perform certain transformation, such as in gradient clipping, then you may want to manually call `allreduce_grads()` and `update()` separately. Parameters ---------- batch_size : int Batch size of data processed. Gradient will be normalized by `1/batch_size`. Set this to 1 if you normalized loss manually with `loss = mean(loss)`. ignore_stale_grad : bool, optional, default=False If true, ignores Parameters with stale gradient (gradient that has not been updated by `backward` after last step) and skip update.
[ "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_sample = 0 with open(DATA_PATH) as f: for line in f: if (random.random() < P): num_non_zero += len(line.split(" ")) - 1 num_sample += 1 density.append(num_non_zero * 1.0 / (feature_size * num_sample)) return sum(density) / len(density)
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_sample = 0 with open(DATA_PATH) as f: for line in f: if (random.random() < P): num_non_zero += len(line.split(" ")) - 1 num_sample += 1 density.append(num_non_zero * 1.0 / (feature_size * num_sample)) return sum(density) / len(density)
[ "def", "estimate_density", "(", "DATA_PATH", ",", "feature_size", ")", ":", "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_sample", "=", "0", "with", "open", "(", "DATA_PATH", ")", "as", "f", ":", "for", "line", "in", "f", ":", "if", "(", "random", ".", "random", "(", ")", "<", "P", ")", ":", "num_non_zero", "+=", "len", "(", "line", ".", "split", "(", "\" \"", ")", ")", "-", "1", "num_sample", "+=", "1", "density", ".", "append", "(", "num_non_zero", "*", "1.0", "/", "(", "feature_size", "*", "num_sample", ")", ")", "return", "sum", "(", "density", ")", "/", "len", "(", "density", ")" ]
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_TASK_ID'] = str(taskid) env['DMLC_ROLE'] = role env['DMLC_JOB_CLUSTER'] = 'local' ntrial = 0 while True: if os.name == 'nt': env['DMLC_NUM_ATTEMPT'] = str(ntrial) ret = subprocess.call(cmd, shell=True, env=env) if ret != 0: ntrial += 1 continue else: bash = cmd ret = subprocess.call(bash, shell=True, executable='bash', env=env) if ret == 0: logging.debug('Thread %d exit with 0', taskid) return else: if os.name == 'nt': sys.exit(-1) else: raise RuntimeError('Get nonzero return code=%d' % ret)
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_TASK_ID'] = str(taskid) env['DMLC_ROLE'] = role env['DMLC_JOB_CLUSTER'] = 'local' ntrial = 0 while True: if os.name == 'nt': env['DMLC_NUM_ATTEMPT'] = str(ntrial) ret = subprocess.call(cmd, shell=True, env=env) if ret != 0: ntrial += 1 continue else: bash = cmd ret = subprocess.call(bash, shell=True, executable='bash', env=env) if ret == 0: logging.debug('Thread %d exit with 0', taskid) return else: if os.name == 'nt': sys.exit(-1) else: raise RuntimeError('Get nonzero return code=%d' % ret)
[ "def", "exec_cmd", "(", "cmd", ",", "role", ",", "taskid", ",", "pass_env", ")", ":", "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_TASK_ID'", "]", "=", "str", "(", "taskid", ")", "env", "[", "'DMLC_ROLE'", "]", "=", "role", "env", "[", "'DMLC_JOB_CLUSTER'", "]", "=", "'local'", "ntrial", "=", "0", "while", "True", ":", "if", "os", ".", "name", "==", "'nt'", ":", "env", "[", "'DMLC_NUM_ATTEMPT'", "]", "=", "str", "(", "ntrial", ")", "ret", "=", "subprocess", ".", "call", "(", "cmd", ",", "shell", "=", "True", ",", "env", "=", "env", ")", "if", "ret", "!=", "0", ":", "ntrial", "+=", "1", "continue", "else", ":", "bash", "=", "cmd", "ret", "=", "subprocess", ".", "call", "(", "bash", ",", "shell", "=", "True", ",", "executable", "=", "'bash'", ",", "env", "=", "env", ")", "if", "ret", "==", "0", ":", "logging", ".", "debug", "(", "'Thread %d exit with 0'", ",", "taskid", ")", "return", "else", ":", "if", "os", ".", "name", "==", "'nt'", ":", "sys", ".", "exit", "(", "-", "1", ")", "else", ":", "raise", "RuntimeError", "(", "'Get nonzero return code=%d'", "%", "ret", ")" ]
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 parameters in input Parameters ---------- nworker: number of slave process to start up nserver: number of server nodes to start up envs: enviroment variables to be added to the starting programs """ procs = {} for i, gpu in enumerate(gpus): for j in range(args.num_threads): procs[i] = Thread(target=exec_cmd, args=(args.command + ['--gpus=%s'%gpu], 'worker', i*args.num_threads+j, envs)) procs[i].setDaemon(True) procs[i].start() for i in range(len(gpus)*args.num_threads, len(gpus)*args.num_threads + nserver): procs[i] = Thread(target=exec_cmd, args=(args.command, 'server', i, envs)) procs[i].setDaemon(True) procs[i].start() # call submit, with nslave, the commands to run each job and submit function tracker.submit(args.num_threads*len(gpus), args.num_servers, fun_submit=mthread_submit, pscmd=(' '.join(args.command)))
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 parameters in input Parameters ---------- nworker: number of slave process to start up nserver: number of server nodes to start up envs: enviroment variables to be added to the starting programs """ procs = {} for i, gpu in enumerate(gpus): for j in range(args.num_threads): procs[i] = Thread(target=exec_cmd, args=(args.command + ['--gpus=%s'%gpu], 'worker', i*args.num_threads+j, envs)) procs[i].setDaemon(True) procs[i].start() for i in range(len(gpus)*args.num_threads, len(gpus)*args.num_threads + nserver): procs[i] = Thread(target=exec_cmd, args=(args.command, 'server', i, envs)) procs[i].setDaemon(True) procs[i].start() # call submit, with nslave, the commands to run each job and submit function tracker.submit(args.num_threads*len(gpus), args.num_servers, fun_submit=mthread_submit, pscmd=(' '.join(args.command)))
[ "def", "submit", "(", "args", ")", ":", "gpus", "=", "args", ".", "gpus", ".", "strip", "(", ")", ".", "split", "(", "','", ")", "def", "mthread_submit", "(", "nworker", ",", "nserver", ",", "envs", ")", ":", "\"\"\"\n customized submit script, that submit nslave jobs, each must contain args as parameter\n note this can be a lambda function containing additional parameters in input\n\n Parameters\n ----------\n nworker: number of slave process to start up\n nserver: number of server nodes to start up\n envs: enviroment variables to be added to the starting programs\n \"\"\"", "procs", "=", "{", "}", "for", "i", ",", "gpu", "in", "enumerate", "(", "gpus", ")", ":", "for", "j", "in", "range", "(", "args", ".", "num_threads", ")", ":", "procs", "[", "i", "]", "=", "Thread", "(", "target", "=", "exec_cmd", ",", "args", "=", "(", "args", ".", "command", "+", "[", "'--gpus=%s'", "%", "gpu", "]", ",", "'worker'", ",", "i", "*", "args", ".", "num_threads", "+", "j", ",", "envs", ")", ")", "procs", "[", "i", "]", ".", "setDaemon", "(", "True", ")", "procs", "[", "i", "]", ".", "start", "(", ")", "for", "i", "in", "range", "(", "len", "(", "gpus", ")", "*", "args", ".", "num_threads", ",", "len", "(", "gpus", ")", "*", "args", ".", "num_threads", "+", "nserver", ")", ":", "procs", "[", "i", "]", "=", "Thread", "(", "target", "=", "exec_cmd", ",", "args", "=", "(", "args", ".", "command", ",", "'server'", ",", "i", ",", "envs", ")", ")", "procs", "[", "i", "]", ".", "setDaemon", "(", "True", ")", "procs", "[", "i", "]", ".", "start", "(", ")", "# call submit, with nslave, the commands to run each job and submit function", "tracker", ".", "submit", "(", "args", ".", "num_threads", "*", "len", "(", "gpus", ")", ",", "args", ".", "num_servers", ",", "fun_submit", "=", "mthread_submit", ",", "pscmd", "=", "(", "' '", ".", "join", "(", "args", ".", "command", ")", ")", ")" ]
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", "ret" ]
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 = [] with open(filename, 'r') as f: num_samples = 0 for line in f: tks = line.strip().split('::') if len(tks) != 4: continue num_samples += 1 user.append((tks[0])) item.append((tks[1])) score.append((tks[2])) # convert to ndarrays user = mx.nd.array(user, dtype='int32') item = mx.nd.array(item) score = mx.nd.array(score) # prepare data iters data_train = {'user': user, 'item': item} label_train = {'score': score} iter_train = mx.io.NDArrayIter(data=data_train,label=label_train, batch_size=batch_size, shuffle=True) return mx.io.PrefetchingIter(iter_train)
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 = [] with open(filename, 'r') as f: num_samples = 0 for line in f: tks = line.strip().split('::') if len(tks) != 4: continue num_samples += 1 user.append((tks[0])) item.append((tks[1])) score.append((tks[2])) # convert to ndarrays user = mx.nd.array(user, dtype='int32') item = mx.nd.array(item) score = mx.nd.array(score) # prepare data iters data_train = {'user': user, 'item': item} label_train = {'score': score} iter_train = mx.io.NDArrayIter(data=data_train,label=label_train, batch_size=batch_size, shuffle=True) return mx.io.PrefetchingIter(iter_train)
[ "def", "get_movielens_iter", "(", "filename", ",", "batch_size", ")", ":", "logging", ".", "info", "(", "\"Preparing data iterators for \"", "+", "filename", "+", "\" ... \"", ")", "user", "=", "[", "]", "item", "=", "[", "]", "score", "=", "[", "]", "with", "open", "(", "filename", ",", "'r'", ")", "as", "f", ":", "num_samples", "=", "0", "for", "line", "in", "f", ":", "tks", "=", "line", ".", "strip", "(", ")", ".", "split", "(", "'::'", ")", "if", "len", "(", "tks", ")", "!=", "4", ":", "continue", "num_samples", "+=", "1", "user", ".", "append", "(", "(", "tks", "[", "0", "]", ")", ")", "item", ".", "append", "(", "(", "tks", "[", "1", "]", ")", ")", "score", ".", "append", "(", "(", "tks", "[", "2", "]", ")", ")", "# convert to ndarrays", "user", "=", "mx", ".", "nd", ".", "array", "(", "user", ",", "dtype", "=", "'int32'", ")", "item", "=", "mx", ".", "nd", ".", "array", "(", "item", ")", "score", "=", "mx", ".", "nd", ".", "array", "(", "score", ")", "# prepare data iters", "data_train", "=", "{", "'user'", ":", "user", ",", "'item'", ":", "item", "}", "label_train", "=", "{", "'score'", ":", "score", "}", "iter_train", "=", "mx", ".", "io", ".", "NDArrayIter", "(", "data", "=", "data_train", ",", "label", "=", "label_train", ",", "batch_size", "=", "batch_size", ",", "shuffle", "=", "True", ")", "return", "mx", ".", "io", ".", "PrefetchingIter", "(", "iter_train", ")" ]
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 image in (width, height, channels) with BGR color channel order """ hdl = NDArrayHandle() check_call(_LIB.MXCVImdecode(ctypes.c_char_p(str_img), mx_uint(len(str_img)), flag, ctypes.byref(hdl))) return mx.nd.NDArray(hdl)
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 image in (width, height, channels) with BGR color channel order """ hdl = NDArrayHandle() check_call(_LIB.MXCVImdecode(ctypes.c_char_p(str_img), mx_uint(len(str_img)), flag, ctypes.byref(hdl))) return mx.nd.NDArray(hdl)
[ "def", "imdecode", "(", "str_img", ",", "flag", "=", "1", ")", ":", "hdl", "=", "NDArrayHandle", "(", ")", "check_call", "(", "_LIB", ".", "MXCVImdecode", "(", "ctypes", ".", "c_char_p", "(", "str_img", ")", ",", "mx_uint", "(", "len", "(", "str_img", ")", ")", ",", "flag", ",", "ctypes", ".", "byref", "(", "hdl", ")", ")", ")", "return", "mx", ".", "nd", ".", "NDArray", "(", "hdl", ")" ]
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) with BGR color channel order
[ "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 same as interpolation for cv2.imresize Returns ------- img : NDArray resized image """ hdl = NDArrayHandle() check_call(_LIB.MXCVResize(src.handle, mx_uint(size[0]), mx_uint(size[1]), interpolation, ctypes.byref(hdl))) return mx.nd.NDArray(hdl)
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 same as interpolation for cv2.imresize Returns ------- img : NDArray resized image """ hdl = NDArrayHandle() check_call(_LIB.MXCVResize(src.handle, mx_uint(size[0]), mx_uint(size[1]), interpolation, ctypes.byref(hdl))) return mx.nd.NDArray(hdl)
[ "def", "resize", "(", "src", ",", "size", ",", "interpolation", "=", "cv2", ".", "INTER_LINEAR", ")", ":", "hdl", "=", "NDArrayHandle", "(", ")", "check_call", "(", "_LIB", ".", "MXCVResize", "(", "src", ".", "handle", ",", "mx_uint", "(", "size", "[", "0", "]", ")", ",", "mx_uint", "(", "size", "[", "1", "]", ")", ",", "interpolation", ",", "ctypes", ".", "byref", "(", "hdl", ")", ")", ")", "return", "mx", ".", "nd", ".", "NDArray", "(", "hdl", ")" ]
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 ------- img : NDArray resized image
[ "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 Returns ------- img : NDArray padded image """ hdl = NDArrayHandle() check_call(_LIB.MXCVcopyMakeBorder(src.handle, ctypes.c_int(top), ctypes.c_int(bot), ctypes.c_int(left), ctypes.c_int(right), ctypes.c_int(border_type), ctypes.c_double(value), ctypes.byref(hdl))) return mx.nd.NDArray(hdl)
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 Returns ------- img : NDArray padded image """ hdl = NDArrayHandle() check_call(_LIB.MXCVcopyMakeBorder(src.handle, ctypes.c_int(top), ctypes.c_int(bot), ctypes.c_int(left), ctypes.c_int(right), ctypes.c_int(border_type), ctypes.c_double(value), ctypes.byref(hdl))) return mx.nd.NDArray(hdl)
[ "def", "copyMakeBorder", "(", "src", ",", "top", ",", "bot", ",", "left", ",", "right", ",", "border_type", "=", "cv2", ".", "BORDER_CONSTANT", ",", "value", "=", "0", ")", ":", "hdl", "=", "NDArrayHandle", "(", ")", "check_call", "(", "_LIB", ".", "MXCVcopyMakeBorder", "(", "src", ".", "handle", ",", "ctypes", ".", "c_int", "(", "top", ")", ",", "ctypes", ".", "c_int", "(", "bot", ")", ",", "ctypes", ".", "c_int", "(", "left", ")", ",", "ctypes", ".", "c_int", "(", "right", ")", ",", "ctypes", ".", "c_int", "(", "border_type", ")", ",", "ctypes", ".", "c_double", "(", "value", ")", ",", "ctypes", ".", "byref", "(", "hdl", ")", ")", ")", "return", "mx", ".", "nd", ".", "NDArray", "(", "hdl", ")" ]
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) return out, (x0, y0, new_w, new_h)
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) return out, (x0, y0, new_w, new_h)
[ "def", "random_crop", "(", "src", ",", "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", ")", "return", "out", ",", "(", "x0", ",", "y0", ",", "new_w", ",", "new_h", ")" ]
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 = int(new_area*new_ratio) new_h = int(new_area/new_ratio) if random.uniform(0., 1.) < 0.5: new_w, new_h = new_h, new_w if new_w > w or new_h > h: continue 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) return out, (x0, y0, new_w, new_h) return random_crop(src, size)
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 = int(new_area*new_ratio) new_h = int(new_area/new_ratio) if random.uniform(0., 1.) < 0.5: new_w, new_h = new_h, new_w if new_w > w or new_h > h: continue 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) return out, (x0, y0, new_w, new_h) return random_crop(src, size)
[ "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", "for", "_", "in", "range", "(", "10", ")", ":", "new_area", "=", "random", ".", "uniform", "(", "min_area", ",", "1.0", ")", "*", "area", "new_ratio", "=", "random", ".", "uniform", "(", "*", "ratio", ")", "new_w", "=", "int", "(", "new_area", "*", "new_ratio", ")", "new_h", "=", "int", "(", "new_area", "/", "new_ratio", ")", "if", "random", ".", "uniform", "(", "0.", ",", "1.", ")", "<", "0.5", ":", "new_w", ",", "new_h", "=", "new_h", ",", "new_w", "if", "new_w", ">", "w", "or", "new_h", ">", "h", ":", "continue", "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", ")", "return", "out", ",", "(", "x0", ",", "y0", ",", "new_w", ",", "new_h", ")", "return", "random_crop", "(", "src", ",", "size", ")" ]
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() img = imdecode(str_img, 1) img, _ = random_crop(img, self.size) batch[i - self.cur] = img batch = mx.nd.transpose(batch, axes=(0, 3, 1, 2)) ret = mx.io.DataBatch(data=[batch], label=[], pad=self.batch_size-(i-self.cur), index=None) self.cur = i return ret
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() img = imdecode(str_img, 1) img, _ = random_crop(img, self.size) batch[i - self.cur] = img batch = mx.nd.transpose(batch, axes=(0, 3, 1, 2)) ret = mx.io.DataBatch(data=[batch], label=[], pad=self.batch_size-(i-self.cur), index=None) self.cur = i return ret
[ "def", "next", "(", "self", ")", ":", "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", "(", ")", "img", "=", "imdecode", "(", "str_img", ",", "1", ")", "img", ",", "_", "=", "random_crop", "(", "img", ",", "self", ".", "size", ")", "batch", "[", "i", "-", "self", ".", "cur", "]", "=", "img", "batch", "=", "mx", ".", "nd", ".", "transpose", "(", "batch", ",", "axes", "=", "(", "0", ",", "3", ",", "1", ",", "2", ")", ")", "ret", "=", "mx", ".", "io", ".", "DataBatch", "(", "data", "=", "[", "batch", "]", ",", "label", "=", "[", "]", ",", "pad", "=", "self", ".", "batch_size", "-", "(", "i", "-", "self", ".", "cur", ")", ",", "index", "=", "None", ")", "self", ".", "cur", "=", "i", "return", "ret" ]
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("Shape of labels {} does not match shape of " "predictions {}".format(label_shape, pred_shape))
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("Shape of labels {} does not match shape of " "predictions {}".format(label_shape, pred_shape))
[ "def", "check_label_shapes", "(", "labels", ",", "preds", ",", "shape", "=", "0", ")", ":", "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", "(", "\"Shape of labels {} does not match shape of \"", "\"predictions {}\"", ".", "format", "(", "label_shape", ",", "pred_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 ------- sym_block : :class:`~mxnet.gluon.SymbolBlock` A SymbolBlock object representing the given model file. Notes ----- This method is available when you ``import mxnet.contrib.onnx`` """ graph = GraphProto() try: import onnx except ImportError: raise ImportError("Onnx and protobuf need to be installed. Instructions to" + " install - https://github.com/onnx/onnx#installation") model_proto = onnx.load_model(model_file) net = graph.graph_to_gluon(model_proto.graph, ctx) return net
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 ------- sym_block : :class:`~mxnet.gluon.SymbolBlock` A SymbolBlock object representing the given model file. Notes ----- This method is available when you ``import mxnet.contrib.onnx`` """ graph = GraphProto() try: import onnx except ImportError: raise ImportError("Onnx and protobuf need to be installed. Instructions to" + " install - https://github.com/onnx/onnx#installation") model_proto = onnx.load_model(model_file) net = graph.graph_to_gluon(model_proto.graph, ctx) return net
[ "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\"", "+", "\" install - https://github.com/onnx/onnx#installation\"", ")", "model_proto", "=", "onnx", ".", "load_model", "(", "model_file", ")", "net", "=", "graph", ".", "graph_to_gluon", "(", "model_proto", ".", "graph", ",", "ctx", ")", "return", "net" ]
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.SymbolBlock` A SymbolBlock object representing the given model file. Notes ----- This method is available when you ``import mxnet.contrib.onnx``
[ "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 = models.get_model(model, **kwargs) if opt.resume: net.load_parameters(opt.resume) elif not opt.use_pretrained: if model in ['alexnet']: net.initialize(mx.init.Normal()) else: net.initialize(mx.init.Xavier(magnitude=2)) net.cast(opt.dtype) return net
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 = models.get_model(model, **kwargs) if opt.resume: net.load_parameters(opt.resume) elif not opt.use_pretrained: if model in ['alexnet']: net.initialize(mx.init.Normal()) else: net.initialize(mx.init.Xavier(magnitude=2)) net.cast(opt.dtype) return net
[ "def", "get_model", "(", "model", ",", "ctx", ",", "opt", ")", ":", "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", "=", "models", ".", "get_model", "(", "model", ",", "*", "*", "kwargs", ")", "if", "opt", ".", "resume", ":", "net", ".", "load_parameters", "(", "opt", ".", "resume", ")", "elif", "not", "opt", ".", "use_pretrained", ":", "if", "model", "in", "[", "'alexnet'", "]", ":", "net", ".", "initialize", "(", "mx", ".", "init", ".", "Normal", "(", ")", ")", "else", ":", "net", ".", "initialize", "(", "mx", ".", "init", ".", "Xavier", "(", "magnitude", "=", "2", ")", ")", "net", ".", "cast", "(", "opt", ".", "dtype", ")", "return", "net" ]
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_data, val_data = get_cifar10_iterator(batch_size, (3, 32, 32), num_parts=kv.num_workers, part_index=kv.rank) elif dataset == 'imagenet': shape_dim = 299 if model_name == 'inceptionv3' else 224 if not opt.data_dir: raise ValueError('Dir containing raw images in train/val is required for imagenet.' 'Please specify "--data-dir"') train_data, val_data = get_imagenet_iterator(opt.data_dir, batch_size, opt.num_workers, shape_dim, opt.dtype) elif dataset == 'caltech101': train_data, val_data = get_caltech101_iterator(batch_size, opt.num_workers, opt.dtype) elif dataset == 'dummy': shape_dim = 299 if model_name == 'inceptionv3' else 224 train_data, val_data = dummy_iterator(batch_size, (3, shape_dim, shape_dim)) return train_data, val_data
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_data, val_data = get_cifar10_iterator(batch_size, (3, 32, 32), num_parts=kv.num_workers, part_index=kv.rank) elif dataset == 'imagenet': shape_dim = 299 if model_name == 'inceptionv3' else 224 if not opt.data_dir: raise ValueError('Dir containing raw images in train/val is required for imagenet.' 'Please specify "--data-dir"') train_data, val_data = get_imagenet_iterator(opt.data_dir, batch_size, opt.num_workers, shape_dim, opt.dtype) elif dataset == 'caltech101': train_data, val_data = get_caltech101_iterator(batch_size, opt.num_workers, opt.dtype) elif dataset == 'dummy': shape_dim = 299 if model_name == 'inceptionv3' else 224 train_data, val_data = dummy_iterator(batch_size, (3, shape_dim, shape_dim)) return train_data, val_data
[ "def", "get_data_iters", "(", "dataset", ",", "batch_size", ",", "opt", ")", ":", "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_data", ",", "val_data", "=", "get_cifar10_iterator", "(", "batch_size", ",", "(", "3", ",", "32", ",", "32", ")", ",", "num_parts", "=", "kv", ".", "num_workers", ",", "part_index", "=", "kv", ".", "rank", ")", "elif", "dataset", "==", "'imagenet'", ":", "shape_dim", "=", "299", "if", "model_name", "==", "'inceptionv3'", "else", "224", "if", "not", "opt", ".", "data_dir", ":", "raise", "ValueError", "(", "'Dir containing raw images in train/val is required for imagenet.'", "'Please specify \"--data-dir\"'", ")", "train_data", ",", "val_data", "=", "get_imagenet_iterator", "(", "opt", ".", "data_dir", ",", "batch_size", ",", "opt", ".", "num_workers", ",", "shape_dim", ",", "opt", ".", "dtype", ")", "elif", "dataset", "==", "'caltech101'", ":", "train_data", ",", "val_data", "=", "get_caltech101_iterator", "(", "batch_size", ",", "opt", ".", "num_workers", ",", "opt", ".", "dtype", ")", "elif", "dataset", "==", "'dummy'", ":", "shape_dim", "=", "299", "if", "model_name", "==", "'inceptionv3'", "else", "224", "train_data", ",", "val_data", "=", "dummy_iterator", "(", "batch_size", ",", "(", "3", ",", "shape_dim", ",", "shape_dim", ")", ")", "return", "train_data", ",", "val_data" ]
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", ")", ")", ")", "trainer", ".", "set_learning_rate", "(", "new_lr", ")", "return", "trainer" ]
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 number seed. ctx : Context The device context of the generator. The default is "all" which means seeding random number generators of all devices. Notes ----- Random number generators in MXNet are device specific. `mx.random.seed(seed_state)` sets the state of each generator using `seed_state` and the device id. Therefore, random numbers generated from different devices can be different even if they are seeded using the same seed. To produce identical random number sequences independent of the device id, set optional `ctx` argument. This produces the same sequence of random numbers independent of the device id, but the sequence can be different on different kind of devices as MXNet's random number generators for CPU and GPU use different algorithms. Example ------- >>> print(mx.nd.random.normal(shape=(2,2)).asnumpy()) [[ 1.36481571 -0.62203991] [-1.4962182 -0.08511394]] >>> print(mx.nd.random.normal(shape=(2,2)).asnumpy()) [[ 1.09544981 -0.20014545] [-0.20808885 0.2527658 ]] # Same results on the same device with the same seed >>> mx.random.seed(128) >>> print(mx.nd.random.normal(shape=(2,2)).asnumpy()) [[ 0.47400656 -0.75213492] [ 0.20251541 0.95352972]] >>> mx.random.seed(128) >>> print(mx.nd.random.normal(shape=(2,2)).asnumpy()) [[ 0.47400656 -0.75213492] [ 0.20251541 0.95352972]] # Different results on gpu(0) and gpu(1) with the same seed >>> mx.random.seed(128) >>> print(mx.nd.random.normal(shape=(2,2), ctx=mx.gpu(0)).asnumpy()) [[ 2.5020072 -1.6884501] [-0.7931333 -1.4218881]] >>> mx.random.seed(128) >>> print(mx.nd.random.normal(shape=(2,2), ctx=mx.gpu(1)).asnumpy()) [[ 0.24336822 -1.664805 ] [-1.0223296 1.253198 ]] # Seeding with `ctx` argument produces identical results on gpu(0) and gpu(1) >>> mx.random.seed(128, ctx=mx.gpu(0)) >>> print(mx.nd.random.normal(shape=(2,2), ctx=mx.gpu(0)).asnumpy()) [[ 2.5020072 -1.6884501] [-0.7931333 -1.4218881]] >>> mx.random.seed(128, ctx=mx.gpu(1)) >>> print(mx.nd.random.normal(shape=(2,2), ctx=mx.gpu(1)).asnumpy()) [[ 2.5020072 -1.6884501] [-0.7931333 -1.4218881]] """ if not isinstance(seed_state, integer_types): raise ValueError('seed_state must be int') seed_state = ctypes.c_int(int(seed_state)) if ctx == "all": check_call(_LIB.MXRandomSeed(seed_state)) else: ctx = Context(ctx) check_call(_LIB.MXRandomSeedContext(seed_state, ctx.device_typeid, ctx.device_id))
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 number seed. ctx : Context The device context of the generator. The default is "all" which means seeding random number generators of all devices. Notes ----- Random number generators in MXNet are device specific. `mx.random.seed(seed_state)` sets the state of each generator using `seed_state` and the device id. Therefore, random numbers generated from different devices can be different even if they are seeded using the same seed. To produce identical random number sequences independent of the device id, set optional `ctx` argument. This produces the same sequence of random numbers independent of the device id, but the sequence can be different on different kind of devices as MXNet's random number generators for CPU and GPU use different algorithms. Example ------- >>> print(mx.nd.random.normal(shape=(2,2)).asnumpy()) [[ 1.36481571 -0.62203991] [-1.4962182 -0.08511394]] >>> print(mx.nd.random.normal(shape=(2,2)).asnumpy()) [[ 1.09544981 -0.20014545] [-0.20808885 0.2527658 ]] # Same results on the same device with the same seed >>> mx.random.seed(128) >>> print(mx.nd.random.normal(shape=(2,2)).asnumpy()) [[ 0.47400656 -0.75213492] [ 0.20251541 0.95352972]] >>> mx.random.seed(128) >>> print(mx.nd.random.normal(shape=(2,2)).asnumpy()) [[ 0.47400656 -0.75213492] [ 0.20251541 0.95352972]] # Different results on gpu(0) and gpu(1) with the same seed >>> mx.random.seed(128) >>> print(mx.nd.random.normal(shape=(2,2), ctx=mx.gpu(0)).asnumpy()) [[ 2.5020072 -1.6884501] [-0.7931333 -1.4218881]] >>> mx.random.seed(128) >>> print(mx.nd.random.normal(shape=(2,2), ctx=mx.gpu(1)).asnumpy()) [[ 0.24336822 -1.664805 ] [-1.0223296 1.253198 ]] # Seeding with `ctx` argument produces identical results on gpu(0) and gpu(1) >>> mx.random.seed(128, ctx=mx.gpu(0)) >>> print(mx.nd.random.normal(shape=(2,2), ctx=mx.gpu(0)).asnumpy()) [[ 2.5020072 -1.6884501] [-0.7931333 -1.4218881]] >>> mx.random.seed(128, ctx=mx.gpu(1)) >>> print(mx.nd.random.normal(shape=(2,2), ctx=mx.gpu(1)).asnumpy()) [[ 2.5020072 -1.6884501] [-0.7931333 -1.4218881]] """ if not isinstance(seed_state, integer_types): raise ValueError('seed_state must be int') seed_state = ctypes.c_int(int(seed_state)) if ctx == "all": check_call(_LIB.MXRandomSeed(seed_state)) else: ctx = Context(ctx) check_call(_LIB.MXRandomSeedContext(seed_state, ctx.device_typeid, ctx.device_id))
[ "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", "(", "int", "(", "seed_state", ")", ")", "if", "ctx", "==", "\"all\"", ":", "check_call", "(", "_LIB", ".", "MXRandomSeed", "(", "seed_state", ")", ")", "else", ":", "ctx", "=", "Context", "(", "ctx", ")", "check_call", "(", "_LIB", ".", "MXRandomSeedContext", "(", "seed_state", ",", "ctx", ".", "device_typeid", ",", "ctx", ".", "device_id", ")", ")" ]
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 device context of the generator. The default is "all" which means seeding random number generators of all devices. Notes ----- Random number generators in MXNet are device specific. `mx.random.seed(seed_state)` sets the state of each generator using `seed_state` and the device id. Therefore, random numbers generated from different devices can be different even if they are seeded using the same seed. To produce identical random number sequences independent of the device id, set optional `ctx` argument. This produces the same sequence of random numbers independent of the device id, but the sequence can be different on different kind of devices as MXNet's random number generators for CPU and GPU use different algorithms. Example ------- >>> print(mx.nd.random.normal(shape=(2,2)).asnumpy()) [[ 1.36481571 -0.62203991] [-1.4962182 -0.08511394]] >>> print(mx.nd.random.normal(shape=(2,2)).asnumpy()) [[ 1.09544981 -0.20014545] [-0.20808885 0.2527658 ]] # Same results on the same device with the same seed >>> mx.random.seed(128) >>> print(mx.nd.random.normal(shape=(2,2)).asnumpy()) [[ 0.47400656 -0.75213492] [ 0.20251541 0.95352972]] >>> mx.random.seed(128) >>> print(mx.nd.random.normal(shape=(2,2)).asnumpy()) [[ 0.47400656 -0.75213492] [ 0.20251541 0.95352972]] # Different results on gpu(0) and gpu(1) with the same seed >>> mx.random.seed(128) >>> print(mx.nd.random.normal(shape=(2,2), ctx=mx.gpu(0)).asnumpy()) [[ 2.5020072 -1.6884501] [-0.7931333 -1.4218881]] >>> mx.random.seed(128) >>> print(mx.nd.random.normal(shape=(2,2), ctx=mx.gpu(1)).asnumpy()) [[ 0.24336822 -1.664805 ] [-1.0223296 1.253198 ]] # Seeding with `ctx` argument produces identical results on gpu(0) and gpu(1) >>> mx.random.seed(128, ctx=mx.gpu(0)) >>> print(mx.nd.random.normal(shape=(2,2), ctx=mx.gpu(0)).asnumpy()) [[ 2.5020072 -1.6884501] [-0.7931333 -1.4218881]] >>> mx.random.seed(128, ctx=mx.gpu(1)) >>> print(mx.nd.random.normal(shape=(2,2), ctx=mx.gpu(1)).asnumpy()) [[ 2.5020072 -1.6884501] [-0.7931333 -1.4218881]]
[ "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 - https://github.com/onnx/onnx") new_attrs = translation_utils._remove_attributes(attrs, ['seed']) new_attrs['dtype'] = TENSOR_TYPE_TO_NP_TYPE[int(new_attrs.get('dtype', 1))] return 'random_uniform', new_attrs, inputs
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 - https://github.com/onnx/onnx") new_attrs = translation_utils._remove_attributes(attrs, ['seed']) new_attrs['dtype'] = TENSOR_TYPE_TO_NP_TYPE[int(new_attrs.get('dtype', 1))] return 'random_uniform', new_attrs, inputs
[ "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. \"", "\"Instructions to install - https://github.com/onnx/onnx\"", ")", "new_attrs", "=", "translation_utils", ".", "_remove_attributes", "(", "attrs", ",", "[", "'seed'", "]", ")", "new_attrs", "[", "'dtype'", "]", "=", "TENSOR_TYPE_TO_NP_TYPE", "[", "int", "(", "new_attrs", ".", "get", "(", "'dtype'", ",", "1", ")", ")", "]", "return", "'random_uniform'", ",", "new_attrs", ",", "inputs" ]
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 - https://github.com/onnx/onnx") new_attr = translation_utils._remove_attributes(attrs, ['seed']) new_attr = translation_utils._fix_attribute_names(new_attr, {'mean': 'loc'}) new_attr['dtype'] = TENSOR_TYPE_TO_NP_TYPE[int(new_attr.get('dtype', 1))] return 'random_normal', new_attr, inputs
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 - https://github.com/onnx/onnx") new_attr = translation_utils._remove_attributes(attrs, ['seed']) new_attr = translation_utils._fix_attribute_names(new_attr, {'mean': 'loc'}) new_attr['dtype'] = TENSOR_TYPE_TO_NP_TYPE[int(new_attr.get('dtype', 1))] return 'random_normal', new_attr, inputs
[ "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. \"", "\"Instructions to install - https://github.com/onnx/onnx\"", ")", "new_attr", "=", "translation_utils", ".", "_remove_attributes", "(", "attrs", ",", "[", "'seed'", "]", ")", "new_attr", "=", "translation_utils", ".", "_fix_attribute_names", "(", "new_attr", ",", "{", "'mean'", ":", "'loc'", "}", ")", "new_attr", "[", "'dtype'", "]", "=", "TENSOR_TYPE_TO_NP_TYPE", "[", "int", "(", "new_attr", ".", "get", "(", "'dtype'", ",", "1", ")", ")", "]", "return", "'random_normal'", ",", "new_attr", ",", "inputs" ]
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_axis, proto_obj) return op_value, new_attr, inputs return 'broadcast_add', new_attr, inputs
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_axis, proto_obj) return op_value, new_attr, inputs return 'broadcast_add', new_attr, inputs
[ "def", "add", "(", "attrs", ",", "inputs", ",", "proto_obj", ")", ":", "new_attr", "=", "{", "}", "if", "'broadcast'", "in", "attrs", "and", "attrs", "[", "'broadcast'", "]", "==", "1", ":", "broadcast_axis", "=", "attrs", "[", "'axis'", "]", "op_value", "=", "translation_utils", ".", "_fix_broadcast", "(", "'broadcast_add'", ",", "inputs", ",", "broadcast_axis", ",", "proto_obj", ")", "return", "op_value", ",", "new_attr", ",", "inputs", "return", "'broadcast_add'", ",", "new_attr", ",", "inputs" ]
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", ".", "concat", "(", "*", "concat_input", ",", "dim", "=", "0", ")", "mean_sym", "=", "symbol", ".", "mean", "(", "concat_sym", ",", "axis", "=", "0", ")", "return", "mean_sym", ",", "attrs", ",", "inputs" ]
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 = {'dtype': 'int64'} return 'cast', cast_attrs, argmax_op
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 = {'dtype': 'int64'} return 'cast', cast_attrs, argmax_op
[ "def", "argmax", "(", "attrs", ",", "inputs", ",", "proto_obj", ")", ":", "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", "=", "{", "'dtype'", ":", "'int64'", "}", "return", "'cast'", ",", "cast_attrs", ",", "argmax_op" ]
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_attrs = {'dtype': 'int64'} return 'cast', cast_attrs, argmin_op
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_attrs = {'dtype': 'int64'} return 'cast', cast_attrs, argmin_op
[ "def", "argmin", "(", "attrs", ",", "inputs", ",", "proto_obj", ")", ":", "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_attrs", "=", "{", "'dtype'", ":", "'int64'", "}", "return", "'cast'", ",", "cast_attrs", ",", "argmin_op" ]
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(inputs[0], inputs[1]) for op_input in inputs[2:]: mxnet_op = symbol.maximum(mxnet_op, op_input) else: mxnet_op = symbol.maximum(inputs[0], inputs[0]) return mxnet_op, attrs, inputs
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(inputs[0], inputs[1]) for op_input in inputs[2:]: mxnet_op = symbol.maximum(mxnet_op, op_input) else: mxnet_op = symbol.maximum(inputs[0], inputs[0]) return mxnet_op, attrs, inputs
[ "def", "maximum", "(", "attrs", ",", "inputs", ",", "proto_obj", ")", ":", "if", "len", "(", "inputs", ")", ">", "1", ":", "mxnet_op", "=", "symbol", ".", "maximum", "(", "inputs", "[", "0", "]", ",", "inputs", "[", "1", "]", ")", "for", "op_input", "in", "inputs", "[", "2", ":", "]", ":", "mxnet_op", "=", "symbol", ".", "maximum", "(", "mxnet_op", ",", "op_input", ")", "else", ":", "mxnet_op", "=", "symbol", ".", "maximum", "(", "inputs", "[", "0", "]", ",", "inputs", "[", "0", "]", ")", "return", "mxnet_op", ",", "attrs", ",", "inputs" ]
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", "compare", "two", "symbols", "at", "a", "time" ]
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[0], inputs[1]) for op_input in inputs[2:]: mxnet_op = symbol.minimum(mxnet_op, op_input) else: mxnet_op = symbol.minimum(inputs[0], inputs[0]) return mxnet_op, attrs, 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[0], inputs[1]) for op_input in inputs[2:]: mxnet_op = symbol.minimum(mxnet_op, op_input) else: mxnet_op = symbol.minimum(inputs[0], inputs[0]) return mxnet_op, attrs, 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", ")", ">", "1", ":", "mxnet_op", "=", "symbol", ".", "minimum", "(", "inputs", "[", "0", "]", ",", "inputs", "[", "1", "]", ")", "for", "op_input", "in", "inputs", "[", "2", ":", "]", ":", "mxnet_op", "=", "symbol", ".", "minimum", "(", "mxnet_op", ",", "op_input", ")", "else", ":", "mxnet_op", "=", "symbol", ".", "minimum", "(", "inputs", "[", "0", "]", ",", "inputs", "[", "0", "]", ")", "return", "mxnet_op", ",", "attrs", ",", "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' }) new_attrs['pad_width'] = translation_utils._pad_sequence_fix(new_attrs.get('pad_width')) return 'pad', new_attrs, inputs
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' }) new_attrs['pad_width'] = translation_utils._pad_sequence_fix(new_attrs.get('pad_width')) return 'pad', new_attrs, inputs
[ "def", "pad", "(", "attrs", ",", "inputs", ",", "proto_obj", ")", ":", "new_attrs", "=", "translation_utils", ".", "_fix_attribute_names", "(", "attrs", ",", "{", "'pads'", ":", "'pad_width'", ",", "'value'", ":", "'constant_value'", "}", ")", "new_attrs", "[", "'pad_width'", "]", "=", "translation_utils", ".", "_pad_sequence_fix", "(", "new_attrs", ".", "get", "(", "'pad_width'", ")", ")", "return", "'pad'", ",", "new_attrs", ",", "inputs" ]
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", ".", "get", "(", "'epsilon'", ",", "1e-5", ")", "return", "'InstanceNorm'", ",", "new_attrs", ",", "inputs" ]
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", ":", "new_attrs", "=", "translation_utils", ".", "_add_extra_attributes", "(", "attrs", ",", "{", "'slope'", ":", "0.01", "}", ")", "return", "'LeakyReLU'", ",", "new_attrs", ",", "inputs" ]
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", "'softmax'", ",", "attrs", ",", "inputs" ]
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", ",", "inputs" ]
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', 'pads': 'pad', 'dilations': 'dilate', 'group': 'num_group'}) new_attrs = translation_utils._add_extra_attributes(new_attrs, {'num_group' : 1}) new_attrs = translation_utils._fix_bias('Deconvolution', new_attrs, len(inputs)) new_attrs = translation_utils._fix_channels('Deconvolution', new_attrs, inputs, proto_obj) kernel = new_attrs['kernel'] stride = new_attrs['stride'] if 'stride' in new_attrs else [] padding = new_attrs['pad'] if 'pad' in new_attrs else [] dilations = new_attrs['dilate'] if 'dilate' in new_attrs else [] num_filter = new_attrs['num_filter'] num_group = new_attrs['num_group'] no_bias = new_attrs['no_bias'] if 'no_bias' in new_attrs else False bias = None if no_bias is True else inputs[2] # Unlike ONNX, MXNet's deconvolution operator does not support asymmetric padding, so we first # use 'Pad' operator, which supports asymmetric padding. Then use the deconvolution operator. pad_width = (0, 0, 0, 0) + translation_utils._pad_sequence_fix(padding, kernel_dim=len(kernel)) pad_op = symbol.pad(inputs[0], mode='constant', pad_width=pad_width) deconv_op = symbol.Deconvolution(pad_op, inputs[1], bias, kernel=kernel, stride=stride, dilate=dilations, num_filter=num_filter, num_group=num_group, no_bias=no_bias) return deconv_op, new_attrs, inputs
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', 'pads': 'pad', 'dilations': 'dilate', 'group': 'num_group'}) new_attrs = translation_utils._add_extra_attributes(new_attrs, {'num_group' : 1}) new_attrs = translation_utils._fix_bias('Deconvolution', new_attrs, len(inputs)) new_attrs = translation_utils._fix_channels('Deconvolution', new_attrs, inputs, proto_obj) kernel = new_attrs['kernel'] stride = new_attrs['stride'] if 'stride' in new_attrs else [] padding = new_attrs['pad'] if 'pad' in new_attrs else [] dilations = new_attrs['dilate'] if 'dilate' in new_attrs else [] num_filter = new_attrs['num_filter'] num_group = new_attrs['num_group'] no_bias = new_attrs['no_bias'] if 'no_bias' in new_attrs else False bias = None if no_bias is True else inputs[2] # Unlike ONNX, MXNet's deconvolution operator does not support asymmetric padding, so we first # use 'Pad' operator, which supports asymmetric padding. Then use the deconvolution operator. pad_width = (0, 0, 0, 0) + translation_utils._pad_sequence_fix(padding, kernel_dim=len(kernel)) pad_op = symbol.pad(inputs[0], mode='constant', pad_width=pad_width) deconv_op = symbol.Deconvolution(pad_op, inputs[1], bias, kernel=kernel, stride=stride, dilate=dilations, num_filter=num_filter, num_group=num_group, no_bias=no_bias) return deconv_op, new_attrs, inputs
[ "def", "deconv", "(", "attrs", ",", "inputs", ",", "proto_obj", ")", ":", "new_attrs", "=", "translation_utils", ".", "_fix_attribute_names", "(", "attrs", ",", "{", "'kernel_shape'", ":", "'kernel'", ",", "'strides'", ":", "'stride'", ",", "'pads'", ":", "'pad'", ",", "'dilations'", ":", "'dilate'", ",", "'group'", ":", "'num_group'", "}", ")", "new_attrs", "=", "translation_utils", ".", "_add_extra_attributes", "(", "new_attrs", ",", "{", "'num_group'", ":", "1", "}", ")", "new_attrs", "=", "translation_utils", ".", "_fix_bias", "(", "'Deconvolution'", ",", "new_attrs", ",", "len", "(", "inputs", ")", ")", "new_attrs", "=", "translation_utils", ".", "_fix_channels", "(", "'Deconvolution'", ",", "new_attrs", ",", "inputs", ",", "proto_obj", ")", "kernel", "=", "new_attrs", "[", "'kernel'", "]", "stride", "=", "new_attrs", "[", "'stride'", "]", "if", "'stride'", "in", "new_attrs", "else", "[", "]", "padding", "=", "new_attrs", "[", "'pad'", "]", "if", "'pad'", "in", "new_attrs", "else", "[", "]", "dilations", "=", "new_attrs", "[", "'dilate'", "]", "if", "'dilate'", "in", "new_attrs", "else", "[", "]", "num_filter", "=", "new_attrs", "[", "'num_filter'", "]", "num_group", "=", "new_attrs", "[", "'num_group'", "]", "no_bias", "=", "new_attrs", "[", "'no_bias'", "]", "if", "'no_bias'", "in", "new_attrs", "else", "False", "bias", "=", "None", "if", "no_bias", "is", "True", "else", "inputs", "[", "2", "]", "# Unlike ONNX, MXNet's deconvolution operator does not support asymmetric padding, so we first", "# use 'Pad' operator, which supports asymmetric padding. Then use the deconvolution operator.", "pad_width", "=", "(", "0", ",", "0", ",", "0", ",", "0", ")", "+", "translation_utils", ".", "_pad_sequence_fix", "(", "padding", ",", "kernel_dim", "=", "len", "(", "kernel", ")", ")", "pad_op", "=", "symbol", ".", "pad", "(", "inputs", "[", "0", "]", ",", "mode", "=", "'constant'", ",", "pad_width", "=", "pad_width", ")", "deconv_op", "=", "symbol", ".", "Deconvolution", "(", "pad_op", ",", "inputs", "[", "1", "]", ",", "bias", ",", "kernel", "=", "kernel", ",", "stride", "=", "stride", ",", "dilate", "=", "dilations", ",", "num_filter", "=", "num_filter", ",", "num_group", "=", "num_group", ",", "no_bias", "=", "no_bias", ")", "return", "deconv_op", ",", "new_attrs", ",", "inputs" ]
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), 'pool_type': 'max'}) return 'Pooling', new_attrs, inputs
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), 'pool_type': 'max'}) return 'Pooling', new_attrs, inputs
[ "def", "global_maxpooling", "(", "attrs", ",", "inputs", ",", "proto_obj", ")", ":", "new_attrs", "=", "translation_utils", ".", "_add_extra_attributes", "(", "attrs", ",", "{", "'global_pool'", ":", "True", ",", "'kernel'", ":", "(", "1", ",", "1", ")", ",", "'pool_type'", ":", "'max'", "}", ")", "return", "'Pooling'", ",", "new_attrs", ",", "inputs" ]
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), 'pool_type': 'avg'}) return 'Pooling', new_attrs, inputs
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), 'pool_type': 'avg'}) return 'Pooling', new_attrs, inputs
[ "def", "global_avgpooling", "(", "attrs", ",", "inputs", ",", "proto_obj", ")", ":", "new_attrs", "=", "translation_utils", ".", "_add_extra_attributes", "(", "attrs", ",", "{", "'global_pool'", ":", "True", ",", "'kernel'", ":", "(", "1", ",", "1", ")", ",", "'pool_type'", ":", "'avg'", "}", ")", "return", "'Pooling'", ",", "new_attrs", ",", "inputs" ]
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