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,700
apache/incubator-mxnet
example/bayesian-methods/bdk_demo.py
get_mnist_sym
def get_mnist_sym(output_op=None, num_hidden=400): """Get symbol of mnist""" net = mx.symbol.Variable('data') net = mx.symbol.FullyConnected(data=net, name='mnist_fc1', num_hidden=num_hidden) net = mx.symbol.Activation(data=net, name='mnist_relu1', act_type="relu") net = mx.symbol.FullyConnected(data=net, name='mnist_fc2', num_hidden=num_hidden) net = mx.symbol.Activation(data=net, name='mnist_relu2', act_type="relu") net = mx.symbol.FullyConnected(data=net, name='mnist_fc3', num_hidden=10) if output_op is None: net = mx.symbol.SoftmaxOutput(data=net, name='softmax') else: net = output_op(data=net, name='softmax') return net
python
def get_mnist_sym(output_op=None, num_hidden=400): """Get symbol of mnist""" net = mx.symbol.Variable('data') net = mx.symbol.FullyConnected(data=net, name='mnist_fc1', num_hidden=num_hidden) net = mx.symbol.Activation(data=net, name='mnist_relu1', act_type="relu") net = mx.symbol.FullyConnected(data=net, name='mnist_fc2', num_hidden=num_hidden) net = mx.symbol.Activation(data=net, name='mnist_relu2', act_type="relu") net = mx.symbol.FullyConnected(data=net, name='mnist_fc3', num_hidden=10) if output_op is None: net = mx.symbol.SoftmaxOutput(data=net, name='softmax') else: net = output_op(data=net, name='softmax') return net
[ "def", "get_mnist_sym", "(", "output_op", "=", "None", ",", "num_hidden", "=", "400", ")", ":", "net", "=", "mx", ".", "symbol", ".", "Variable", "(", "'data'", ")", "net", "=", "mx", ".", "symbol", ".", "FullyConnected", "(", "data", "=", "net", ",", "name", "=", "'mnist_fc1'", ",", "num_hidden", "=", "num_hidden", ")", "net", "=", "mx", ".", "symbol", ".", "Activation", "(", "data", "=", "net", ",", "name", "=", "'mnist_relu1'", ",", "act_type", "=", "\"relu\"", ")", "net", "=", "mx", ".", "symbol", ".", "FullyConnected", "(", "data", "=", "net", ",", "name", "=", "'mnist_fc2'", ",", "num_hidden", "=", "num_hidden", ")", "net", "=", "mx", ".", "symbol", ".", "Activation", "(", "data", "=", "net", ",", "name", "=", "'mnist_relu2'", ",", "act_type", "=", "\"relu\"", ")", "net", "=", "mx", ".", "symbol", ".", "FullyConnected", "(", "data", "=", "net", ",", "name", "=", "'mnist_fc3'", ",", "num_hidden", "=", "10", ")", "if", "output_op", "is", "None", ":", "net", "=", "mx", ".", "symbol", ".", "SoftmaxOutput", "(", "data", "=", "net", ",", "name", "=", "'softmax'", ")", "else", ":", "net", "=", "output_op", "(", "data", "=", "net", ",", "name", "=", "'softmax'", ")", "return", "net" ]
Get symbol of mnist
[ "Get", "symbol", "of", "mnist" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/bayesian-methods/bdk_demo.py#L106-L118
23,701
apache/incubator-mxnet
example/bayesian-methods/bdk_demo.py
synthetic_grad
def synthetic_grad(X, theta, sigma1, sigma2, sigmax, rescale_grad=1.0, grad=None): """Get synthetic gradient value""" if grad is None: grad = nd.empty(theta.shape, theta.context) theta1 = theta.asnumpy()[0] theta2 = theta.asnumpy()[1] v1 = sigma1 ** 2 v2 = sigma2 ** 2 vx = sigmax ** 2 denominator = numpy.exp(-(X - theta1) ** 2 / (2 * vx)) + numpy.exp( -(X - theta1 - theta2) ** 2 / (2 * vx)) grad_npy = numpy.zeros(theta.shape) grad_npy[0] = -rescale_grad * ((numpy.exp(-(X - theta1) ** 2 / (2 * vx)) * (X - theta1) / vx + numpy.exp(-(X - theta1 - theta2) ** 2 / (2 * vx)) * (X - theta1 - theta2) / vx) / denominator).sum() + theta1 / v1 grad_npy[1] = -rescale_grad * ((numpy.exp(-(X - theta1 - theta2) ** 2 / (2 * vx)) * (X - theta1 - theta2) / vx) / denominator).sum() + theta2 / v2 grad[:] = grad_npy return grad
python
def synthetic_grad(X, theta, sigma1, sigma2, sigmax, rescale_grad=1.0, grad=None): """Get synthetic gradient value""" if grad is None: grad = nd.empty(theta.shape, theta.context) theta1 = theta.asnumpy()[0] theta2 = theta.asnumpy()[1] v1 = sigma1 ** 2 v2 = sigma2 ** 2 vx = sigmax ** 2 denominator = numpy.exp(-(X - theta1) ** 2 / (2 * vx)) + numpy.exp( -(X - theta1 - theta2) ** 2 / (2 * vx)) grad_npy = numpy.zeros(theta.shape) grad_npy[0] = -rescale_grad * ((numpy.exp(-(X - theta1) ** 2 / (2 * vx)) * (X - theta1) / vx + numpy.exp(-(X - theta1 - theta2) ** 2 / (2 * vx)) * (X - theta1 - theta2) / vx) / denominator).sum() + theta1 / v1 grad_npy[1] = -rescale_grad * ((numpy.exp(-(X - theta1 - theta2) ** 2 / (2 * vx)) * (X - theta1 - theta2) / vx) / denominator).sum() + theta2 / v2 grad[:] = grad_npy return grad
[ "def", "synthetic_grad", "(", "X", ",", "theta", ",", "sigma1", ",", "sigma2", ",", "sigmax", ",", "rescale_grad", "=", "1.0", ",", "grad", "=", "None", ")", ":", "if", "grad", "is", "None", ":", "grad", "=", "nd", ".", "empty", "(", "theta", ".", "shape", ",", "theta", ".", "context", ")", "theta1", "=", "theta", ".", "asnumpy", "(", ")", "[", "0", "]", "theta2", "=", "theta", ".", "asnumpy", "(", ")", "[", "1", "]", "v1", "=", "sigma1", "**", "2", "v2", "=", "sigma2", "**", "2", "vx", "=", "sigmax", "**", "2", "denominator", "=", "numpy", ".", "exp", "(", "-", "(", "X", "-", "theta1", ")", "**", "2", "/", "(", "2", "*", "vx", ")", ")", "+", "numpy", ".", "exp", "(", "-", "(", "X", "-", "theta1", "-", "theta2", ")", "**", "2", "/", "(", "2", "*", "vx", ")", ")", "grad_npy", "=", "numpy", ".", "zeros", "(", "theta", ".", "shape", ")", "grad_npy", "[", "0", "]", "=", "-", "rescale_grad", "*", "(", "(", "numpy", ".", "exp", "(", "-", "(", "X", "-", "theta1", ")", "**", "2", "/", "(", "2", "*", "vx", ")", ")", "*", "(", "X", "-", "theta1", ")", "/", "vx", "+", "numpy", ".", "exp", "(", "-", "(", "X", "-", "theta1", "-", "theta2", ")", "**", "2", "/", "(", "2", "*", "vx", ")", ")", "*", "(", "X", "-", "theta1", "-", "theta2", ")", "/", "vx", ")", "/", "denominator", ")", ".", "sum", "(", ")", "+", "theta1", "/", "v1", "grad_npy", "[", "1", "]", "=", "-", "rescale_grad", "*", "(", "(", "numpy", ".", "exp", "(", "-", "(", "X", "-", "theta1", "-", "theta2", ")", "**", "2", "/", "(", "2", "*", "vx", ")", ")", "*", "(", "X", "-", "theta1", "-", "theta2", ")", "/", "vx", ")", "/", "denominator", ")", ".", "sum", "(", ")", "+", "theta2", "/", "v2", "grad", "[", ":", "]", "=", "grad_npy", "return", "grad" ]
Get synthetic gradient value
[ "Get", "synthetic", "gradient", "value" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/bayesian-methods/bdk_demo.py#L121-L139
23,702
apache/incubator-mxnet
example/bayesian-methods/bdk_demo.py
get_toy_sym
def get_toy_sym(teacher=True, teacher_noise_precision=None): """Get toy symbol""" if teacher: net = mx.symbol.Variable('data') net = mx.symbol.FullyConnected(data=net, name='teacher_fc1', num_hidden=100) net = mx.symbol.Activation(data=net, name='teacher_relu1', act_type="relu") net = mx.symbol.FullyConnected(data=net, name='teacher_fc2', num_hidden=1) net = mx.symbol.LinearRegressionOutput(data=net, name='teacher_output', grad_scale=teacher_noise_precision) else: net = mx.symbol.Variable('data') net = mx.symbol.FullyConnected(data=net, name='student_fc1', num_hidden=100) net = mx.symbol.Activation(data=net, name='student_relu1', act_type="relu") student_mean = mx.symbol.FullyConnected(data=net, name='student_mean', num_hidden=1) student_var = mx.symbol.FullyConnected(data=net, name='student_var', num_hidden=1) net = mx.symbol.Group([student_mean, student_var]) return net
python
def get_toy_sym(teacher=True, teacher_noise_precision=None): """Get toy symbol""" if teacher: net = mx.symbol.Variable('data') net = mx.symbol.FullyConnected(data=net, name='teacher_fc1', num_hidden=100) net = mx.symbol.Activation(data=net, name='teacher_relu1', act_type="relu") net = mx.symbol.FullyConnected(data=net, name='teacher_fc2', num_hidden=1) net = mx.symbol.LinearRegressionOutput(data=net, name='teacher_output', grad_scale=teacher_noise_precision) else: net = mx.symbol.Variable('data') net = mx.symbol.FullyConnected(data=net, name='student_fc1', num_hidden=100) net = mx.symbol.Activation(data=net, name='student_relu1', act_type="relu") student_mean = mx.symbol.FullyConnected(data=net, name='student_mean', num_hidden=1) student_var = mx.symbol.FullyConnected(data=net, name='student_var', num_hidden=1) net = mx.symbol.Group([student_mean, student_var]) return net
[ "def", "get_toy_sym", "(", "teacher", "=", "True", ",", "teacher_noise_precision", "=", "None", ")", ":", "if", "teacher", ":", "net", "=", "mx", ".", "symbol", ".", "Variable", "(", "'data'", ")", "net", "=", "mx", ".", "symbol", ".", "FullyConnected", "(", "data", "=", "net", ",", "name", "=", "'teacher_fc1'", ",", "num_hidden", "=", "100", ")", "net", "=", "mx", ".", "symbol", ".", "Activation", "(", "data", "=", "net", ",", "name", "=", "'teacher_relu1'", ",", "act_type", "=", "\"relu\"", ")", "net", "=", "mx", ".", "symbol", ".", "FullyConnected", "(", "data", "=", "net", ",", "name", "=", "'teacher_fc2'", ",", "num_hidden", "=", "1", ")", "net", "=", "mx", ".", "symbol", ".", "LinearRegressionOutput", "(", "data", "=", "net", ",", "name", "=", "'teacher_output'", ",", "grad_scale", "=", "teacher_noise_precision", ")", "else", ":", "net", "=", "mx", ".", "symbol", ".", "Variable", "(", "'data'", ")", "net", "=", "mx", ".", "symbol", ".", "FullyConnected", "(", "data", "=", "net", ",", "name", "=", "'student_fc1'", ",", "num_hidden", "=", "100", ")", "net", "=", "mx", ".", "symbol", ".", "Activation", "(", "data", "=", "net", ",", "name", "=", "'student_relu1'", ",", "act_type", "=", "\"relu\"", ")", "student_mean", "=", "mx", ".", "symbol", ".", "FullyConnected", "(", "data", "=", "net", ",", "name", "=", "'student_mean'", ",", "num_hidden", "=", "1", ")", "student_var", "=", "mx", ".", "symbol", ".", "FullyConnected", "(", "data", "=", "net", ",", "name", "=", "'student_var'", ",", "num_hidden", "=", "1", ")", "net", "=", "mx", ".", "symbol", ".", "Group", "(", "[", "student_mean", ",", "student_var", "]", ")", "return", "net" ]
Get toy symbol
[ "Get", "toy", "symbol" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/bayesian-methods/bdk_demo.py#L142-L158
23,703
apache/incubator-mxnet
example/bayesian-methods/bdk_demo.py
run_mnist_DistilledSGLD
def run_mnist_DistilledSGLD(num_training=50000, gpu_id=None): """Run DistilledSGLD on mnist dataset""" X, Y, X_test, Y_test = load_mnist(num_training) minibatch_size = 100 if num_training >= 10000: num_hidden = 800 total_iter_num = 1000000 teacher_learning_rate = 1E-6 student_learning_rate = 0.0001 teacher_prior = 1 student_prior = 0.1 perturb_deviation = 0.1 else: num_hidden = 400 total_iter_num = 20000 teacher_learning_rate = 4E-5 student_learning_rate = 0.0001 teacher_prior = 1 student_prior = 0.1 perturb_deviation = 0.001 teacher_net = get_mnist_sym(num_hidden=num_hidden) logsoftmax = LogSoftmax() student_net = get_mnist_sym(output_op=logsoftmax, num_hidden=num_hidden) data_shape = (minibatch_size,) + X.shape[1::] teacher_data_inputs = {'data': nd.zeros(data_shape, ctx=dev(gpu_id)), 'softmax_label': nd.zeros((minibatch_size,), ctx=dev(gpu_id))} student_data_inputs = {'data': nd.zeros(data_shape, ctx=dev(gpu_id)), 'softmax_label': nd.zeros((minibatch_size, 10), ctx=dev(gpu_id))} teacher_initializer = BiasXavier(factor_type="in", magnitude=1) student_initializer = BiasXavier(factor_type="in", magnitude=1) student_exe, student_params, _ = \ DistilledSGLD(teacher_sym=teacher_net, student_sym=student_net, teacher_data_inputs=teacher_data_inputs, student_data_inputs=student_data_inputs, X=X, Y=Y, X_test=X_test, Y_test=Y_test, total_iter_num=total_iter_num, student_initializer=student_initializer, teacher_initializer=teacher_initializer, student_optimizing_algorithm="adam", teacher_learning_rate=teacher_learning_rate, student_learning_rate=student_learning_rate, teacher_prior_precision=teacher_prior, student_prior_precision=student_prior, perturb_deviation=perturb_deviation, minibatch_size=100, dev=dev(gpu_id))
python
def run_mnist_DistilledSGLD(num_training=50000, gpu_id=None): """Run DistilledSGLD on mnist dataset""" X, Y, X_test, Y_test = load_mnist(num_training) minibatch_size = 100 if num_training >= 10000: num_hidden = 800 total_iter_num = 1000000 teacher_learning_rate = 1E-6 student_learning_rate = 0.0001 teacher_prior = 1 student_prior = 0.1 perturb_deviation = 0.1 else: num_hidden = 400 total_iter_num = 20000 teacher_learning_rate = 4E-5 student_learning_rate = 0.0001 teacher_prior = 1 student_prior = 0.1 perturb_deviation = 0.001 teacher_net = get_mnist_sym(num_hidden=num_hidden) logsoftmax = LogSoftmax() student_net = get_mnist_sym(output_op=logsoftmax, num_hidden=num_hidden) data_shape = (minibatch_size,) + X.shape[1::] teacher_data_inputs = {'data': nd.zeros(data_shape, ctx=dev(gpu_id)), 'softmax_label': nd.zeros((minibatch_size,), ctx=dev(gpu_id))} student_data_inputs = {'data': nd.zeros(data_shape, ctx=dev(gpu_id)), 'softmax_label': nd.zeros((minibatch_size, 10), ctx=dev(gpu_id))} teacher_initializer = BiasXavier(factor_type="in", magnitude=1) student_initializer = BiasXavier(factor_type="in", magnitude=1) student_exe, student_params, _ = \ DistilledSGLD(teacher_sym=teacher_net, student_sym=student_net, teacher_data_inputs=teacher_data_inputs, student_data_inputs=student_data_inputs, X=X, Y=Y, X_test=X_test, Y_test=Y_test, total_iter_num=total_iter_num, student_initializer=student_initializer, teacher_initializer=teacher_initializer, student_optimizing_algorithm="adam", teacher_learning_rate=teacher_learning_rate, student_learning_rate=student_learning_rate, teacher_prior_precision=teacher_prior, student_prior_precision=student_prior, perturb_deviation=perturb_deviation, minibatch_size=100, dev=dev(gpu_id))
[ "def", "run_mnist_DistilledSGLD", "(", "num_training", "=", "50000", ",", "gpu_id", "=", "None", ")", ":", "X", ",", "Y", ",", "X_test", ",", "Y_test", "=", "load_mnist", "(", "num_training", ")", "minibatch_size", "=", "100", "if", "num_training", ">=", "10000", ":", "num_hidden", "=", "800", "total_iter_num", "=", "1000000", "teacher_learning_rate", "=", "1E-6", "student_learning_rate", "=", "0.0001", "teacher_prior", "=", "1", "student_prior", "=", "0.1", "perturb_deviation", "=", "0.1", "else", ":", "num_hidden", "=", "400", "total_iter_num", "=", "20000", "teacher_learning_rate", "=", "4E-5", "student_learning_rate", "=", "0.0001", "teacher_prior", "=", "1", "student_prior", "=", "0.1", "perturb_deviation", "=", "0.001", "teacher_net", "=", "get_mnist_sym", "(", "num_hidden", "=", "num_hidden", ")", "logsoftmax", "=", "LogSoftmax", "(", ")", "student_net", "=", "get_mnist_sym", "(", "output_op", "=", "logsoftmax", ",", "num_hidden", "=", "num_hidden", ")", "data_shape", "=", "(", "minibatch_size", ",", ")", "+", "X", ".", "shape", "[", "1", ":", ":", "]", "teacher_data_inputs", "=", "{", "'data'", ":", "nd", ".", "zeros", "(", "data_shape", ",", "ctx", "=", "dev", "(", "gpu_id", ")", ")", ",", "'softmax_label'", ":", "nd", ".", "zeros", "(", "(", "minibatch_size", ",", ")", ",", "ctx", "=", "dev", "(", "gpu_id", ")", ")", "}", "student_data_inputs", "=", "{", "'data'", ":", "nd", ".", "zeros", "(", "data_shape", ",", "ctx", "=", "dev", "(", "gpu_id", ")", ")", ",", "'softmax_label'", ":", "nd", ".", "zeros", "(", "(", "minibatch_size", ",", "10", ")", ",", "ctx", "=", "dev", "(", "gpu_id", ")", ")", "}", "teacher_initializer", "=", "BiasXavier", "(", "factor_type", "=", "\"in\"", ",", "magnitude", "=", "1", ")", "student_initializer", "=", "BiasXavier", "(", "factor_type", "=", "\"in\"", ",", "magnitude", "=", "1", ")", "student_exe", ",", "student_params", ",", "_", "=", "DistilledSGLD", "(", "teacher_sym", "=", "teacher_net", ",", "student_sym", "=", "student_net", ",", "teacher_data_inputs", "=", "teacher_data_inputs", ",", "student_data_inputs", "=", "student_data_inputs", ",", "X", "=", "X", ",", "Y", "=", "Y", ",", "X_test", "=", "X_test", ",", "Y_test", "=", "Y_test", ",", "total_iter_num", "=", "total_iter_num", ",", "student_initializer", "=", "student_initializer", ",", "teacher_initializer", "=", "teacher_initializer", ",", "student_optimizing_algorithm", "=", "\"adam\"", ",", "teacher_learning_rate", "=", "teacher_learning_rate", ",", "student_learning_rate", "=", "student_learning_rate", ",", "teacher_prior_precision", "=", "teacher_prior", ",", "student_prior_precision", "=", "student_prior", ",", "perturb_deviation", "=", "perturb_deviation", ",", "minibatch_size", "=", "100", ",", "dev", "=", "dev", "(", "gpu_id", ")", ")" ]
Run DistilledSGLD on mnist dataset
[ "Run", "DistilledSGLD", "on", "mnist", "dataset" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/bayesian-methods/bdk_demo.py#L196-L237
23,704
apache/incubator-mxnet
example/bayesian-methods/bdk_demo.py
run_toy_SGLD
def run_toy_SGLD(gpu_id=None): """Run SGLD on toy dataset""" X, Y, X_test, Y_test = load_toy() minibatch_size = 1 teacher_noise_precision = 1.0 / 9.0 net = get_toy_sym(True, teacher_noise_precision) data_shape = (minibatch_size,) + X.shape[1::] data_inputs = {'data': nd.zeros(data_shape, ctx=dev(gpu_id)), 'teacher_output_label': nd.zeros((minibatch_size, 1), ctx=dev(gpu_id))} initializer = mx.init.Uniform(0.07) exe, params, _ = SGLD(sym=net, data_inputs=data_inputs, X=X, Y=Y, X_test=X_test, Y_test=Y_test, total_iter_num=50000, initializer=initializer, learning_rate=1E-4, # lr_scheduler=mx.lr_scheduler.FactorScheduler(100000, 0.5), prior_precision=0.1, burn_in_iter_num=1000, thin_interval=10, task='regression', minibatch_size=minibatch_size, dev=dev(gpu_id))
python
def run_toy_SGLD(gpu_id=None): """Run SGLD on toy dataset""" X, Y, X_test, Y_test = load_toy() minibatch_size = 1 teacher_noise_precision = 1.0 / 9.0 net = get_toy_sym(True, teacher_noise_precision) data_shape = (minibatch_size,) + X.shape[1::] data_inputs = {'data': nd.zeros(data_shape, ctx=dev(gpu_id)), 'teacher_output_label': nd.zeros((minibatch_size, 1), ctx=dev(gpu_id))} initializer = mx.init.Uniform(0.07) exe, params, _ = SGLD(sym=net, data_inputs=data_inputs, X=X, Y=Y, X_test=X_test, Y_test=Y_test, total_iter_num=50000, initializer=initializer, learning_rate=1E-4, # lr_scheduler=mx.lr_scheduler.FactorScheduler(100000, 0.5), prior_precision=0.1, burn_in_iter_num=1000, thin_interval=10, task='regression', minibatch_size=minibatch_size, dev=dev(gpu_id))
[ "def", "run_toy_SGLD", "(", "gpu_id", "=", "None", ")", ":", "X", ",", "Y", ",", "X_test", ",", "Y_test", "=", "load_toy", "(", ")", "minibatch_size", "=", "1", "teacher_noise_precision", "=", "1.0", "/", "9.0", "net", "=", "get_toy_sym", "(", "True", ",", "teacher_noise_precision", ")", "data_shape", "=", "(", "minibatch_size", ",", ")", "+", "X", ".", "shape", "[", "1", ":", ":", "]", "data_inputs", "=", "{", "'data'", ":", "nd", ".", "zeros", "(", "data_shape", ",", "ctx", "=", "dev", "(", "gpu_id", ")", ")", ",", "'teacher_output_label'", ":", "nd", ".", "zeros", "(", "(", "minibatch_size", ",", "1", ")", ",", "ctx", "=", "dev", "(", "gpu_id", ")", ")", "}", "initializer", "=", "mx", ".", "init", ".", "Uniform", "(", "0.07", ")", "exe", ",", "params", ",", "_", "=", "SGLD", "(", "sym", "=", "net", ",", "data_inputs", "=", "data_inputs", ",", "X", "=", "X", ",", "Y", "=", "Y", ",", "X_test", "=", "X_test", ",", "Y_test", "=", "Y_test", ",", "total_iter_num", "=", "50000", ",", "initializer", "=", "initializer", ",", "learning_rate", "=", "1E-4", ",", "# lr_scheduler=mx.lr_scheduler.FactorScheduler(100000, 0.5),", "prior_precision", "=", "0.1", ",", "burn_in_iter_num", "=", "1000", ",", "thin_interval", "=", "10", ",", "task", "=", "'regression'", ",", "minibatch_size", "=", "minibatch_size", ",", "dev", "=", "dev", "(", "gpu_id", ")", ")" ]
Run SGLD on toy dataset
[ "Run", "SGLD", "on", "toy", "dataset" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/bayesian-methods/bdk_demo.py#L240-L265
23,705
apache/incubator-mxnet
example/bayesian-methods/bdk_demo.py
run_toy_DistilledSGLD
def run_toy_DistilledSGLD(gpu_id): """Run DistilledSGLD on toy dataset""" X, Y, X_test, Y_test = load_toy() minibatch_size = 1 teacher_noise_precision = 1.0 teacher_net = get_toy_sym(True, teacher_noise_precision) student_net = get_toy_sym(False) data_shape = (minibatch_size,) + X.shape[1::] teacher_data_inputs = {'data': nd.zeros(data_shape, ctx=dev(gpu_id)), 'teacher_output_label': nd.zeros((minibatch_size, 1), ctx=dev(gpu_id))} student_data_inputs = {'data': nd.zeros(data_shape, ctx=dev(gpu_id))} teacher_initializer = mx.init.Uniform(0.07) student_initializer = mx.init.Uniform(0.07) student_grad_f = lambda student_outputs, teacher_pred: \ regression_student_grad(student_outputs, teacher_pred, teacher_noise_precision) student_exe, student_params, _ = \ DistilledSGLD(teacher_sym=teacher_net, student_sym=student_net, teacher_data_inputs=teacher_data_inputs, student_data_inputs=student_data_inputs, X=X, Y=Y, X_test=X_test, Y_test=Y_test, total_iter_num=80000, teacher_initializer=teacher_initializer, student_initializer=student_initializer, teacher_learning_rate=1E-4, student_learning_rate=0.01, # teacher_lr_scheduler=mx.lr_scheduler.FactorScheduler(100000, 0.5), student_lr_scheduler=mx.lr_scheduler.FactorScheduler(8000, 0.8), student_grad_f=student_grad_f, teacher_prior_precision=0.1, student_prior_precision=0.001, perturb_deviation=0.1, minibatch_size=minibatch_size, task='regression', dev=dev(gpu_id))
python
def run_toy_DistilledSGLD(gpu_id): """Run DistilledSGLD on toy dataset""" X, Y, X_test, Y_test = load_toy() minibatch_size = 1 teacher_noise_precision = 1.0 teacher_net = get_toy_sym(True, teacher_noise_precision) student_net = get_toy_sym(False) data_shape = (minibatch_size,) + X.shape[1::] teacher_data_inputs = {'data': nd.zeros(data_shape, ctx=dev(gpu_id)), 'teacher_output_label': nd.zeros((minibatch_size, 1), ctx=dev(gpu_id))} student_data_inputs = {'data': nd.zeros(data_shape, ctx=dev(gpu_id))} teacher_initializer = mx.init.Uniform(0.07) student_initializer = mx.init.Uniform(0.07) student_grad_f = lambda student_outputs, teacher_pred: \ regression_student_grad(student_outputs, teacher_pred, teacher_noise_precision) student_exe, student_params, _ = \ DistilledSGLD(teacher_sym=teacher_net, student_sym=student_net, teacher_data_inputs=teacher_data_inputs, student_data_inputs=student_data_inputs, X=X, Y=Y, X_test=X_test, Y_test=Y_test, total_iter_num=80000, teacher_initializer=teacher_initializer, student_initializer=student_initializer, teacher_learning_rate=1E-4, student_learning_rate=0.01, # teacher_lr_scheduler=mx.lr_scheduler.FactorScheduler(100000, 0.5), student_lr_scheduler=mx.lr_scheduler.FactorScheduler(8000, 0.8), student_grad_f=student_grad_f, teacher_prior_precision=0.1, student_prior_precision=0.001, perturb_deviation=0.1, minibatch_size=minibatch_size, task='regression', dev=dev(gpu_id))
[ "def", "run_toy_DistilledSGLD", "(", "gpu_id", ")", ":", "X", ",", "Y", ",", "X_test", ",", "Y_test", "=", "load_toy", "(", ")", "minibatch_size", "=", "1", "teacher_noise_precision", "=", "1.0", "teacher_net", "=", "get_toy_sym", "(", "True", ",", "teacher_noise_precision", ")", "student_net", "=", "get_toy_sym", "(", "False", ")", "data_shape", "=", "(", "minibatch_size", ",", ")", "+", "X", ".", "shape", "[", "1", ":", ":", "]", "teacher_data_inputs", "=", "{", "'data'", ":", "nd", ".", "zeros", "(", "data_shape", ",", "ctx", "=", "dev", "(", "gpu_id", ")", ")", ",", "'teacher_output_label'", ":", "nd", ".", "zeros", "(", "(", "minibatch_size", ",", "1", ")", ",", "ctx", "=", "dev", "(", "gpu_id", ")", ")", "}", "student_data_inputs", "=", "{", "'data'", ":", "nd", ".", "zeros", "(", "data_shape", ",", "ctx", "=", "dev", "(", "gpu_id", ")", ")", "}", "teacher_initializer", "=", "mx", ".", "init", ".", "Uniform", "(", "0.07", ")", "student_initializer", "=", "mx", ".", "init", ".", "Uniform", "(", "0.07", ")", "student_grad_f", "=", "lambda", "student_outputs", ",", "teacher_pred", ":", "regression_student_grad", "(", "student_outputs", ",", "teacher_pred", ",", "teacher_noise_precision", ")", "student_exe", ",", "student_params", ",", "_", "=", "DistilledSGLD", "(", "teacher_sym", "=", "teacher_net", ",", "student_sym", "=", "student_net", ",", "teacher_data_inputs", "=", "teacher_data_inputs", ",", "student_data_inputs", "=", "student_data_inputs", ",", "X", "=", "X", ",", "Y", "=", "Y", ",", "X_test", "=", "X_test", ",", "Y_test", "=", "Y_test", ",", "total_iter_num", "=", "80000", ",", "teacher_initializer", "=", "teacher_initializer", ",", "student_initializer", "=", "student_initializer", ",", "teacher_learning_rate", "=", "1E-4", ",", "student_learning_rate", "=", "0.01", ",", "# teacher_lr_scheduler=mx.lr_scheduler.FactorScheduler(100000, 0.5),", "student_lr_scheduler", "=", "mx", ".", "lr_scheduler", ".", "FactorScheduler", "(", "8000", ",", "0.8", ")", ",", "student_grad_f", "=", "student_grad_f", ",", "teacher_prior_precision", "=", "0.1", ",", "student_prior_precision", "=", "0.001", ",", "perturb_deviation", "=", "0.1", ",", "minibatch_size", "=", "minibatch_size", ",", "task", "=", "'regression'", ",", "dev", "=", "dev", "(", "gpu_id", ")", ")" ]
Run DistilledSGLD on toy dataset
[ "Run", "DistilledSGLD", "on", "toy", "dataset" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/bayesian-methods/bdk_demo.py#L268-L297
23,706
apache/incubator-mxnet
example/bayesian-methods/bdk_demo.py
run_toy_HMC
def run_toy_HMC(gpu_id=None): """Run HMC on toy dataset""" X, Y, X_test, Y_test = load_toy() minibatch_size = Y.shape[0] noise_precision = 1 / 9.0 net = get_toy_sym(True, noise_precision) data_shape = (minibatch_size,) + X.shape[1::] data_inputs = {'data': nd.zeros(data_shape, ctx=dev(gpu_id)), 'teacher_output_label': nd.zeros((minibatch_size, 1), ctx=dev(gpu_id))} initializer = mx.init.Uniform(0.07) sample_pool = HMC(net, data_inputs=data_inputs, X=X, Y=Y, X_test=X_test, Y_test=Y_test, sample_num=300000, initializer=initializer, prior_precision=1.0, learning_rate=1E-3, L=10, dev=dev(gpu_id))
python
def run_toy_HMC(gpu_id=None): """Run HMC on toy dataset""" X, Y, X_test, Y_test = load_toy() minibatch_size = Y.shape[0] noise_precision = 1 / 9.0 net = get_toy_sym(True, noise_precision) data_shape = (minibatch_size,) + X.shape[1::] data_inputs = {'data': nd.zeros(data_shape, ctx=dev(gpu_id)), 'teacher_output_label': nd.zeros((minibatch_size, 1), ctx=dev(gpu_id))} initializer = mx.init.Uniform(0.07) sample_pool = HMC(net, data_inputs=data_inputs, X=X, Y=Y, X_test=X_test, Y_test=Y_test, sample_num=300000, initializer=initializer, prior_precision=1.0, learning_rate=1E-3, L=10, dev=dev(gpu_id))
[ "def", "run_toy_HMC", "(", "gpu_id", "=", "None", ")", ":", "X", ",", "Y", ",", "X_test", ",", "Y_test", "=", "load_toy", "(", ")", "minibatch_size", "=", "Y", ".", "shape", "[", "0", "]", "noise_precision", "=", "1", "/", "9.0", "net", "=", "get_toy_sym", "(", "True", ",", "noise_precision", ")", "data_shape", "=", "(", "minibatch_size", ",", ")", "+", "X", ".", "shape", "[", "1", ":", ":", "]", "data_inputs", "=", "{", "'data'", ":", "nd", ".", "zeros", "(", "data_shape", ",", "ctx", "=", "dev", "(", "gpu_id", ")", ")", ",", "'teacher_output_label'", ":", "nd", ".", "zeros", "(", "(", "minibatch_size", ",", "1", ")", ",", "ctx", "=", "dev", "(", "gpu_id", ")", ")", "}", "initializer", "=", "mx", ".", "init", ".", "Uniform", "(", "0.07", ")", "sample_pool", "=", "HMC", "(", "net", ",", "data_inputs", "=", "data_inputs", ",", "X", "=", "X", ",", "Y", "=", "Y", ",", "X_test", "=", "X_test", ",", "Y_test", "=", "Y_test", ",", "sample_num", "=", "300000", ",", "initializer", "=", "initializer", ",", "prior_precision", "=", "1.0", ",", "learning_rate", "=", "1E-3", ",", "L", "=", "10", ",", "dev", "=", "dev", "(", "gpu_id", ")", ")" ]
Run HMC on toy dataset
[ "Run", "HMC", "on", "toy", "dataset" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/bayesian-methods/bdk_demo.py#L300-L312
23,707
apache/incubator-mxnet
example/bayesian-methods/bdk_demo.py
run_synthetic_SGLD
def run_synthetic_SGLD(): """Run synthetic SGLD""" theta1 = 0 theta2 = 1 sigma1 = numpy.sqrt(10) sigma2 = 1 sigmax = numpy.sqrt(2) X = load_synthetic(theta1=theta1, theta2=theta2, sigmax=sigmax, num=100) minibatch_size = 1 total_iter_num = 1000000 lr_scheduler = SGLDScheduler(begin_rate=0.01, end_rate=0.0001, total_iter_num=total_iter_num, factor=0.55) optimizer = mx.optimizer.create('sgld', learning_rate=None, rescale_grad=1.0, lr_scheduler=lr_scheduler, wd=0) updater = mx.optimizer.get_updater(optimizer) theta = mx.random.normal(0, 1, (2,), mx.cpu()) grad = nd.empty((2,), mx.cpu()) samples = numpy.zeros((2, total_iter_num)) start = time.time() for i in range(total_iter_num): if (i + 1) % 100000 == 0: end = time.time() print("Iter:%d, Time spent: %f" % (i + 1, end - start)) start = time.time() ind = numpy.random.randint(0, X.shape[0]) synthetic_grad(X[ind], theta, sigma1, sigma2, sigmax, rescale_grad=X.shape[0] / float(minibatch_size), grad=grad) updater('theta', grad, theta) samples[:, i] = theta.asnumpy() plt.hist2d(samples[0, :], samples[1, :], (200, 200), cmap=plt.cm.jet) plt.colorbar() plt.show()
python
def run_synthetic_SGLD(): """Run synthetic SGLD""" theta1 = 0 theta2 = 1 sigma1 = numpy.sqrt(10) sigma2 = 1 sigmax = numpy.sqrt(2) X = load_synthetic(theta1=theta1, theta2=theta2, sigmax=sigmax, num=100) minibatch_size = 1 total_iter_num = 1000000 lr_scheduler = SGLDScheduler(begin_rate=0.01, end_rate=0.0001, total_iter_num=total_iter_num, factor=0.55) optimizer = mx.optimizer.create('sgld', learning_rate=None, rescale_grad=1.0, lr_scheduler=lr_scheduler, wd=0) updater = mx.optimizer.get_updater(optimizer) theta = mx.random.normal(0, 1, (2,), mx.cpu()) grad = nd.empty((2,), mx.cpu()) samples = numpy.zeros((2, total_iter_num)) start = time.time() for i in range(total_iter_num): if (i + 1) % 100000 == 0: end = time.time() print("Iter:%d, Time spent: %f" % (i + 1, end - start)) start = time.time() ind = numpy.random.randint(0, X.shape[0]) synthetic_grad(X[ind], theta, sigma1, sigma2, sigmax, rescale_grad=X.shape[0] / float(minibatch_size), grad=grad) updater('theta', grad, theta) samples[:, i] = theta.asnumpy() plt.hist2d(samples[0, :], samples[1, :], (200, 200), cmap=plt.cm.jet) plt.colorbar() plt.show()
[ "def", "run_synthetic_SGLD", "(", ")", ":", "theta1", "=", "0", "theta2", "=", "1", "sigma1", "=", "numpy", ".", "sqrt", "(", "10", ")", "sigma2", "=", "1", "sigmax", "=", "numpy", ".", "sqrt", "(", "2", ")", "X", "=", "load_synthetic", "(", "theta1", "=", "theta1", ",", "theta2", "=", "theta2", ",", "sigmax", "=", "sigmax", ",", "num", "=", "100", ")", "minibatch_size", "=", "1", "total_iter_num", "=", "1000000", "lr_scheduler", "=", "SGLDScheduler", "(", "begin_rate", "=", "0.01", ",", "end_rate", "=", "0.0001", ",", "total_iter_num", "=", "total_iter_num", ",", "factor", "=", "0.55", ")", "optimizer", "=", "mx", ".", "optimizer", ".", "create", "(", "'sgld'", ",", "learning_rate", "=", "None", ",", "rescale_grad", "=", "1.0", ",", "lr_scheduler", "=", "lr_scheduler", ",", "wd", "=", "0", ")", "updater", "=", "mx", ".", "optimizer", ".", "get_updater", "(", "optimizer", ")", "theta", "=", "mx", ".", "random", ".", "normal", "(", "0", ",", "1", ",", "(", "2", ",", ")", ",", "mx", ".", "cpu", "(", ")", ")", "grad", "=", "nd", ".", "empty", "(", "(", "2", ",", ")", ",", "mx", ".", "cpu", "(", ")", ")", "samples", "=", "numpy", ".", "zeros", "(", "(", "2", ",", "total_iter_num", ")", ")", "start", "=", "time", ".", "time", "(", ")", "for", "i", "in", "range", "(", "total_iter_num", ")", ":", "if", "(", "i", "+", "1", ")", "%", "100000", "==", "0", ":", "end", "=", "time", ".", "time", "(", ")", "print", "(", "\"Iter:%d, Time spent: %f\"", "%", "(", "i", "+", "1", ",", "end", "-", "start", ")", ")", "start", "=", "time", ".", "time", "(", ")", "ind", "=", "numpy", ".", "random", ".", "randint", "(", "0", ",", "X", ".", "shape", "[", "0", "]", ")", "synthetic_grad", "(", "X", "[", "ind", "]", ",", "theta", ",", "sigma1", ",", "sigma2", ",", "sigmax", ",", "rescale_grad", "=", "X", ".", "shape", "[", "0", "]", "/", "float", "(", "minibatch_size", ")", ",", "grad", "=", "grad", ")", "updater", "(", "'theta'", ",", "grad", ",", "theta", ")", "samples", "[", ":", ",", "i", "]", "=", "theta", ".", "asnumpy", "(", ")", "plt", ".", "hist2d", "(", "samples", "[", "0", ",", ":", "]", ",", "samples", "[", "1", ",", ":", "]", ",", "(", "200", ",", "200", ")", ",", "cmap", "=", "plt", ".", "cm", ".", "jet", ")", "plt", ".", "colorbar", "(", ")", "plt", ".", "show", "(", ")" ]
Run synthetic SGLD
[ "Run", "synthetic", "SGLD" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/bayesian-methods/bdk_demo.py#L315-L349
23,708
apache/incubator-mxnet
example/ssd/tools/prepare_dataset.py
load_pascal
def load_pascal(image_set, year, devkit_path, shuffle=False): """ wrapper function for loading pascal voc dataset Parameters: ---------- image_set : str train, trainval... year : str 2007, 2012 or combinations splitted by comma devkit_path : str root directory of dataset shuffle : bool whether to shuffle initial list Returns: ---------- Imdb """ image_set = [y.strip() for y in image_set.split(',')] assert image_set, "No image_set specified" year = [y.strip() for y in year.split(',')] assert year, "No year specified" # make sure (# sets == # years) if len(image_set) > 1 and len(year) == 1: year = year * len(image_set) if len(image_set) == 1 and len(year) > 1: image_set = image_set * len(year) assert len(image_set) == len(year), "Number of sets and year mismatch" imdbs = [] for s, y in zip(image_set, year): imdbs.append(PascalVoc(s, y, devkit_path, shuffle, is_train=True)) if len(imdbs) > 1: return ConcatDB(imdbs, shuffle) else: return imdbs[0]
python
def load_pascal(image_set, year, devkit_path, shuffle=False): """ wrapper function for loading pascal voc dataset Parameters: ---------- image_set : str train, trainval... year : str 2007, 2012 or combinations splitted by comma devkit_path : str root directory of dataset shuffle : bool whether to shuffle initial list Returns: ---------- Imdb """ image_set = [y.strip() for y in image_set.split(',')] assert image_set, "No image_set specified" year = [y.strip() for y in year.split(',')] assert year, "No year specified" # make sure (# sets == # years) if len(image_set) > 1 and len(year) == 1: year = year * len(image_set) if len(image_set) == 1 and len(year) > 1: image_set = image_set * len(year) assert len(image_set) == len(year), "Number of sets and year mismatch" imdbs = [] for s, y in zip(image_set, year): imdbs.append(PascalVoc(s, y, devkit_path, shuffle, is_train=True)) if len(imdbs) > 1: return ConcatDB(imdbs, shuffle) else: return imdbs[0]
[ "def", "load_pascal", "(", "image_set", ",", "year", ",", "devkit_path", ",", "shuffle", "=", "False", ")", ":", "image_set", "=", "[", "y", ".", "strip", "(", ")", "for", "y", "in", "image_set", ".", "split", "(", "','", ")", "]", "assert", "image_set", ",", "\"No image_set specified\"", "year", "=", "[", "y", ".", "strip", "(", ")", "for", "y", "in", "year", ".", "split", "(", "','", ")", "]", "assert", "year", ",", "\"No year specified\"", "# make sure (# sets == # years)", "if", "len", "(", "image_set", ")", ">", "1", "and", "len", "(", "year", ")", "==", "1", ":", "year", "=", "year", "*", "len", "(", "image_set", ")", "if", "len", "(", "image_set", ")", "==", "1", "and", "len", "(", "year", ")", ">", "1", ":", "image_set", "=", "image_set", "*", "len", "(", "year", ")", "assert", "len", "(", "image_set", ")", "==", "len", "(", "year", ")", ",", "\"Number of sets and year mismatch\"", "imdbs", "=", "[", "]", "for", "s", ",", "y", "in", "zip", "(", "image_set", ",", "year", ")", ":", "imdbs", ".", "append", "(", "PascalVoc", "(", "s", ",", "y", ",", "devkit_path", ",", "shuffle", ",", "is_train", "=", "True", ")", ")", "if", "len", "(", "imdbs", ")", ">", "1", ":", "return", "ConcatDB", "(", "imdbs", ",", "shuffle", ")", "else", ":", "return", "imdbs", "[", "0", "]" ]
wrapper function for loading pascal voc dataset Parameters: ---------- image_set : str train, trainval... year : str 2007, 2012 or combinations splitted by comma devkit_path : str root directory of dataset shuffle : bool whether to shuffle initial list Returns: ---------- Imdb
[ "wrapper", "function", "for", "loading", "pascal", "voc", "dataset" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/ssd/tools/prepare_dataset.py#L31-L68
23,709
apache/incubator-mxnet
example/ssd/tools/prepare_dataset.py
load_coco
def load_coco(image_set, dirname, shuffle=False): """ wrapper function for loading ms coco dataset Parameters: ---------- image_set : str train2014, val2014, valminusminival2014, minival2014 dirname: str root dir for coco shuffle: boolean initial shuffle """ anno_files = ['instances_' + y.strip() + '.json' for y in image_set.split(',')] assert anno_files, "No image set specified" imdbs = [] for af in anno_files: af_path = os.path.join(dirname, 'annotations', af) imdbs.append(Coco(af_path, dirname, shuffle=shuffle)) if len(imdbs) > 1: return ConcatDB(imdbs, shuffle) else: return imdbs[0]
python
def load_coco(image_set, dirname, shuffle=False): """ wrapper function for loading ms coco dataset Parameters: ---------- image_set : str train2014, val2014, valminusminival2014, minival2014 dirname: str root dir for coco shuffle: boolean initial shuffle """ anno_files = ['instances_' + y.strip() + '.json' for y in image_set.split(',')] assert anno_files, "No image set specified" imdbs = [] for af in anno_files: af_path = os.path.join(dirname, 'annotations', af) imdbs.append(Coco(af_path, dirname, shuffle=shuffle)) if len(imdbs) > 1: return ConcatDB(imdbs, shuffle) else: return imdbs[0]
[ "def", "load_coco", "(", "image_set", ",", "dirname", ",", "shuffle", "=", "False", ")", ":", "anno_files", "=", "[", "'instances_'", "+", "y", ".", "strip", "(", ")", "+", "'.json'", "for", "y", "in", "image_set", ".", "split", "(", "','", ")", "]", "assert", "anno_files", ",", "\"No image set specified\"", "imdbs", "=", "[", "]", "for", "af", "in", "anno_files", ":", "af_path", "=", "os", ".", "path", ".", "join", "(", "dirname", ",", "'annotations'", ",", "af", ")", "imdbs", ".", "append", "(", "Coco", "(", "af_path", ",", "dirname", ",", "shuffle", "=", "shuffle", ")", ")", "if", "len", "(", "imdbs", ")", ">", "1", ":", "return", "ConcatDB", "(", "imdbs", ",", "shuffle", ")", "else", ":", "return", "imdbs", "[", "0", "]" ]
wrapper function for loading ms coco dataset Parameters: ---------- image_set : str train2014, val2014, valminusminival2014, minival2014 dirname: str root dir for coco shuffle: boolean initial shuffle
[ "wrapper", "function", "for", "loading", "ms", "coco", "dataset" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/ssd/tools/prepare_dataset.py#L70-L92
23,710
apache/incubator-mxnet
tools/coreml/converter/_layers.py
convert_transpose
def convert_transpose(net, node, module, builder): """Convert a transpose layer from mxnet to coreml. Parameters ---------- network: net A mxnet network object. layer: node Node to convert. module: module An module for MXNet builder: NeuralNetworkBuilder A neural network builder object. """ input_name, output_name = _get_input_output_name(net, node) name = node['name'] param = _get_attrs(node) axes = literal_eval(param['axes']) builder.add_permute(name, axes, input_name, output_name)
python
def convert_transpose(net, node, module, builder): """Convert a transpose layer from mxnet to coreml. Parameters ---------- network: net A mxnet network object. layer: node Node to convert. module: module An module for MXNet builder: NeuralNetworkBuilder A neural network builder object. """ input_name, output_name = _get_input_output_name(net, node) name = node['name'] param = _get_attrs(node) axes = literal_eval(param['axes']) builder.add_permute(name, axes, input_name, output_name)
[ "def", "convert_transpose", "(", "net", ",", "node", ",", "module", ",", "builder", ")", ":", "input_name", ",", "output_name", "=", "_get_input_output_name", "(", "net", ",", "node", ")", "name", "=", "node", "[", "'name'", "]", "param", "=", "_get_attrs", "(", "node", ")", "axes", "=", "literal_eval", "(", "param", "[", "'axes'", "]", ")", "builder", ".", "add_permute", "(", "name", ",", "axes", ",", "input_name", ",", "output_name", ")" ]
Convert a transpose layer from mxnet to coreml. Parameters ---------- network: net A mxnet network object. layer: node Node to convert. module: module An module for MXNet builder: NeuralNetworkBuilder A neural network builder object.
[ "Convert", "a", "transpose", "layer", "from", "mxnet", "to", "coreml", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/tools/coreml/converter/_layers.py#L116-L138
23,711
apache/incubator-mxnet
tools/coreml/converter/_layers.py
convert_flatten
def convert_flatten(net, node, module, builder): """Convert a flatten layer from mxnet to coreml. Parameters ---------- network: net A mxnet network object. layer: node Node to convert. module: module An module for MXNet builder: NeuralNetworkBuilder A neural network builder object. """ input_name, output_name = _get_input_output_name(net, node) name = node['name'] mode = 0 # CHANNEL_FIRST builder.add_flatten(name, mode, input_name, output_name)
python
def convert_flatten(net, node, module, builder): """Convert a flatten layer from mxnet to coreml. Parameters ---------- network: net A mxnet network object. layer: node Node to convert. module: module An module for MXNet builder: NeuralNetworkBuilder A neural network builder object. """ input_name, output_name = _get_input_output_name(net, node) name = node['name'] mode = 0 # CHANNEL_FIRST builder.add_flatten(name, mode, input_name, output_name)
[ "def", "convert_flatten", "(", "net", ",", "node", ",", "module", ",", "builder", ")", ":", "input_name", ",", "output_name", "=", "_get_input_output_name", "(", "net", ",", "node", ")", "name", "=", "node", "[", "'name'", "]", "mode", "=", "0", "# CHANNEL_FIRST", "builder", ".", "add_flatten", "(", "name", ",", "mode", ",", "input_name", ",", "output_name", ")" ]
Convert a flatten layer from mxnet to coreml. Parameters ---------- network: net A mxnet network object. layer: node Node to convert. module: module An module for MXNet builder: NeuralNetworkBuilder A neural network builder object.
[ "Convert", "a", "flatten", "layer", "from", "mxnet", "to", "coreml", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/tools/coreml/converter/_layers.py#L141-L161
23,712
apache/incubator-mxnet
tools/coreml/converter/_layers.py
convert_activation
def convert_activation(net, node, module, builder): """Convert an activation layer from mxnet to coreml. Parameters ---------- network: net A mxnet network object. layer: node Node to convert. module: module An module for MXNet builder: NeuralNetworkBuilder A neural network builder object. """ input_name, output_name = _get_input_output_name(net, node) name = node['name'] mx_non_linearity = _get_attrs(node)['act_type'] #TODO add SCALED_TANH, SOFTPLUS, SOFTSIGN, SIGMOID_HARD, LEAKYRELU, PRELU, ELU, PARAMETRICSOFTPLUS, THRESHOLDEDRELU, LINEAR if mx_non_linearity == 'relu': non_linearity = 'RELU' elif mx_non_linearity == 'tanh': non_linearity = 'TANH' elif mx_non_linearity == 'sigmoid': non_linearity = 'SIGMOID' else: raise TypeError('Unknown activation type %s' % mx_non_linearity) builder.add_activation(name = name, non_linearity = non_linearity, input_name = input_name, output_name = output_name)
python
def convert_activation(net, node, module, builder): """Convert an activation layer from mxnet to coreml. Parameters ---------- network: net A mxnet network object. layer: node Node to convert. module: module An module for MXNet builder: NeuralNetworkBuilder A neural network builder object. """ input_name, output_name = _get_input_output_name(net, node) name = node['name'] mx_non_linearity = _get_attrs(node)['act_type'] #TODO add SCALED_TANH, SOFTPLUS, SOFTSIGN, SIGMOID_HARD, LEAKYRELU, PRELU, ELU, PARAMETRICSOFTPLUS, THRESHOLDEDRELU, LINEAR if mx_non_linearity == 'relu': non_linearity = 'RELU' elif mx_non_linearity == 'tanh': non_linearity = 'TANH' elif mx_non_linearity == 'sigmoid': non_linearity = 'SIGMOID' else: raise TypeError('Unknown activation type %s' % mx_non_linearity) builder.add_activation(name = name, non_linearity = non_linearity, input_name = input_name, output_name = output_name)
[ "def", "convert_activation", "(", "net", ",", "node", ",", "module", ",", "builder", ")", ":", "input_name", ",", "output_name", "=", "_get_input_output_name", "(", "net", ",", "node", ")", "name", "=", "node", "[", "'name'", "]", "mx_non_linearity", "=", "_get_attrs", "(", "node", ")", "[", "'act_type'", "]", "#TODO add SCALED_TANH, SOFTPLUS, SOFTSIGN, SIGMOID_HARD, LEAKYRELU, PRELU, ELU, PARAMETRICSOFTPLUS, THRESHOLDEDRELU, LINEAR", "if", "mx_non_linearity", "==", "'relu'", ":", "non_linearity", "=", "'RELU'", "elif", "mx_non_linearity", "==", "'tanh'", ":", "non_linearity", "=", "'TANH'", "elif", "mx_non_linearity", "==", "'sigmoid'", ":", "non_linearity", "=", "'SIGMOID'", "else", ":", "raise", "TypeError", "(", "'Unknown activation type %s'", "%", "mx_non_linearity", ")", "builder", ".", "add_activation", "(", "name", "=", "name", ",", "non_linearity", "=", "non_linearity", ",", "input_name", "=", "input_name", ",", "output_name", "=", "output_name", ")" ]
Convert an activation layer from mxnet to coreml. Parameters ---------- network: net A mxnet network object. layer: node Node to convert. module: module An module for MXNet builder: NeuralNetworkBuilder A neural network builder object.
[ "Convert", "an", "activation", "layer", "from", "mxnet", "to", "coreml", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/tools/coreml/converter/_layers.py#L188-L220
23,713
apache/incubator-mxnet
tools/coreml/converter/_layers.py
convert_leakyrelu
def convert_leakyrelu(net, node, module, builder): """Convert a leakyrelu layer from mxnet to coreml. Parameters ---------- network: net A mxnet network object. layer: node Node to convert. module: module An module for MXNet builder: NeuralNetworkBuilder A neural network builder object. """ input_name, output_name = _get_input_output_name(net, node) name = node['name'] inputs = node['inputs'] args, _ = module.get_params() mx_non_linearity = _get_attrs(node)['act_type'] if mx_non_linearity == 'elu': non_linearity = 'ELU' slope = _get_attrs(node)['slope'] if 'slope' in _get_attrs(node) else 0.25 params = slope elif mx_non_linearity == 'leaky': non_linearity = 'LEAKYRELU' slope = _get_attrs(node)['slope'] if 'slope' in _get_attrs(node) else 0.25 params = [slope] elif mx_non_linearity == 'prelu': non_linearity = 'PRELU' params = args[_get_node_name(net, inputs[1][0])].asnumpy() else: raise TypeError('Unknown activation type %s' % mx_non_linearity) builder.add_activation(name = name, non_linearity = non_linearity, input_name = input_name, output_name = output_name, params = params)
python
def convert_leakyrelu(net, node, module, builder): """Convert a leakyrelu layer from mxnet to coreml. Parameters ---------- network: net A mxnet network object. layer: node Node to convert. module: module An module for MXNet builder: NeuralNetworkBuilder A neural network builder object. """ input_name, output_name = _get_input_output_name(net, node) name = node['name'] inputs = node['inputs'] args, _ = module.get_params() mx_non_linearity = _get_attrs(node)['act_type'] if mx_non_linearity == 'elu': non_linearity = 'ELU' slope = _get_attrs(node)['slope'] if 'slope' in _get_attrs(node) else 0.25 params = slope elif mx_non_linearity == 'leaky': non_linearity = 'LEAKYRELU' slope = _get_attrs(node)['slope'] if 'slope' in _get_attrs(node) else 0.25 params = [slope] elif mx_non_linearity == 'prelu': non_linearity = 'PRELU' params = args[_get_node_name(net, inputs[1][0])].asnumpy() else: raise TypeError('Unknown activation type %s' % mx_non_linearity) builder.add_activation(name = name, non_linearity = non_linearity, input_name = input_name, output_name = output_name, params = params)
[ "def", "convert_leakyrelu", "(", "net", ",", "node", ",", "module", ",", "builder", ")", ":", "input_name", ",", "output_name", "=", "_get_input_output_name", "(", "net", ",", "node", ")", "name", "=", "node", "[", "'name'", "]", "inputs", "=", "node", "[", "'inputs'", "]", "args", ",", "_", "=", "module", ".", "get_params", "(", ")", "mx_non_linearity", "=", "_get_attrs", "(", "node", ")", "[", "'act_type'", "]", "if", "mx_non_linearity", "==", "'elu'", ":", "non_linearity", "=", "'ELU'", "slope", "=", "_get_attrs", "(", "node", ")", "[", "'slope'", "]", "if", "'slope'", "in", "_get_attrs", "(", "node", ")", "else", "0.25", "params", "=", "slope", "elif", "mx_non_linearity", "==", "'leaky'", ":", "non_linearity", "=", "'LEAKYRELU'", "slope", "=", "_get_attrs", "(", "node", ")", "[", "'slope'", "]", "if", "'slope'", "in", "_get_attrs", "(", "node", ")", "else", "0.25", "params", "=", "[", "slope", "]", "elif", "mx_non_linearity", "==", "'prelu'", ":", "non_linearity", "=", "'PRELU'", "params", "=", "args", "[", "_get_node_name", "(", "net", ",", "inputs", "[", "1", "]", "[", "0", "]", ")", "]", ".", "asnumpy", "(", ")", "else", ":", "raise", "TypeError", "(", "'Unknown activation type %s'", "%", "mx_non_linearity", ")", "builder", ".", "add_activation", "(", "name", "=", "name", ",", "non_linearity", "=", "non_linearity", ",", "input_name", "=", "input_name", ",", "output_name", "=", "output_name", ",", "params", "=", "params", ")" ]
Convert a leakyrelu layer from mxnet to coreml. Parameters ---------- network: net A mxnet network object. layer: node Node to convert. module: module An module for MXNet builder: NeuralNetworkBuilder A neural network builder object.
[ "Convert", "a", "leakyrelu", "layer", "from", "mxnet", "to", "coreml", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/tools/coreml/converter/_layers.py#L223-L263
23,714
apache/incubator-mxnet
tools/coreml/converter/_layers.py
convert_elementwise_add
def convert_elementwise_add(net, node, module, builder): """Convert an elementwise add layer from mxnet to coreml. Parameters ---------- network: net A mxnet network object. layer: node Node to convert. module: module An module for MXNet builder: NeuralNetworkBuilder A neural network builder object. """ input_names, output_name = _get_input_output_name(net, node, [0, 1]) name = node['name'] builder.add_elementwise(name, input_names, output_name, 'ADD')
python
def convert_elementwise_add(net, node, module, builder): """Convert an elementwise add layer from mxnet to coreml. Parameters ---------- network: net A mxnet network object. layer: node Node to convert. module: module An module for MXNet builder: NeuralNetworkBuilder A neural network builder object. """ input_names, output_name = _get_input_output_name(net, node, [0, 1]) name = node['name'] builder.add_elementwise(name, input_names, output_name, 'ADD')
[ "def", "convert_elementwise_add", "(", "net", ",", "node", ",", "module", ",", "builder", ")", ":", "input_names", ",", "output_name", "=", "_get_input_output_name", "(", "net", ",", "node", ",", "[", "0", ",", "1", "]", ")", "name", "=", "node", "[", "'name'", "]", "builder", ".", "add_elementwise", "(", "name", ",", "input_names", ",", "output_name", ",", "'ADD'", ")" ]
Convert an elementwise add layer from mxnet to coreml. Parameters ---------- network: net A mxnet network object. layer: node Node to convert. module: module An module for MXNet builder: NeuralNetworkBuilder A neural network builder object.
[ "Convert", "an", "elementwise", "add", "layer", "from", "mxnet", "to", "coreml", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/tools/coreml/converter/_layers.py#L266-L287
23,715
apache/incubator-mxnet
tools/coreml/converter/_layers.py
convert_convolution
def convert_convolution(net, node, module, builder): """Convert a convolution layer from mxnet to coreml. Parameters ---------- network: net A mxnet network object. layer: node Node to convert. module: module An module for MXNet builder: NeuralNetworkBuilder A neural network builder object. """ input_name, output_name = _get_input_output_name(net, node) name = node['name'] param = _get_attrs(node) inputs = node['inputs'] args, _ = module.get_params() if 'no_bias' in param.keys(): has_bias = not literal_eval(param['no_bias']) else: has_bias = True if 'pad' in param.keys() and literal_eval(param['pad']) != (0, 0): pad = literal_eval(param['pad']) builder.add_padding( name=name+"_pad", left=pad[1], right=pad[1], top=pad[0], bottom=pad[0], value=0, input_name=input_name, output_name=name+"_pad_output") input_name = name+"_pad_output" border_mode = "valid" n_filters = int(param['num_filter']) n_groups = int(param['num_group']) if 'num_group' in param else 1 W = args[_get_node_name(net, inputs[1][0])].asnumpy() if has_bias: Wb = args[_get_node_name(net, inputs[2][0])].asnumpy() else: Wb = None channels = W.shape[1] stride_height = 1 stride_width = 1 if 'stride' in param.keys(): stride_height, stride_width = literal_eval(param['stride']) kernel_height, kernel_width = literal_eval(param['kernel']) W = W.transpose((2, 3, 1, 0)) builder.add_convolution( name=name, kernel_channels=channels, output_channels=n_filters, height=kernel_height, width=kernel_width, stride_height=stride_height, stride_width=stride_width, border_mode=border_mode, groups=n_groups, W=W, b=Wb, has_bias=has_bias, is_deconv=False, output_shape=None, input_name=input_name, output_name=output_name)
python
def convert_convolution(net, node, module, builder): """Convert a convolution layer from mxnet to coreml. Parameters ---------- network: net A mxnet network object. layer: node Node to convert. module: module An module for MXNet builder: NeuralNetworkBuilder A neural network builder object. """ input_name, output_name = _get_input_output_name(net, node) name = node['name'] param = _get_attrs(node) inputs = node['inputs'] args, _ = module.get_params() if 'no_bias' in param.keys(): has_bias = not literal_eval(param['no_bias']) else: has_bias = True if 'pad' in param.keys() and literal_eval(param['pad']) != (0, 0): pad = literal_eval(param['pad']) builder.add_padding( name=name+"_pad", left=pad[1], right=pad[1], top=pad[0], bottom=pad[0], value=0, input_name=input_name, output_name=name+"_pad_output") input_name = name+"_pad_output" border_mode = "valid" n_filters = int(param['num_filter']) n_groups = int(param['num_group']) if 'num_group' in param else 1 W = args[_get_node_name(net, inputs[1][0])].asnumpy() if has_bias: Wb = args[_get_node_name(net, inputs[2][0])].asnumpy() else: Wb = None channels = W.shape[1] stride_height = 1 stride_width = 1 if 'stride' in param.keys(): stride_height, stride_width = literal_eval(param['stride']) kernel_height, kernel_width = literal_eval(param['kernel']) W = W.transpose((2, 3, 1, 0)) builder.add_convolution( name=name, kernel_channels=channels, output_channels=n_filters, height=kernel_height, width=kernel_width, stride_height=stride_height, stride_width=stride_width, border_mode=border_mode, groups=n_groups, W=W, b=Wb, has_bias=has_bias, is_deconv=False, output_shape=None, input_name=input_name, output_name=output_name)
[ "def", "convert_convolution", "(", "net", ",", "node", ",", "module", ",", "builder", ")", ":", "input_name", ",", "output_name", "=", "_get_input_output_name", "(", "net", ",", "node", ")", "name", "=", "node", "[", "'name'", "]", "param", "=", "_get_attrs", "(", "node", ")", "inputs", "=", "node", "[", "'inputs'", "]", "args", ",", "_", "=", "module", ".", "get_params", "(", ")", "if", "'no_bias'", "in", "param", ".", "keys", "(", ")", ":", "has_bias", "=", "not", "literal_eval", "(", "param", "[", "'no_bias'", "]", ")", "else", ":", "has_bias", "=", "True", "if", "'pad'", "in", "param", ".", "keys", "(", ")", "and", "literal_eval", "(", "param", "[", "'pad'", "]", ")", "!=", "(", "0", ",", "0", ")", ":", "pad", "=", "literal_eval", "(", "param", "[", "'pad'", "]", ")", "builder", ".", "add_padding", "(", "name", "=", "name", "+", "\"_pad\"", ",", "left", "=", "pad", "[", "1", "]", ",", "right", "=", "pad", "[", "1", "]", ",", "top", "=", "pad", "[", "0", "]", ",", "bottom", "=", "pad", "[", "0", "]", ",", "value", "=", "0", ",", "input_name", "=", "input_name", ",", "output_name", "=", "name", "+", "\"_pad_output\"", ")", "input_name", "=", "name", "+", "\"_pad_output\"", "border_mode", "=", "\"valid\"", "n_filters", "=", "int", "(", "param", "[", "'num_filter'", "]", ")", "n_groups", "=", "int", "(", "param", "[", "'num_group'", "]", ")", "if", "'num_group'", "in", "param", "else", "1", "W", "=", "args", "[", "_get_node_name", "(", "net", ",", "inputs", "[", "1", "]", "[", "0", "]", ")", "]", ".", "asnumpy", "(", ")", "if", "has_bias", ":", "Wb", "=", "args", "[", "_get_node_name", "(", "net", ",", "inputs", "[", "2", "]", "[", "0", "]", ")", "]", ".", "asnumpy", "(", ")", "else", ":", "Wb", "=", "None", "channels", "=", "W", ".", "shape", "[", "1", "]", "stride_height", "=", "1", "stride_width", "=", "1", "if", "'stride'", "in", "param", ".", "keys", "(", ")", ":", "stride_height", ",", "stride_width", "=", "literal_eval", "(", "param", "[", "'stride'", "]", ")", "kernel_height", ",", "kernel_width", "=", "literal_eval", "(", "param", "[", "'kernel'", "]", ")", "W", "=", "W", ".", "transpose", "(", "(", "2", ",", "3", ",", "1", ",", "0", ")", ")", "builder", ".", "add_convolution", "(", "name", "=", "name", ",", "kernel_channels", "=", "channels", ",", "output_channels", "=", "n_filters", ",", "height", "=", "kernel_height", ",", "width", "=", "kernel_width", ",", "stride_height", "=", "stride_height", ",", "stride_width", "=", "stride_width", ",", "border_mode", "=", "border_mode", ",", "groups", "=", "n_groups", ",", "W", "=", "W", ",", "b", "=", "Wb", ",", "has_bias", "=", "has_bias", ",", "is_deconv", "=", "False", ",", "output_shape", "=", "None", ",", "input_name", "=", "input_name", ",", "output_name", "=", "output_name", ")" ]
Convert a convolution layer from mxnet to coreml. Parameters ---------- network: net A mxnet network object. layer: node Node to convert. module: module An module for MXNet builder: NeuralNetworkBuilder A neural network builder object.
[ "Convert", "a", "convolution", "layer", "from", "mxnet", "to", "coreml", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/tools/coreml/converter/_layers.py#L337-L415
23,716
apache/incubator-mxnet
tools/coreml/converter/_layers.py
convert_pooling
def convert_pooling(net, node, module, builder): """Convert a pooling layer from mxnet to coreml. Parameters ---------- network: net A mxnet network object. layer: node Node to convert. module: module An module for MXNet builder: NeuralNetworkBuilder A neural network builder object. """ input_name, output_name = _get_input_output_name(net, node) name = node['name'] param = _get_attrs(node) layer_type_mx = param['pool_type'] if layer_type_mx == 'max': layer_type = 'MAX' elif layer_type_mx == 'avg': layer_type = 'AVERAGE' else: raise TypeError("Pooling type %s not supported" % layer_type_mx) # Add padding if there is any if 'pad' in param.keys() and literal_eval(param['pad']) != (0, 0): pad = literal_eval(param['pad']) builder.add_padding( name=name+"_pad", left=pad[1], right=pad[1], top=pad[0], bottom=pad[0], value=0, input_name=input_name, output_name=name+"_pad_output") input_name = name+"_pad_output" stride_height = 1 stride_width = 1 if 'stride' in param.keys(): stride_height, stride_width = literal_eval(param['stride']) kernel_width, kernel_height = literal_eval(param['kernel']) type_map = {'valid': 'VALID', 'full': 'INCLUDE_LAST_PIXEL'} padding_type = param['pooling_convention'] if 'pooling_convention' in param else 'valid' if padding_type not in type_map: raise KeyError("%s type is not supported in this converter. It is a Github issue.") padding_type = type_map[padding_type] if 'global_pool' in param.keys(): is_global = literal_eval(param['global_pool']) else: is_global = False # For reasons why we are not using the standard builder but having our own implementation, # see the function documentation. _add_pooling.add_pooling_with_padding_types( builder=builder, name=name, height=kernel_height, width=kernel_width, stride_height=stride_height, stride_width=stride_width, layer_type=layer_type, padding_type=padding_type, exclude_pad_area=False, is_global=is_global, input_name=input_name, output_name=output_name )
python
def convert_pooling(net, node, module, builder): """Convert a pooling layer from mxnet to coreml. Parameters ---------- network: net A mxnet network object. layer: node Node to convert. module: module An module for MXNet builder: NeuralNetworkBuilder A neural network builder object. """ input_name, output_name = _get_input_output_name(net, node) name = node['name'] param = _get_attrs(node) layer_type_mx = param['pool_type'] if layer_type_mx == 'max': layer_type = 'MAX' elif layer_type_mx == 'avg': layer_type = 'AVERAGE' else: raise TypeError("Pooling type %s not supported" % layer_type_mx) # Add padding if there is any if 'pad' in param.keys() and literal_eval(param['pad']) != (0, 0): pad = literal_eval(param['pad']) builder.add_padding( name=name+"_pad", left=pad[1], right=pad[1], top=pad[0], bottom=pad[0], value=0, input_name=input_name, output_name=name+"_pad_output") input_name = name+"_pad_output" stride_height = 1 stride_width = 1 if 'stride' in param.keys(): stride_height, stride_width = literal_eval(param['stride']) kernel_width, kernel_height = literal_eval(param['kernel']) type_map = {'valid': 'VALID', 'full': 'INCLUDE_LAST_PIXEL'} padding_type = param['pooling_convention'] if 'pooling_convention' in param else 'valid' if padding_type not in type_map: raise KeyError("%s type is not supported in this converter. It is a Github issue.") padding_type = type_map[padding_type] if 'global_pool' in param.keys(): is_global = literal_eval(param['global_pool']) else: is_global = False # For reasons why we are not using the standard builder but having our own implementation, # see the function documentation. _add_pooling.add_pooling_with_padding_types( builder=builder, name=name, height=kernel_height, width=kernel_width, stride_height=stride_height, stride_width=stride_width, layer_type=layer_type, padding_type=padding_type, exclude_pad_area=False, is_global=is_global, input_name=input_name, output_name=output_name )
[ "def", "convert_pooling", "(", "net", ",", "node", ",", "module", ",", "builder", ")", ":", "input_name", ",", "output_name", "=", "_get_input_output_name", "(", "net", ",", "node", ")", "name", "=", "node", "[", "'name'", "]", "param", "=", "_get_attrs", "(", "node", ")", "layer_type_mx", "=", "param", "[", "'pool_type'", "]", "if", "layer_type_mx", "==", "'max'", ":", "layer_type", "=", "'MAX'", "elif", "layer_type_mx", "==", "'avg'", ":", "layer_type", "=", "'AVERAGE'", "else", ":", "raise", "TypeError", "(", "\"Pooling type %s not supported\"", "%", "layer_type_mx", ")", "# Add padding if there is any", "if", "'pad'", "in", "param", ".", "keys", "(", ")", "and", "literal_eval", "(", "param", "[", "'pad'", "]", ")", "!=", "(", "0", ",", "0", ")", ":", "pad", "=", "literal_eval", "(", "param", "[", "'pad'", "]", ")", "builder", ".", "add_padding", "(", "name", "=", "name", "+", "\"_pad\"", ",", "left", "=", "pad", "[", "1", "]", ",", "right", "=", "pad", "[", "1", "]", ",", "top", "=", "pad", "[", "0", "]", ",", "bottom", "=", "pad", "[", "0", "]", ",", "value", "=", "0", ",", "input_name", "=", "input_name", ",", "output_name", "=", "name", "+", "\"_pad_output\"", ")", "input_name", "=", "name", "+", "\"_pad_output\"", "stride_height", "=", "1", "stride_width", "=", "1", "if", "'stride'", "in", "param", ".", "keys", "(", ")", ":", "stride_height", ",", "stride_width", "=", "literal_eval", "(", "param", "[", "'stride'", "]", ")", "kernel_width", ",", "kernel_height", "=", "literal_eval", "(", "param", "[", "'kernel'", "]", ")", "type_map", "=", "{", "'valid'", ":", "'VALID'", ",", "'full'", ":", "'INCLUDE_LAST_PIXEL'", "}", "padding_type", "=", "param", "[", "'pooling_convention'", "]", "if", "'pooling_convention'", "in", "param", "else", "'valid'", "if", "padding_type", "not", "in", "type_map", ":", "raise", "KeyError", "(", "\"%s type is not supported in this converter. It is a Github issue.\"", ")", "padding_type", "=", "type_map", "[", "padding_type", "]", "if", "'global_pool'", "in", "param", ".", "keys", "(", ")", ":", "is_global", "=", "literal_eval", "(", "param", "[", "'global_pool'", "]", ")", "else", ":", "is_global", "=", "False", "# For reasons why we are not using the standard builder but having our own implementation,", "# see the function documentation.", "_add_pooling", ".", "add_pooling_with_padding_types", "(", "builder", "=", "builder", ",", "name", "=", "name", ",", "height", "=", "kernel_height", ",", "width", "=", "kernel_width", ",", "stride_height", "=", "stride_height", ",", "stride_width", "=", "stride_width", ",", "layer_type", "=", "layer_type", ",", "padding_type", "=", "padding_type", ",", "exclude_pad_area", "=", "False", ",", "is_global", "=", "is_global", ",", "input_name", "=", "input_name", ",", "output_name", "=", "output_name", ")" ]
Convert a pooling layer from mxnet to coreml. Parameters ---------- network: net A mxnet network object. layer: node Node to convert. module: module An module for MXNet builder: NeuralNetworkBuilder A neural network builder object.
[ "Convert", "a", "pooling", "layer", "from", "mxnet", "to", "coreml", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/tools/coreml/converter/_layers.py#L418-L494
23,717
apache/incubator-mxnet
tools/coreml/converter/_layers.py
convert_batchnorm
def convert_batchnorm(net, node, module, builder): """Convert a batchnorm layer from mxnet to coreml. Parameters ---------- network: net A mxnet network object. layer: node Node to convert. module: module An module for MXNet builder: NeuralNetworkBuilder A neural network builder object. """ input_name, output_name = _get_input_output_name(net, node) name = node['name'] inputs = node['inputs'] eps = 1e-3 # Default value of eps for MXNet. use_global_stats = False # Default value of use_global_stats for MXNet. fix_gamma = True # Default value of fix_gamma for MXNet. attrs = _get_attrs(node) if 'eps' in attrs: eps = literal_eval(attrs['eps']) if 'fix_gamma' in attrs: fix_gamma = literal_eval(attrs['fix_gamma']) args, aux = module.get_params() gamma = args[_get_node_name(net, inputs[1][0])].asnumpy() beta = args[_get_node_name(net, inputs[2][0])].asnumpy() mean = aux[_get_node_name(net, inputs[3][0])].asnumpy() variance = aux[_get_node_name(net, inputs[4][0])].asnumpy() nb_channels = gamma.shape[0] if fix_gamma: gamma.fill(1.) builder.add_batchnorm( name=name, channels=nb_channels, gamma=gamma, beta=beta, mean=mean, variance=variance, input_name=input_name, output_name=output_name, epsilon=eps)
python
def convert_batchnorm(net, node, module, builder): """Convert a batchnorm layer from mxnet to coreml. Parameters ---------- network: net A mxnet network object. layer: node Node to convert. module: module An module for MXNet builder: NeuralNetworkBuilder A neural network builder object. """ input_name, output_name = _get_input_output_name(net, node) name = node['name'] inputs = node['inputs'] eps = 1e-3 # Default value of eps for MXNet. use_global_stats = False # Default value of use_global_stats for MXNet. fix_gamma = True # Default value of fix_gamma for MXNet. attrs = _get_attrs(node) if 'eps' in attrs: eps = literal_eval(attrs['eps']) if 'fix_gamma' in attrs: fix_gamma = literal_eval(attrs['fix_gamma']) args, aux = module.get_params() gamma = args[_get_node_name(net, inputs[1][0])].asnumpy() beta = args[_get_node_name(net, inputs[2][0])].asnumpy() mean = aux[_get_node_name(net, inputs[3][0])].asnumpy() variance = aux[_get_node_name(net, inputs[4][0])].asnumpy() nb_channels = gamma.shape[0] if fix_gamma: gamma.fill(1.) builder.add_batchnorm( name=name, channels=nb_channels, gamma=gamma, beta=beta, mean=mean, variance=variance, input_name=input_name, output_name=output_name, epsilon=eps)
[ "def", "convert_batchnorm", "(", "net", ",", "node", ",", "module", ",", "builder", ")", ":", "input_name", ",", "output_name", "=", "_get_input_output_name", "(", "net", ",", "node", ")", "name", "=", "node", "[", "'name'", "]", "inputs", "=", "node", "[", "'inputs'", "]", "eps", "=", "1e-3", "# Default value of eps for MXNet.", "use_global_stats", "=", "False", "# Default value of use_global_stats for MXNet.", "fix_gamma", "=", "True", "# Default value of fix_gamma for MXNet.", "attrs", "=", "_get_attrs", "(", "node", ")", "if", "'eps'", "in", "attrs", ":", "eps", "=", "literal_eval", "(", "attrs", "[", "'eps'", "]", ")", "if", "'fix_gamma'", "in", "attrs", ":", "fix_gamma", "=", "literal_eval", "(", "attrs", "[", "'fix_gamma'", "]", ")", "args", ",", "aux", "=", "module", ".", "get_params", "(", ")", "gamma", "=", "args", "[", "_get_node_name", "(", "net", ",", "inputs", "[", "1", "]", "[", "0", "]", ")", "]", ".", "asnumpy", "(", ")", "beta", "=", "args", "[", "_get_node_name", "(", "net", ",", "inputs", "[", "2", "]", "[", "0", "]", ")", "]", ".", "asnumpy", "(", ")", "mean", "=", "aux", "[", "_get_node_name", "(", "net", ",", "inputs", "[", "3", "]", "[", "0", "]", ")", "]", ".", "asnumpy", "(", ")", "variance", "=", "aux", "[", "_get_node_name", "(", "net", ",", "inputs", "[", "4", "]", "[", "0", "]", ")", "]", ".", "asnumpy", "(", ")", "nb_channels", "=", "gamma", ".", "shape", "[", "0", "]", "if", "fix_gamma", ":", "gamma", ".", "fill", "(", "1.", ")", "builder", ".", "add_batchnorm", "(", "name", "=", "name", ",", "channels", "=", "nb_channels", ",", "gamma", "=", "gamma", ",", "beta", "=", "beta", ",", "mean", "=", "mean", ",", "variance", "=", "variance", ",", "input_name", "=", "input_name", ",", "output_name", "=", "output_name", ",", "epsilon", "=", "eps", ")" ]
Convert a batchnorm layer from mxnet to coreml. Parameters ---------- network: net A mxnet network object. layer: node Node to convert. module: module An module for MXNet builder: NeuralNetworkBuilder A neural network builder object.
[ "Convert", "a", "batchnorm", "layer", "from", "mxnet", "to", "coreml", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/tools/coreml/converter/_layers.py#L497-L545
23,718
apache/incubator-mxnet
tools/coreml/converter/_layers.py
convert_concat
def convert_concat(net, node, module, builder): """Convert concat layer from mxnet to coreml. Parameters ---------- network: net A mxnet network object. layer: node Node to convert. module: module An module for MXNet builder: NeuralNetworkBuilder A neural network builder object. """ # Get input and output names input_names, output_name = _get_input_output_name(net, node, 'all') name = node['name'] mode = 'CONCAT' builder.add_elementwise(name = name, input_names = input_names, output_name = output_name, mode = mode)
python
def convert_concat(net, node, module, builder): """Convert concat layer from mxnet to coreml. Parameters ---------- network: net A mxnet network object. layer: node Node to convert. module: module An module for MXNet builder: NeuralNetworkBuilder A neural network builder object. """ # Get input and output names input_names, output_name = _get_input_output_name(net, node, 'all') name = node['name'] mode = 'CONCAT' builder.add_elementwise(name = name, input_names = input_names, output_name = output_name, mode = mode)
[ "def", "convert_concat", "(", "net", ",", "node", ",", "module", ",", "builder", ")", ":", "# Get input and output names", "input_names", ",", "output_name", "=", "_get_input_output_name", "(", "net", ",", "node", ",", "'all'", ")", "name", "=", "node", "[", "'name'", "]", "mode", "=", "'CONCAT'", "builder", ".", "add_elementwise", "(", "name", "=", "name", ",", "input_names", "=", "input_names", ",", "output_name", "=", "output_name", ",", "mode", "=", "mode", ")" ]
Convert concat layer from mxnet to coreml. Parameters ---------- network: net A mxnet network object. layer: node Node to convert. module: module An module for MXNet builder: NeuralNetworkBuilder A neural network builder object.
[ "Convert", "concat", "layer", "from", "mxnet", "to", "coreml", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/tools/coreml/converter/_layers.py#L548-L570
23,719
apache/incubator-mxnet
tools/launch.py
dmlc_opts
def dmlc_opts(opts): """convert from mxnet's opts to dmlc's opts """ args = ['--num-workers', str(opts.num_workers), '--num-servers', str(opts.num_servers), '--cluster', opts.launcher, '--host-file', opts.hostfile, '--sync-dst-dir', opts.sync_dst_dir] # convert to dictionary dopts = vars(opts) for key in ['env_server', 'env_worker', 'env']: for v in dopts[key]: args.append('--' + key.replace("_","-")) args.append(v) args += opts.command try: from dmlc_tracker import opts except ImportError: print("Can't load dmlc_tracker package. Perhaps you need to run") print(" git submodule update --init --recursive") raise dmlc_opts = opts.get_opts(args) return dmlc_opts
python
def dmlc_opts(opts): """convert from mxnet's opts to dmlc's opts """ args = ['--num-workers', str(opts.num_workers), '--num-servers', str(opts.num_servers), '--cluster', opts.launcher, '--host-file', opts.hostfile, '--sync-dst-dir', opts.sync_dst_dir] # convert to dictionary dopts = vars(opts) for key in ['env_server', 'env_worker', 'env']: for v in dopts[key]: args.append('--' + key.replace("_","-")) args.append(v) args += opts.command try: from dmlc_tracker import opts except ImportError: print("Can't load dmlc_tracker package. Perhaps you need to run") print(" git submodule update --init --recursive") raise dmlc_opts = opts.get_opts(args) return dmlc_opts
[ "def", "dmlc_opts", "(", "opts", ")", ":", "args", "=", "[", "'--num-workers'", ",", "str", "(", "opts", ".", "num_workers", ")", ",", "'--num-servers'", ",", "str", "(", "opts", ".", "num_servers", ")", ",", "'--cluster'", ",", "opts", ".", "launcher", ",", "'--host-file'", ",", "opts", ".", "hostfile", ",", "'--sync-dst-dir'", ",", "opts", ".", "sync_dst_dir", "]", "# convert to dictionary", "dopts", "=", "vars", "(", "opts", ")", "for", "key", "in", "[", "'env_server'", ",", "'env_worker'", ",", "'env'", "]", ":", "for", "v", "in", "dopts", "[", "key", "]", ":", "args", ".", "append", "(", "'--'", "+", "key", ".", "replace", "(", "\"_\"", ",", "\"-\"", ")", ")", "args", ".", "append", "(", "v", ")", "args", "+=", "opts", ".", "command", "try", ":", "from", "dmlc_tracker", "import", "opts", "except", "ImportError", ":", "print", "(", "\"Can't load dmlc_tracker package. Perhaps you need to run\"", ")", "print", "(", "\" git submodule update --init --recursive\"", ")", "raise", "dmlc_opts", "=", "opts", ".", "get_opts", "(", "args", ")", "return", "dmlc_opts" ]
convert from mxnet's opts to dmlc's opts
[ "convert", "from", "mxnet", "s", "opts", "to", "dmlc", "s", "opts" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/tools/launch.py#L31-L54
23,720
apache/incubator-mxnet
python/mxnet/gluon/rnn/rnn_layer.py
_RNNLayer._unfuse
def _unfuse(self): """Unfuses the fused RNN in to a stack of rnn cells.""" assert not self._projection_size, "_unfuse does not support projection layer yet!" assert not self._lstm_state_clip_min and not self._lstm_state_clip_max, \ "_unfuse does not support state clipping yet!" get_cell = {'rnn_relu': lambda **kwargs: rnn_cell.RNNCell(self._hidden_size, activation='relu', **kwargs), 'rnn_tanh': lambda **kwargs: rnn_cell.RNNCell(self._hidden_size, activation='tanh', **kwargs), 'lstm': lambda **kwargs: rnn_cell.LSTMCell(self._hidden_size, **kwargs), 'gru': lambda **kwargs: rnn_cell.GRUCell(self._hidden_size, **kwargs)}[self._mode] stack = rnn_cell.HybridSequentialRNNCell(prefix=self.prefix, params=self.params) with stack.name_scope(): ni = self._input_size for i in range(self._num_layers): kwargs = {'input_size': ni, 'i2h_weight_initializer': self._i2h_weight_initializer, 'h2h_weight_initializer': self._h2h_weight_initializer, 'i2h_bias_initializer': self._i2h_bias_initializer, 'h2h_bias_initializer': self._h2h_bias_initializer} if self._dir == 2: stack.add(rnn_cell.BidirectionalCell( get_cell(prefix='l%d_'%i, **kwargs), get_cell(prefix='r%d_'%i, **kwargs))) else: stack.add(get_cell(prefix='l%d_'%i, **kwargs)) if self._dropout > 0 and i != self._num_layers - 1: stack.add(rnn_cell.DropoutCell(self._dropout)) ni = self._hidden_size * self._dir return stack
python
def _unfuse(self): """Unfuses the fused RNN in to a stack of rnn cells.""" assert not self._projection_size, "_unfuse does not support projection layer yet!" assert not self._lstm_state_clip_min and not self._lstm_state_clip_max, \ "_unfuse does not support state clipping yet!" get_cell = {'rnn_relu': lambda **kwargs: rnn_cell.RNNCell(self._hidden_size, activation='relu', **kwargs), 'rnn_tanh': lambda **kwargs: rnn_cell.RNNCell(self._hidden_size, activation='tanh', **kwargs), 'lstm': lambda **kwargs: rnn_cell.LSTMCell(self._hidden_size, **kwargs), 'gru': lambda **kwargs: rnn_cell.GRUCell(self._hidden_size, **kwargs)}[self._mode] stack = rnn_cell.HybridSequentialRNNCell(prefix=self.prefix, params=self.params) with stack.name_scope(): ni = self._input_size for i in range(self._num_layers): kwargs = {'input_size': ni, 'i2h_weight_initializer': self._i2h_weight_initializer, 'h2h_weight_initializer': self._h2h_weight_initializer, 'i2h_bias_initializer': self._i2h_bias_initializer, 'h2h_bias_initializer': self._h2h_bias_initializer} if self._dir == 2: stack.add(rnn_cell.BidirectionalCell( get_cell(prefix='l%d_'%i, **kwargs), get_cell(prefix='r%d_'%i, **kwargs))) else: stack.add(get_cell(prefix='l%d_'%i, **kwargs)) if self._dropout > 0 and i != self._num_layers - 1: stack.add(rnn_cell.DropoutCell(self._dropout)) ni = self._hidden_size * self._dir return stack
[ "def", "_unfuse", "(", "self", ")", ":", "assert", "not", "self", ".", "_projection_size", ",", "\"_unfuse does not support projection layer yet!\"", "assert", "not", "self", ".", "_lstm_state_clip_min", "and", "not", "self", ".", "_lstm_state_clip_max", ",", "\"_unfuse does not support state clipping yet!\"", "get_cell", "=", "{", "'rnn_relu'", ":", "lambda", "*", "*", "kwargs", ":", "rnn_cell", ".", "RNNCell", "(", "self", ".", "_hidden_size", ",", "activation", "=", "'relu'", ",", "*", "*", "kwargs", ")", ",", "'rnn_tanh'", ":", "lambda", "*", "*", "kwargs", ":", "rnn_cell", ".", "RNNCell", "(", "self", ".", "_hidden_size", ",", "activation", "=", "'tanh'", ",", "*", "*", "kwargs", ")", ",", "'lstm'", ":", "lambda", "*", "*", "kwargs", ":", "rnn_cell", ".", "LSTMCell", "(", "self", ".", "_hidden_size", ",", "*", "*", "kwargs", ")", ",", "'gru'", ":", "lambda", "*", "*", "kwargs", ":", "rnn_cell", ".", "GRUCell", "(", "self", ".", "_hidden_size", ",", "*", "*", "kwargs", ")", "}", "[", "self", ".", "_mode", "]", "stack", "=", "rnn_cell", ".", "HybridSequentialRNNCell", "(", "prefix", "=", "self", ".", "prefix", ",", "params", "=", "self", ".", "params", ")", "with", "stack", ".", "name_scope", "(", ")", ":", "ni", "=", "self", ".", "_input_size", "for", "i", "in", "range", "(", "self", ".", "_num_layers", ")", ":", "kwargs", "=", "{", "'input_size'", ":", "ni", ",", "'i2h_weight_initializer'", ":", "self", ".", "_i2h_weight_initializer", ",", "'h2h_weight_initializer'", ":", "self", ".", "_h2h_weight_initializer", ",", "'i2h_bias_initializer'", ":", "self", ".", "_i2h_bias_initializer", ",", "'h2h_bias_initializer'", ":", "self", ".", "_h2h_bias_initializer", "}", "if", "self", ".", "_dir", "==", "2", ":", "stack", ".", "add", "(", "rnn_cell", ".", "BidirectionalCell", "(", "get_cell", "(", "prefix", "=", "'l%d_'", "%", "i", ",", "*", "*", "kwargs", ")", ",", "get_cell", "(", "prefix", "=", "'r%d_'", "%", "i", ",", "*", "*", "kwargs", ")", ")", ")", "else", ":", "stack", ".", "add", "(", "get_cell", "(", "prefix", "=", "'l%d_'", "%", "i", ",", "*", "*", "kwargs", ")", ")", "if", "self", ".", "_dropout", ">", "0", "and", "i", "!=", "self", ".", "_num_layers", "-", "1", ":", "stack", ".", "add", "(", "rnn_cell", ".", "DropoutCell", "(", "self", ".", "_dropout", ")", ")", "ni", "=", "self", ".", "_hidden_size", "*", "self", ".", "_dir", "return", "stack" ]
Unfuses the fused RNN in to a stack of rnn cells.
[ "Unfuses", "the", "fused", "RNN", "in", "to", "a", "stack", "of", "rnn", "cells", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/gluon/rnn/rnn_layer.py#L144-L181
23,721
apache/incubator-mxnet
python/mxnet/gluon/rnn/rnn_layer.py
_RNNLayer._forward_kernel
def _forward_kernel(self, F, inputs, states, **kwargs): """ forward using CUDNN or CPU kenrel""" if self._layout == 'NTC': inputs = F.swapaxes(inputs, dim1=0, dim2=1) if self._projection_size is None: params = (kwargs['{}{}_{}_{}'.format(d, l, g, t)].reshape(-1) for t in ['weight', 'bias'] for l in range(self._num_layers) for d in ['l', 'r'][:self._dir] for g in ['i2h', 'h2h']) else: params = (kwargs['{}{}_{}_{}'.format(d, l, g, t)].reshape(-1) for t in ['weight', 'bias'] for l in range(self._num_layers) for d in ['l', 'r'][:self._dir] for g in ['i2h', 'h2h', 'h2r'] if g != 'h2r' or t != 'bias') params = F._internal._rnn_param_concat(*params, dim=0) rnn = F.RNN(inputs, params, *states, state_size=self._hidden_size, projection_size=self._projection_size, num_layers=self._num_layers, bidirectional=self._dir == 2, p=self._dropout, state_outputs=True, mode=self._mode, lstm_state_clip_min=self._lstm_state_clip_min, lstm_state_clip_max=self._lstm_state_clip_max, lstm_state_clip_nan=self._lstm_state_clip_nan) if self._mode == 'lstm': outputs, states = rnn[0], [rnn[1], rnn[2]] else: outputs, states = rnn[0], [rnn[1]] if self._layout == 'NTC': outputs = F.swapaxes(outputs, dim1=0, dim2=1) return outputs, states
python
def _forward_kernel(self, F, inputs, states, **kwargs): """ forward using CUDNN or CPU kenrel""" if self._layout == 'NTC': inputs = F.swapaxes(inputs, dim1=0, dim2=1) if self._projection_size is None: params = (kwargs['{}{}_{}_{}'.format(d, l, g, t)].reshape(-1) for t in ['weight', 'bias'] for l in range(self._num_layers) for d in ['l', 'r'][:self._dir] for g in ['i2h', 'h2h']) else: params = (kwargs['{}{}_{}_{}'.format(d, l, g, t)].reshape(-1) for t in ['weight', 'bias'] for l in range(self._num_layers) for d in ['l', 'r'][:self._dir] for g in ['i2h', 'h2h', 'h2r'] if g != 'h2r' or t != 'bias') params = F._internal._rnn_param_concat(*params, dim=0) rnn = F.RNN(inputs, params, *states, state_size=self._hidden_size, projection_size=self._projection_size, num_layers=self._num_layers, bidirectional=self._dir == 2, p=self._dropout, state_outputs=True, mode=self._mode, lstm_state_clip_min=self._lstm_state_clip_min, lstm_state_clip_max=self._lstm_state_clip_max, lstm_state_clip_nan=self._lstm_state_clip_nan) if self._mode == 'lstm': outputs, states = rnn[0], [rnn[1], rnn[2]] else: outputs, states = rnn[0], [rnn[1]] if self._layout == 'NTC': outputs = F.swapaxes(outputs, dim1=0, dim2=1) return outputs, states
[ "def", "_forward_kernel", "(", "self", ",", "F", ",", "inputs", ",", "states", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "_layout", "==", "'NTC'", ":", "inputs", "=", "F", ".", "swapaxes", "(", "inputs", ",", "dim1", "=", "0", ",", "dim2", "=", "1", ")", "if", "self", ".", "_projection_size", "is", "None", ":", "params", "=", "(", "kwargs", "[", "'{}{}_{}_{}'", ".", "format", "(", "d", ",", "l", ",", "g", ",", "t", ")", "]", ".", "reshape", "(", "-", "1", ")", "for", "t", "in", "[", "'weight'", ",", "'bias'", "]", "for", "l", "in", "range", "(", "self", ".", "_num_layers", ")", "for", "d", "in", "[", "'l'", ",", "'r'", "]", "[", ":", "self", ".", "_dir", "]", "for", "g", "in", "[", "'i2h'", ",", "'h2h'", "]", ")", "else", ":", "params", "=", "(", "kwargs", "[", "'{}{}_{}_{}'", ".", "format", "(", "d", ",", "l", ",", "g", ",", "t", ")", "]", ".", "reshape", "(", "-", "1", ")", "for", "t", "in", "[", "'weight'", ",", "'bias'", "]", "for", "l", "in", "range", "(", "self", ".", "_num_layers", ")", "for", "d", "in", "[", "'l'", ",", "'r'", "]", "[", ":", "self", ".", "_dir", "]", "for", "g", "in", "[", "'i2h'", ",", "'h2h'", ",", "'h2r'", "]", "if", "g", "!=", "'h2r'", "or", "t", "!=", "'bias'", ")", "params", "=", "F", ".", "_internal", ".", "_rnn_param_concat", "(", "*", "params", ",", "dim", "=", "0", ")", "rnn", "=", "F", ".", "RNN", "(", "inputs", ",", "params", ",", "*", "states", ",", "state_size", "=", "self", ".", "_hidden_size", ",", "projection_size", "=", "self", ".", "_projection_size", ",", "num_layers", "=", "self", ".", "_num_layers", ",", "bidirectional", "=", "self", ".", "_dir", "==", "2", ",", "p", "=", "self", ".", "_dropout", ",", "state_outputs", "=", "True", ",", "mode", "=", "self", ".", "_mode", ",", "lstm_state_clip_min", "=", "self", ".", "_lstm_state_clip_min", ",", "lstm_state_clip_max", "=", "self", ".", "_lstm_state_clip_max", ",", "lstm_state_clip_nan", "=", "self", ".", "_lstm_state_clip_nan", ")", "if", "self", ".", "_mode", "==", "'lstm'", ":", "outputs", ",", "states", "=", "rnn", "[", "0", "]", ",", "[", "rnn", "[", "1", "]", ",", "rnn", "[", "2", "]", "]", "else", ":", "outputs", ",", "states", "=", "rnn", "[", "0", "]", ",", "[", "rnn", "[", "1", "]", "]", "if", "self", ".", "_layout", "==", "'NTC'", ":", "outputs", "=", "F", ".", "swapaxes", "(", "outputs", ",", "dim1", "=", "0", ",", "dim2", "=", "1", ")", "return", "outputs", ",", "states" ]
forward using CUDNN or CPU kenrel
[ "forward", "using", "CUDNN", "or", "CPU", "kenrel" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/gluon/rnn/rnn_layer.py#L244-L280
23,722
apache/incubator-mxnet
example/distributed_training/cifar10_dist.py
evaluate_accuracy
def evaluate_accuracy(data_iterator, network): """ Measure the accuracy of ResNet Parameters ---------- data_iterator: Iter examples of dataset network: ResNet Returns ---------- tuple of array element """ acc = mx.metric.Accuracy() # Iterate through data and label for i, (data, label) in enumerate(data_iterator): # Get the data and label into the GPU data = data.as_in_context(ctx[0]) label = label.as_in_context(ctx[0]) # Get network's output which is a probability distribution # Apply argmax on the probability distribution to get network's classification. output = network(data) predictions = nd.argmax(output, axis=1) # Give network's prediction and the correct label to update the metric acc.update(preds=predictions, labels=label) # Return the accuracy return acc.get()[1]
python
def evaluate_accuracy(data_iterator, network): """ Measure the accuracy of ResNet Parameters ---------- data_iterator: Iter examples of dataset network: ResNet Returns ---------- tuple of array element """ acc = mx.metric.Accuracy() # Iterate through data and label for i, (data, label) in enumerate(data_iterator): # Get the data and label into the GPU data = data.as_in_context(ctx[0]) label = label.as_in_context(ctx[0]) # Get network's output which is a probability distribution # Apply argmax on the probability distribution to get network's classification. output = network(data) predictions = nd.argmax(output, axis=1) # Give network's prediction and the correct label to update the metric acc.update(preds=predictions, labels=label) # Return the accuracy return acc.get()[1]
[ "def", "evaluate_accuracy", "(", "data_iterator", ",", "network", ")", ":", "acc", "=", "mx", ".", "metric", ".", "Accuracy", "(", ")", "# Iterate through data and label", "for", "i", ",", "(", "data", ",", "label", ")", "in", "enumerate", "(", "data_iterator", ")", ":", "# Get the data and label into the GPU", "data", "=", "data", ".", "as_in_context", "(", "ctx", "[", "0", "]", ")", "label", "=", "label", ".", "as_in_context", "(", "ctx", "[", "0", "]", ")", "# Get network's output which is a probability distribution", "# Apply argmax on the probability distribution to get network's classification.", "output", "=", "network", "(", "data", ")", "predictions", "=", "nd", ".", "argmax", "(", "output", ",", "axis", "=", "1", ")", "# Give network's prediction and the correct label to update the metric", "acc", ".", "update", "(", "preds", "=", "predictions", ",", "labels", "=", "label", ")", "# Return the accuracy", "return", "acc", ".", "get", "(", ")", "[", "1", "]" ]
Measure the accuracy of ResNet Parameters ---------- data_iterator: Iter examples of dataset network: ResNet Returns ---------- tuple of array element
[ "Measure", "the", "accuracy", "of", "ResNet" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/distributed_training/cifar10_dist.py#L110-L142
23,723
apache/incubator-mxnet
example/distributed_training/cifar10_dist.py
train_batch
def train_batch(batch_list, context, network, gluon_trainer): """ Training with multiple GPUs Parameters ---------- batch_list: List list of dataset context: List a list of all GPUs to be used for training network: ResNet gluon_trainer: rain module of gluon """ # Split and load data into multiple GPUs data = batch_list[0] data = gluon.utils.split_and_load(data, context) # Split and load label into multiple GPUs label = batch_list[1] label = gluon.utils.split_and_load(label, context) # Run the forward and backward pass forward_backward(network, data, label) # Update the parameters this_batch_size = batch_list[0].shape[0] gluon_trainer.step(this_batch_size)
python
def train_batch(batch_list, context, network, gluon_trainer): """ Training with multiple GPUs Parameters ---------- batch_list: List list of dataset context: List a list of all GPUs to be used for training network: ResNet gluon_trainer: rain module of gluon """ # Split and load data into multiple GPUs data = batch_list[0] data = gluon.utils.split_and_load(data, context) # Split and load label into multiple GPUs label = batch_list[1] label = gluon.utils.split_and_load(label, context) # Run the forward and backward pass forward_backward(network, data, label) # Update the parameters this_batch_size = batch_list[0].shape[0] gluon_trainer.step(this_batch_size)
[ "def", "train_batch", "(", "batch_list", ",", "context", ",", "network", ",", "gluon_trainer", ")", ":", "# Split and load data into multiple GPUs", "data", "=", "batch_list", "[", "0", "]", "data", "=", "gluon", ".", "utils", ".", "split_and_load", "(", "data", ",", "context", ")", "# Split and load label into multiple GPUs", "label", "=", "batch_list", "[", "1", "]", "label", "=", "gluon", ".", "utils", ".", "split_and_load", "(", "label", ",", "context", ")", "# Run the forward and backward pass", "forward_backward", "(", "network", ",", "data", ",", "label", ")", "# Update the parameters", "this_batch_size", "=", "batch_list", "[", "0", "]", ".", "shape", "[", "0", "]", "gluon_trainer", ".", "step", "(", "this_batch_size", ")" ]
Training with multiple GPUs Parameters ---------- batch_list: List list of dataset context: List a list of all GPUs to be used for training network: ResNet gluon_trainer: rain module of gluon
[ "Training", "with", "multiple", "GPUs" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/distributed_training/cifar10_dist.py#L163-L190
23,724
apache/incubator-mxnet
python/mxnet/contrib/tensorrt.py
get_optimized_symbol
def get_optimized_symbol(executor): """ Take an executor's underlying symbol graph and return its generated optimized version. Parameters ---------- executor : An executor for which you want to see an optimized symbol. Getting an optimized symbol is useful to compare and verify the work TensorRT has done against a legacy behaviour. Returns ------- symbol : nnvm::Symbol The nnvm symbol optimized. """ handle = SymbolHandle() try: check_call(_LIB.MXExecutorGetOptimizedSymbol(executor.handle, ctypes.byref(handle))) result = sym.Symbol(handle=handle) return result except MXNetError: logging.error('Error while trying to fetch TRT optimized symbol for graph. Please ensure ' 'build was compiled with MXNET_USE_TENSORRT enabled.') raise
python
def get_optimized_symbol(executor): """ Take an executor's underlying symbol graph and return its generated optimized version. Parameters ---------- executor : An executor for which you want to see an optimized symbol. Getting an optimized symbol is useful to compare and verify the work TensorRT has done against a legacy behaviour. Returns ------- symbol : nnvm::Symbol The nnvm symbol optimized. """ handle = SymbolHandle() try: check_call(_LIB.MXExecutorGetOptimizedSymbol(executor.handle, ctypes.byref(handle))) result = sym.Symbol(handle=handle) return result except MXNetError: logging.error('Error while trying to fetch TRT optimized symbol for graph. Please ensure ' 'build was compiled with MXNET_USE_TENSORRT enabled.') raise
[ "def", "get_optimized_symbol", "(", "executor", ")", ":", "handle", "=", "SymbolHandle", "(", ")", "try", ":", "check_call", "(", "_LIB", ".", "MXExecutorGetOptimizedSymbol", "(", "executor", ".", "handle", ",", "ctypes", ".", "byref", "(", "handle", ")", ")", ")", "result", "=", "sym", ".", "Symbol", "(", "handle", "=", "handle", ")", "return", "result", "except", "MXNetError", ":", "logging", ".", "error", "(", "'Error while trying to fetch TRT optimized symbol for graph. Please ensure '", "'build was compiled with MXNET_USE_TENSORRT enabled.'", ")", "raise" ]
Take an executor's underlying symbol graph and return its generated optimized version. Parameters ---------- executor : An executor for which you want to see an optimized symbol. Getting an optimized symbol is useful to compare and verify the work TensorRT has done against a legacy behaviour. Returns ------- symbol : nnvm::Symbol The nnvm symbol optimized.
[ "Take", "an", "executor", "s", "underlying", "symbol", "graph", "and", "return", "its", "generated", "optimized", "version", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/contrib/tensorrt.py#L50-L73
23,725
apache/incubator-mxnet
python/mxnet/contrib/tensorrt.py
tensorrt_bind
def tensorrt_bind(symbol, ctx, all_params, type_dict=None, stype_dict=None, group2ctx=None, **kwargs): """Bind current symbol to get an optimized trt executor. Parameters ---------- symbol : Symbol The symbol you wish to bind, and optimize with TensorRT. ctx : Context The device context the generated executor to run on. all_params : Dict of str->ndarray A dictionary of mappings from parameter names to parameter NDArrays. type_dict : Dict of str->numpy.dtype Input type dictionary, name->dtype stype_dict : Dict of str->str Input storage type dictionary, name->storage_type group2ctx : Dict of string to mx.Context The dict mapping the `ctx_group` attribute to the context assignment. kwargs : Dict of str->shape Input shape dictionary, name->shape Returns ------- executor : mxnet.Executor An optimized TensorRT executor. """ kwargs['shared_buffer'] = all_params return symbol.simple_bind(ctx, type_dict=type_dict, stype_dict=stype_dict, group2ctx=group2ctx, **kwargs)
python
def tensorrt_bind(symbol, ctx, all_params, type_dict=None, stype_dict=None, group2ctx=None, **kwargs): """Bind current symbol to get an optimized trt executor. Parameters ---------- symbol : Symbol The symbol you wish to bind, and optimize with TensorRT. ctx : Context The device context the generated executor to run on. all_params : Dict of str->ndarray A dictionary of mappings from parameter names to parameter NDArrays. type_dict : Dict of str->numpy.dtype Input type dictionary, name->dtype stype_dict : Dict of str->str Input storage type dictionary, name->storage_type group2ctx : Dict of string to mx.Context The dict mapping the `ctx_group` attribute to the context assignment. kwargs : Dict of str->shape Input shape dictionary, name->shape Returns ------- executor : mxnet.Executor An optimized TensorRT executor. """ kwargs['shared_buffer'] = all_params return symbol.simple_bind(ctx, type_dict=type_dict, stype_dict=stype_dict, group2ctx=group2ctx, **kwargs)
[ "def", "tensorrt_bind", "(", "symbol", ",", "ctx", ",", "all_params", ",", "type_dict", "=", "None", ",", "stype_dict", "=", "None", ",", "group2ctx", "=", "None", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'shared_buffer'", "]", "=", "all_params", "return", "symbol", ".", "simple_bind", "(", "ctx", ",", "type_dict", "=", "type_dict", ",", "stype_dict", "=", "stype_dict", ",", "group2ctx", "=", "group2ctx", ",", "*", "*", "kwargs", ")" ]
Bind current symbol to get an optimized trt executor. Parameters ---------- symbol : Symbol The symbol you wish to bind, and optimize with TensorRT. ctx : Context The device context the generated executor to run on. all_params : Dict of str->ndarray A dictionary of mappings from parameter names to parameter NDArrays. type_dict : Dict of str->numpy.dtype Input type dictionary, name->dtype stype_dict : Dict of str->str Input storage type dictionary, name->storage_type group2ctx : Dict of string to mx.Context The dict mapping the `ctx_group` attribute to the context assignment. kwargs : Dict of str->shape Input shape dictionary, name->shape Returns ------- executor : mxnet.Executor An optimized TensorRT executor.
[ "Bind", "current", "symbol", "to", "get", "an", "optimized", "trt", "executor", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/contrib/tensorrt.py#L76-L110
23,726
apache/incubator-mxnet
example/ssd/detect/detector.py
Detector.detect_iter
def detect_iter(self, det_iter, show_timer=False): """ detect all images in iterator Parameters: ---------- det_iter : DetIter iterator for all testing images show_timer : Boolean whether to print out detection exec time Returns: ---------- list of detection results """ num_images = det_iter._size if not isinstance(det_iter, mx.io.PrefetchingIter): det_iter = mx.io.PrefetchingIter(det_iter) start = timer() detections = self.mod.predict(det_iter).asnumpy() time_elapsed = timer() - start if show_timer: logging.info("Detection time for {} images: {:.4f} sec".format( num_images, time_elapsed)) result = Detector.filter_positive_detections(detections) return result
python
def detect_iter(self, det_iter, show_timer=False): """ detect all images in iterator Parameters: ---------- det_iter : DetIter iterator for all testing images show_timer : Boolean whether to print out detection exec time Returns: ---------- list of detection results """ num_images = det_iter._size if not isinstance(det_iter, mx.io.PrefetchingIter): det_iter = mx.io.PrefetchingIter(det_iter) start = timer() detections = self.mod.predict(det_iter).asnumpy() time_elapsed = timer() - start if show_timer: logging.info("Detection time for {} images: {:.4f} sec".format( num_images, time_elapsed)) result = Detector.filter_positive_detections(detections) return result
[ "def", "detect_iter", "(", "self", ",", "det_iter", ",", "show_timer", "=", "False", ")", ":", "num_images", "=", "det_iter", ".", "_size", "if", "not", "isinstance", "(", "det_iter", ",", "mx", ".", "io", ".", "PrefetchingIter", ")", ":", "det_iter", "=", "mx", ".", "io", ".", "PrefetchingIter", "(", "det_iter", ")", "start", "=", "timer", "(", ")", "detections", "=", "self", ".", "mod", ".", "predict", "(", "det_iter", ")", ".", "asnumpy", "(", ")", "time_elapsed", "=", "timer", "(", ")", "-", "start", "if", "show_timer", ":", "logging", ".", "info", "(", "\"Detection time for {} images: {:.4f} sec\"", ".", "format", "(", "num_images", ",", "time_elapsed", ")", ")", "result", "=", "Detector", ".", "filter_positive_detections", "(", "detections", ")", "return", "result" ]
detect all images in iterator Parameters: ---------- det_iter : DetIter iterator for all testing images show_timer : Boolean whether to print out detection exec time Returns: ---------- list of detection results
[ "detect", "all", "images", "in", "iterator" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/ssd/detect/detector.py#L82-L107
23,727
apache/incubator-mxnet
example/ssd/detect/detector.py
Detector.im_detect
def im_detect(self, im_list, root_dir=None, extension=None, show_timer=False): """ wrapper for detecting multiple images Parameters: ---------- im_list : list of str image path or list of image paths root_dir : str directory of input images, optional if image path already has full directory information extension : str image extension, eg. ".jpg", optional Returns: ---------- list of detection results in format [det0, det1...], det is in format np.array([id, score, xmin, ymin, xmax, ymax]...) """ test_db = TestDB(im_list, root_dir=root_dir, extension=extension) test_iter = DetIter(test_db, 1, self.data_shape, self.mean_pixels, is_train=False) return self.detect_iter(test_iter, show_timer)
python
def im_detect(self, im_list, root_dir=None, extension=None, show_timer=False): """ wrapper for detecting multiple images Parameters: ---------- im_list : list of str image path or list of image paths root_dir : str directory of input images, optional if image path already has full directory information extension : str image extension, eg. ".jpg", optional Returns: ---------- list of detection results in format [det0, det1...], det is in format np.array([id, score, xmin, ymin, xmax, ymax]...) """ test_db = TestDB(im_list, root_dir=root_dir, extension=extension) test_iter = DetIter(test_db, 1, self.data_shape, self.mean_pixels, is_train=False) return self.detect_iter(test_iter, show_timer)
[ "def", "im_detect", "(", "self", ",", "im_list", ",", "root_dir", "=", "None", ",", "extension", "=", "None", ",", "show_timer", "=", "False", ")", ":", "test_db", "=", "TestDB", "(", "im_list", ",", "root_dir", "=", "root_dir", ",", "extension", "=", "extension", ")", "test_iter", "=", "DetIter", "(", "test_db", ",", "1", ",", "self", ".", "data_shape", ",", "self", ".", "mean_pixels", ",", "is_train", "=", "False", ")", "return", "self", ".", "detect_iter", "(", "test_iter", ",", "show_timer", ")" ]
wrapper for detecting multiple images Parameters: ---------- im_list : list of str image path or list of image paths root_dir : str directory of input images, optional if image path already has full directory information extension : str image extension, eg. ".jpg", optional Returns: ---------- list of detection results in format [det0, det1...], det is in format np.array([id, score, xmin, ymin, xmax, ymax]...)
[ "wrapper", "for", "detecting", "multiple", "images" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/ssd/detect/detector.py#L120-L142
23,728
apache/incubator-mxnet
example/ssd/detect/detector.py
Detector.visualize_detection
def visualize_detection(self, img, dets, classes=[], thresh=0.6): """ visualize detections in one image Parameters: ---------- img : numpy.array image, in bgr format dets : numpy.array ssd detections, numpy.array([[id, score, x1, y1, x2, y2]...]) each row is one object classes : tuple or list of str class names thresh : float score threshold """ import matplotlib.pyplot as plt import random plt.imshow(img) height = img.shape[0] width = img.shape[1] colors = dict() for det in dets: (klass, score, x0, y0, x1, y1) = det if score < thresh: continue cls_id = int(klass) if cls_id not in colors: colors[cls_id] = (random.random(), random.random(), random.random()) xmin = int(x0 * width) ymin = int(y0 * height) xmax = int(x1 * width) ymax = int(y1 * height) rect = plt.Rectangle((xmin, ymin), xmax - xmin, ymax - ymin, fill=False, edgecolor=colors[cls_id], linewidth=3.5) plt.gca().add_patch(rect) class_name = str(cls_id) if classes and len(classes) > cls_id: class_name = classes[cls_id] plt.gca().text(xmin, ymin - 2, '{:s} {:.3f}'.format(class_name, score), bbox=dict(facecolor=colors[cls_id], alpha=0.5), fontsize=12, color='white') plt.show()
python
def visualize_detection(self, img, dets, classes=[], thresh=0.6): """ visualize detections in one image Parameters: ---------- img : numpy.array image, in bgr format dets : numpy.array ssd detections, numpy.array([[id, score, x1, y1, x2, y2]...]) each row is one object classes : tuple or list of str class names thresh : float score threshold """ import matplotlib.pyplot as plt import random plt.imshow(img) height = img.shape[0] width = img.shape[1] colors = dict() for det in dets: (klass, score, x0, y0, x1, y1) = det if score < thresh: continue cls_id = int(klass) if cls_id not in colors: colors[cls_id] = (random.random(), random.random(), random.random()) xmin = int(x0 * width) ymin = int(y0 * height) xmax = int(x1 * width) ymax = int(y1 * height) rect = plt.Rectangle((xmin, ymin), xmax - xmin, ymax - ymin, fill=False, edgecolor=colors[cls_id], linewidth=3.5) plt.gca().add_patch(rect) class_name = str(cls_id) if classes and len(classes) > cls_id: class_name = classes[cls_id] plt.gca().text(xmin, ymin - 2, '{:s} {:.3f}'.format(class_name, score), bbox=dict(facecolor=colors[cls_id], alpha=0.5), fontsize=12, color='white') plt.show()
[ "def", "visualize_detection", "(", "self", ",", "img", ",", "dets", ",", "classes", "=", "[", "]", ",", "thresh", "=", "0.6", ")", ":", "import", "matplotlib", ".", "pyplot", "as", "plt", "import", "random", "plt", ".", "imshow", "(", "img", ")", "height", "=", "img", ".", "shape", "[", "0", "]", "width", "=", "img", ".", "shape", "[", "1", "]", "colors", "=", "dict", "(", ")", "for", "det", "in", "dets", ":", "(", "klass", ",", "score", ",", "x0", ",", "y0", ",", "x1", ",", "y1", ")", "=", "det", "if", "score", "<", "thresh", ":", "continue", "cls_id", "=", "int", "(", "klass", ")", "if", "cls_id", "not", "in", "colors", ":", "colors", "[", "cls_id", "]", "=", "(", "random", ".", "random", "(", ")", ",", "random", ".", "random", "(", ")", ",", "random", ".", "random", "(", ")", ")", "xmin", "=", "int", "(", "x0", "*", "width", ")", "ymin", "=", "int", "(", "y0", "*", "height", ")", "xmax", "=", "int", "(", "x1", "*", "width", ")", "ymax", "=", "int", "(", "y1", "*", "height", ")", "rect", "=", "plt", ".", "Rectangle", "(", "(", "xmin", ",", "ymin", ")", ",", "xmax", "-", "xmin", ",", "ymax", "-", "ymin", ",", "fill", "=", "False", ",", "edgecolor", "=", "colors", "[", "cls_id", "]", ",", "linewidth", "=", "3.5", ")", "plt", ".", "gca", "(", ")", ".", "add_patch", "(", "rect", ")", "class_name", "=", "str", "(", "cls_id", ")", "if", "classes", "and", "len", "(", "classes", ")", ">", "cls_id", ":", "class_name", "=", "classes", "[", "cls_id", "]", "plt", ".", "gca", "(", ")", ".", "text", "(", "xmin", ",", "ymin", "-", "2", ",", "'{:s} {:.3f}'", ".", "format", "(", "class_name", ",", "score", ")", ",", "bbox", "=", "dict", "(", "facecolor", "=", "colors", "[", "cls_id", "]", ",", "alpha", "=", "0.5", ")", ",", "fontsize", "=", "12", ",", "color", "=", "'white'", ")", "plt", ".", "show", "(", ")" ]
visualize detections in one image Parameters: ---------- img : numpy.array image, in bgr format dets : numpy.array ssd detections, numpy.array([[id, score, x1, y1, x2, y2]...]) each row is one object classes : tuple or list of str class names thresh : float score threshold
[ "visualize", "detections", "in", "one", "image" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/ssd/detect/detector.py#L144-L189
23,729
apache/incubator-mxnet
example/ssd/detect/detector.py
Detector.detect_and_visualize
def detect_and_visualize(self, im_list, root_dir=None, extension=None, classes=[], thresh=0.6, show_timer=False): """ wrapper for im_detect and visualize_detection Parameters: ---------- im_list : list of str or str image path or list of image paths root_dir : str or None directory of input images, optional if image path already has full directory information extension : str or None image extension, eg. ".jpg", optional Returns: ---------- """ dets = self.im_detect(im_list, root_dir, extension, show_timer=show_timer) if not isinstance(im_list, list): im_list = [im_list] assert len(dets) == len(im_list) for k, det in enumerate(dets): img = cv2.imread(im_list[k]) img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) self.visualize_detection(img, det, classes, thresh)
python
def detect_and_visualize(self, im_list, root_dir=None, extension=None, classes=[], thresh=0.6, show_timer=False): """ wrapper for im_detect and visualize_detection Parameters: ---------- im_list : list of str or str image path or list of image paths root_dir : str or None directory of input images, optional if image path already has full directory information extension : str or None image extension, eg. ".jpg", optional Returns: ---------- """ dets = self.im_detect(im_list, root_dir, extension, show_timer=show_timer) if not isinstance(im_list, list): im_list = [im_list] assert len(dets) == len(im_list) for k, det in enumerate(dets): img = cv2.imread(im_list[k]) img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) self.visualize_detection(img, det, classes, thresh)
[ "def", "detect_and_visualize", "(", "self", ",", "im_list", ",", "root_dir", "=", "None", ",", "extension", "=", "None", ",", "classes", "=", "[", "]", ",", "thresh", "=", "0.6", ",", "show_timer", "=", "False", ")", ":", "dets", "=", "self", ".", "im_detect", "(", "im_list", ",", "root_dir", ",", "extension", ",", "show_timer", "=", "show_timer", ")", "if", "not", "isinstance", "(", "im_list", ",", "list", ")", ":", "im_list", "=", "[", "im_list", "]", "assert", "len", "(", "dets", ")", "==", "len", "(", "im_list", ")", "for", "k", ",", "det", "in", "enumerate", "(", "dets", ")", ":", "img", "=", "cv2", ".", "imread", "(", "im_list", "[", "k", "]", ")", "img", "=", "cv2", ".", "cvtColor", "(", "img", ",", "cv2", ".", "COLOR_BGR2RGB", ")", "self", ".", "visualize_detection", "(", "img", ",", "det", ",", "classes", ",", "thresh", ")" ]
wrapper for im_detect and visualize_detection Parameters: ---------- im_list : list of str or str image path or list of image paths root_dir : str or None directory of input images, optional if image path already has full directory information extension : str or None image extension, eg. ".jpg", optional Returns: ----------
[ "wrapper", "for", "im_detect", "and", "visualize_detection" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/ssd/detect/detector.py#L212-L238
23,730
apache/incubator-mxnet
tools/caffe_converter/caffe_proto_utils.py
process_network_proto
def process_network_proto(caffe_root, deploy_proto): """ Runs the caffe upgrade tool on the prototxt to create a prototxt in the latest format. This enable us to work just with latest structures, instead of supporting all the variants :param caffe_root: link to caffe root folder, where the upgrade tool is located :param deploy_proto: name of the original prototxt file :return: name of new processed prototxt file """ processed_deploy_proto = deploy_proto + ".processed" from shutil import copyfile copyfile(deploy_proto, processed_deploy_proto) # run upgrade tool on new file name (same output file) import os upgrade_tool_command_line = caffe_root + '/build/tools/upgrade_net_proto_text.bin ' \ + processed_deploy_proto + ' ' + processed_deploy_proto os.system(upgrade_tool_command_line) return processed_deploy_proto
python
def process_network_proto(caffe_root, deploy_proto): """ Runs the caffe upgrade tool on the prototxt to create a prototxt in the latest format. This enable us to work just with latest structures, instead of supporting all the variants :param caffe_root: link to caffe root folder, where the upgrade tool is located :param deploy_proto: name of the original prototxt file :return: name of new processed prototxt file """ processed_deploy_proto = deploy_proto + ".processed" from shutil import copyfile copyfile(deploy_proto, processed_deploy_proto) # run upgrade tool on new file name (same output file) import os upgrade_tool_command_line = caffe_root + '/build/tools/upgrade_net_proto_text.bin ' \ + processed_deploy_proto + ' ' + processed_deploy_proto os.system(upgrade_tool_command_line) return processed_deploy_proto
[ "def", "process_network_proto", "(", "caffe_root", ",", "deploy_proto", ")", ":", "processed_deploy_proto", "=", "deploy_proto", "+", "\".processed\"", "from", "shutil", "import", "copyfile", "copyfile", "(", "deploy_proto", ",", "processed_deploy_proto", ")", "# run upgrade tool on new file name (same output file)", "import", "os", "upgrade_tool_command_line", "=", "caffe_root", "+", "'/build/tools/upgrade_net_proto_text.bin '", "+", "processed_deploy_proto", "+", "' '", "+", "processed_deploy_proto", "os", ".", "system", "(", "upgrade_tool_command_line", ")", "return", "processed_deploy_proto" ]
Runs the caffe upgrade tool on the prototxt to create a prototxt in the latest format. This enable us to work just with latest structures, instead of supporting all the variants :param caffe_root: link to caffe root folder, where the upgrade tool is located :param deploy_proto: name of the original prototxt file :return: name of new processed prototxt file
[ "Runs", "the", "caffe", "upgrade", "tool", "on", "the", "prototxt", "to", "create", "a", "prototxt", "in", "the", "latest", "format", ".", "This", "enable", "us", "to", "work", "just", "with", "latest", "structures", "instead", "of", "supporting", "all", "the", "variants" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/tools/caffe_converter/caffe_proto_utils.py#L22-L42
23,731
apache/incubator-mxnet
example/gluon/embedding_learning/model.py
get_distance
def get_distance(F, x): """Helper function for margin-based loss. Return a distance matrix given a matrix.""" n = x.shape[0] square = F.sum(x ** 2.0, axis=1, keepdims=True) distance_square = square + square.transpose() - (2.0 * F.dot(x, x.transpose())) # Adding identity to make sqrt work. return F.sqrt(distance_square + F.array(np.identity(n)))
python
def get_distance(F, x): """Helper function for margin-based loss. Return a distance matrix given a matrix.""" n = x.shape[0] square = F.sum(x ** 2.0, axis=1, keepdims=True) distance_square = square + square.transpose() - (2.0 * F.dot(x, x.transpose())) # Adding identity to make sqrt work. return F.sqrt(distance_square + F.array(np.identity(n)))
[ "def", "get_distance", "(", "F", ",", "x", ")", ":", "n", "=", "x", ".", "shape", "[", "0", "]", "square", "=", "F", ".", "sum", "(", "x", "**", "2.0", ",", "axis", "=", "1", ",", "keepdims", "=", "True", ")", "distance_square", "=", "square", "+", "square", ".", "transpose", "(", ")", "-", "(", "2.0", "*", "F", ".", "dot", "(", "x", ",", "x", ".", "transpose", "(", ")", ")", ")", "# Adding identity to make sqrt work.", "return", "F", ".", "sqrt", "(", "distance_square", "+", "F", ".", "array", "(", "np", ".", "identity", "(", "n", ")", ")", ")" ]
Helper function for margin-based loss. Return a distance matrix given a matrix.
[ "Helper", "function", "for", "margin", "-", "based", "loss", ".", "Return", "a", "distance", "matrix", "given", "a", "matrix", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/gluon/embedding_learning/model.py#L51-L59
23,732
apache/incubator-mxnet
example/rnn/large_word_lm/model.py
cross_entropy_loss
def cross_entropy_loss(inputs, labels, rescale_loss=1): """ cross entropy loss with a mask """ criterion = mx.gluon.loss.SoftmaxCrossEntropyLoss(weight=rescale_loss) loss = criterion(inputs, labels) mask = S.var('mask') loss = loss * S.reshape(mask, shape=(-1,)) return S.make_loss(loss.mean())
python
def cross_entropy_loss(inputs, labels, rescale_loss=1): """ cross entropy loss with a mask """ criterion = mx.gluon.loss.SoftmaxCrossEntropyLoss(weight=rescale_loss) loss = criterion(inputs, labels) mask = S.var('mask') loss = loss * S.reshape(mask, shape=(-1,)) return S.make_loss(loss.mean())
[ "def", "cross_entropy_loss", "(", "inputs", ",", "labels", ",", "rescale_loss", "=", "1", ")", ":", "criterion", "=", "mx", ".", "gluon", ".", "loss", ".", "SoftmaxCrossEntropyLoss", "(", "weight", "=", "rescale_loss", ")", "loss", "=", "criterion", "(", "inputs", ",", "labels", ")", "mask", "=", "S", ".", "var", "(", "'mask'", ")", "loss", "=", "loss", "*", "S", ".", "reshape", "(", "mask", ",", "shape", "=", "(", "-", "1", ",", ")", ")", "return", "S", ".", "make_loss", "(", "loss", ".", "mean", "(", ")", ")" ]
cross entropy loss with a mask
[ "cross", "entropy", "loss", "with", "a", "mask" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/rnn/large_word_lm/model.py#L39-L45
23,733
apache/incubator-mxnet
example/rnn/large_word_lm/model.py
rnn
def rnn(bptt, vocab_size, num_embed, nhid, num_layers, dropout, num_proj, batch_size): """ word embedding + LSTM Projected """ state_names = [] data = S.var('data') weight = S.var("encoder_weight", stype='row_sparse') embed = S.sparse.Embedding(data=data, weight=weight, input_dim=vocab_size, output_dim=num_embed, name='embed', sparse_grad=True) states = [] outputs = S.Dropout(embed, p=dropout) for i in range(num_layers): prefix = 'lstmp%d_' % i init_h = S.var(prefix + 'init_h', shape=(batch_size, num_proj), init=mx.init.Zero()) init_c = S.var(prefix + 'init_c', shape=(batch_size, nhid), init=mx.init.Zero()) state_names += [prefix + 'init_h', prefix + 'init_c'] lstmp = mx.gluon.contrib.rnn.LSTMPCell(nhid, num_proj, prefix=prefix) outputs, next_states = lstmp.unroll(bptt, outputs, begin_state=[init_h, init_c], \ layout='NTC', merge_outputs=True) outputs = S.Dropout(outputs, p=dropout) states += [S.stop_gradient(s) for s in next_states] outputs = S.reshape(outputs, shape=(-1, num_proj)) trainable_lstm_args = [] for arg in outputs.list_arguments(): if 'lstmp' in arg and 'init' not in arg: trainable_lstm_args.append(arg) return outputs, states, trainable_lstm_args, state_names
python
def rnn(bptt, vocab_size, num_embed, nhid, num_layers, dropout, num_proj, batch_size): """ word embedding + LSTM Projected """ state_names = [] data = S.var('data') weight = S.var("encoder_weight", stype='row_sparse') embed = S.sparse.Embedding(data=data, weight=weight, input_dim=vocab_size, output_dim=num_embed, name='embed', sparse_grad=True) states = [] outputs = S.Dropout(embed, p=dropout) for i in range(num_layers): prefix = 'lstmp%d_' % i init_h = S.var(prefix + 'init_h', shape=(batch_size, num_proj), init=mx.init.Zero()) init_c = S.var(prefix + 'init_c', shape=(batch_size, nhid), init=mx.init.Zero()) state_names += [prefix + 'init_h', prefix + 'init_c'] lstmp = mx.gluon.contrib.rnn.LSTMPCell(nhid, num_proj, prefix=prefix) outputs, next_states = lstmp.unroll(bptt, outputs, begin_state=[init_h, init_c], \ layout='NTC', merge_outputs=True) outputs = S.Dropout(outputs, p=dropout) states += [S.stop_gradient(s) for s in next_states] outputs = S.reshape(outputs, shape=(-1, num_proj)) trainable_lstm_args = [] for arg in outputs.list_arguments(): if 'lstmp' in arg and 'init' not in arg: trainable_lstm_args.append(arg) return outputs, states, trainable_lstm_args, state_names
[ "def", "rnn", "(", "bptt", ",", "vocab_size", ",", "num_embed", ",", "nhid", ",", "num_layers", ",", "dropout", ",", "num_proj", ",", "batch_size", ")", ":", "state_names", "=", "[", "]", "data", "=", "S", ".", "var", "(", "'data'", ")", "weight", "=", "S", ".", "var", "(", "\"encoder_weight\"", ",", "stype", "=", "'row_sparse'", ")", "embed", "=", "S", ".", "sparse", ".", "Embedding", "(", "data", "=", "data", ",", "weight", "=", "weight", ",", "input_dim", "=", "vocab_size", ",", "output_dim", "=", "num_embed", ",", "name", "=", "'embed'", ",", "sparse_grad", "=", "True", ")", "states", "=", "[", "]", "outputs", "=", "S", ".", "Dropout", "(", "embed", ",", "p", "=", "dropout", ")", "for", "i", "in", "range", "(", "num_layers", ")", ":", "prefix", "=", "'lstmp%d_'", "%", "i", "init_h", "=", "S", ".", "var", "(", "prefix", "+", "'init_h'", ",", "shape", "=", "(", "batch_size", ",", "num_proj", ")", ",", "init", "=", "mx", ".", "init", ".", "Zero", "(", ")", ")", "init_c", "=", "S", ".", "var", "(", "prefix", "+", "'init_c'", ",", "shape", "=", "(", "batch_size", ",", "nhid", ")", ",", "init", "=", "mx", ".", "init", ".", "Zero", "(", ")", ")", "state_names", "+=", "[", "prefix", "+", "'init_h'", ",", "prefix", "+", "'init_c'", "]", "lstmp", "=", "mx", ".", "gluon", ".", "contrib", ".", "rnn", ".", "LSTMPCell", "(", "nhid", ",", "num_proj", ",", "prefix", "=", "prefix", ")", "outputs", ",", "next_states", "=", "lstmp", ".", "unroll", "(", "bptt", ",", "outputs", ",", "begin_state", "=", "[", "init_h", ",", "init_c", "]", ",", "layout", "=", "'NTC'", ",", "merge_outputs", "=", "True", ")", "outputs", "=", "S", ".", "Dropout", "(", "outputs", ",", "p", "=", "dropout", ")", "states", "+=", "[", "S", ".", "stop_gradient", "(", "s", ")", "for", "s", "in", "next_states", "]", "outputs", "=", "S", ".", "reshape", "(", "outputs", ",", "shape", "=", "(", "-", "1", ",", "num_proj", ")", ")", "trainable_lstm_args", "=", "[", "]", "for", "arg", "in", "outputs", ".", "list_arguments", "(", ")", ":", "if", "'lstmp'", "in", "arg", "and", "'init'", "not", "in", "arg", ":", "trainable_lstm_args", ".", "append", "(", "arg", ")", "return", "outputs", ",", "states", ",", "trainable_lstm_args", ",", "state_names" ]
word embedding + LSTM Projected
[ "word", "embedding", "+", "LSTM", "Projected" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/rnn/large_word_lm/model.py#L47-L72
23,734
apache/incubator-mxnet
example/rnn/large_word_lm/model.py
sampled_softmax
def sampled_softmax(num_classes, num_samples, in_dim, inputs, weight, bias, sampled_values, remove_accidental_hits=True): """ Sampled softmax via importance sampling. This under-estimates the full softmax and is only used for training. """ # inputs = (n, in_dim) sample, prob_sample, prob_target = sampled_values # (num_samples, ) sample = S.var('sample', shape=(num_samples,), dtype='float32') # (n, ) label = S.var('label') label = S.reshape(label, shape=(-1,), name="label_reshape") # (num_samples+n, ) sample_label = S.concat(sample, label, dim=0) # lookup weights and biases # (num_samples+n, dim) sample_target_w = S.sparse.Embedding(data=sample_label, weight=weight, input_dim=num_classes, output_dim=in_dim, sparse_grad=True) # (num_samples+n, 1) sample_target_b = S.sparse.Embedding(data=sample_label, weight=bias, input_dim=num_classes, output_dim=1, sparse_grad=True) # (num_samples, dim) sample_w = S.slice(sample_target_w, begin=(0, 0), end=(num_samples, None)) target_w = S.slice(sample_target_w, begin=(num_samples, 0), end=(None, None)) sample_b = S.slice(sample_target_b, begin=(0, 0), end=(num_samples, None)) target_b = S.slice(sample_target_b, begin=(num_samples, 0), end=(None, None)) # target # (n, 1) true_pred = S.sum(target_w * inputs, axis=1, keepdims=True) + target_b # samples # (n, num_samples) sample_b = S.reshape(sample_b, (-1,)) sample_pred = S.FullyConnected(inputs, weight=sample_w, bias=sample_b, num_hidden=num_samples) # remove accidental hits if remove_accidental_hits: label_v = S.reshape(label, (-1, 1)) sample_v = S.reshape(sample, (1, -1)) neg = S.broadcast_equal(label_v, sample_v) * -1e37 sample_pred = sample_pred + neg prob_sample = S.reshape(prob_sample, shape=(1, num_samples)) p_target = true_pred - S.log(prob_target) p_sample = S.broadcast_sub(sample_pred, S.log(prob_sample)) # return logits and new_labels # (n, 1+num_samples) logits = S.concat(p_target, p_sample, dim=1) new_targets = S.zeros_like(label) return logits, new_targets
python
def sampled_softmax(num_classes, num_samples, in_dim, inputs, weight, bias, sampled_values, remove_accidental_hits=True): """ Sampled softmax via importance sampling. This under-estimates the full softmax and is only used for training. """ # inputs = (n, in_dim) sample, prob_sample, prob_target = sampled_values # (num_samples, ) sample = S.var('sample', shape=(num_samples,), dtype='float32') # (n, ) label = S.var('label') label = S.reshape(label, shape=(-1,), name="label_reshape") # (num_samples+n, ) sample_label = S.concat(sample, label, dim=0) # lookup weights and biases # (num_samples+n, dim) sample_target_w = S.sparse.Embedding(data=sample_label, weight=weight, input_dim=num_classes, output_dim=in_dim, sparse_grad=True) # (num_samples+n, 1) sample_target_b = S.sparse.Embedding(data=sample_label, weight=bias, input_dim=num_classes, output_dim=1, sparse_grad=True) # (num_samples, dim) sample_w = S.slice(sample_target_w, begin=(0, 0), end=(num_samples, None)) target_w = S.slice(sample_target_w, begin=(num_samples, 0), end=(None, None)) sample_b = S.slice(sample_target_b, begin=(0, 0), end=(num_samples, None)) target_b = S.slice(sample_target_b, begin=(num_samples, 0), end=(None, None)) # target # (n, 1) true_pred = S.sum(target_w * inputs, axis=1, keepdims=True) + target_b # samples # (n, num_samples) sample_b = S.reshape(sample_b, (-1,)) sample_pred = S.FullyConnected(inputs, weight=sample_w, bias=sample_b, num_hidden=num_samples) # remove accidental hits if remove_accidental_hits: label_v = S.reshape(label, (-1, 1)) sample_v = S.reshape(sample, (1, -1)) neg = S.broadcast_equal(label_v, sample_v) * -1e37 sample_pred = sample_pred + neg prob_sample = S.reshape(prob_sample, shape=(1, num_samples)) p_target = true_pred - S.log(prob_target) p_sample = S.broadcast_sub(sample_pred, S.log(prob_sample)) # return logits and new_labels # (n, 1+num_samples) logits = S.concat(p_target, p_sample, dim=1) new_targets = S.zeros_like(label) return logits, new_targets
[ "def", "sampled_softmax", "(", "num_classes", ",", "num_samples", ",", "in_dim", ",", "inputs", ",", "weight", ",", "bias", ",", "sampled_values", ",", "remove_accidental_hits", "=", "True", ")", ":", "# inputs = (n, in_dim)", "sample", ",", "prob_sample", ",", "prob_target", "=", "sampled_values", "# (num_samples, )", "sample", "=", "S", ".", "var", "(", "'sample'", ",", "shape", "=", "(", "num_samples", ",", ")", ",", "dtype", "=", "'float32'", ")", "# (n, )", "label", "=", "S", ".", "var", "(", "'label'", ")", "label", "=", "S", ".", "reshape", "(", "label", ",", "shape", "=", "(", "-", "1", ",", ")", ",", "name", "=", "\"label_reshape\"", ")", "# (num_samples+n, )", "sample_label", "=", "S", ".", "concat", "(", "sample", ",", "label", ",", "dim", "=", "0", ")", "# lookup weights and biases", "# (num_samples+n, dim)", "sample_target_w", "=", "S", ".", "sparse", ".", "Embedding", "(", "data", "=", "sample_label", ",", "weight", "=", "weight", ",", "input_dim", "=", "num_classes", ",", "output_dim", "=", "in_dim", ",", "sparse_grad", "=", "True", ")", "# (num_samples+n, 1)", "sample_target_b", "=", "S", ".", "sparse", ".", "Embedding", "(", "data", "=", "sample_label", ",", "weight", "=", "bias", ",", "input_dim", "=", "num_classes", ",", "output_dim", "=", "1", ",", "sparse_grad", "=", "True", ")", "# (num_samples, dim)", "sample_w", "=", "S", ".", "slice", "(", "sample_target_w", ",", "begin", "=", "(", "0", ",", "0", ")", ",", "end", "=", "(", "num_samples", ",", "None", ")", ")", "target_w", "=", "S", ".", "slice", "(", "sample_target_w", ",", "begin", "=", "(", "num_samples", ",", "0", ")", ",", "end", "=", "(", "None", ",", "None", ")", ")", "sample_b", "=", "S", ".", "slice", "(", "sample_target_b", ",", "begin", "=", "(", "0", ",", "0", ")", ",", "end", "=", "(", "num_samples", ",", "None", ")", ")", "target_b", "=", "S", ".", "slice", "(", "sample_target_b", ",", "begin", "=", "(", "num_samples", ",", "0", ")", ",", "end", "=", "(", "None", ",", "None", ")", ")", "# target", "# (n, 1)", "true_pred", "=", "S", ".", "sum", "(", "target_w", "*", "inputs", ",", "axis", "=", "1", ",", "keepdims", "=", "True", ")", "+", "target_b", "# samples", "# (n, num_samples)", "sample_b", "=", "S", ".", "reshape", "(", "sample_b", ",", "(", "-", "1", ",", ")", ")", "sample_pred", "=", "S", ".", "FullyConnected", "(", "inputs", ",", "weight", "=", "sample_w", ",", "bias", "=", "sample_b", ",", "num_hidden", "=", "num_samples", ")", "# remove accidental hits", "if", "remove_accidental_hits", ":", "label_v", "=", "S", ".", "reshape", "(", "label", ",", "(", "-", "1", ",", "1", ")", ")", "sample_v", "=", "S", ".", "reshape", "(", "sample", ",", "(", "1", ",", "-", "1", ")", ")", "neg", "=", "S", ".", "broadcast_equal", "(", "label_v", ",", "sample_v", ")", "*", "-", "1e37", "sample_pred", "=", "sample_pred", "+", "neg", "prob_sample", "=", "S", ".", "reshape", "(", "prob_sample", ",", "shape", "=", "(", "1", ",", "num_samples", ")", ")", "p_target", "=", "true_pred", "-", "S", ".", "log", "(", "prob_target", ")", "p_sample", "=", "S", ".", "broadcast_sub", "(", "sample_pred", ",", "S", ".", "log", "(", "prob_sample", ")", ")", "# return logits and new_labels", "# (n, 1+num_samples)", "logits", "=", "S", ".", "concat", "(", "p_target", ",", "p_sample", ",", "dim", "=", "1", ")", "new_targets", "=", "S", ".", "zeros_like", "(", "label", ")", "return", "logits", ",", "new_targets" ]
Sampled softmax via importance sampling. This under-estimates the full softmax and is only used for training.
[ "Sampled", "softmax", "via", "importance", "sampling", ".", "This", "under", "-", "estimates", "the", "full", "softmax", "and", "is", "only", "used", "for", "training", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/rnn/large_word_lm/model.py#L74-L128
23,735
apache/incubator-mxnet
example/rnn/large_word_lm/model.py
generate_samples
def generate_samples(label, num_splits, sampler): """ Split labels into `num_splits` and generate candidates based on log-uniform distribution. """ def listify(x): return x if isinstance(x, list) else [x] label_splits = listify(label.split(num_splits, axis=0)) prob_samples = [] prob_targets = [] samples = [] for label_split in label_splits: label_split_2d = label_split.reshape((-1,1)) sampled_value = sampler.draw(label_split_2d) sampled_classes, exp_cnt_true, exp_cnt_sampled = sampled_value samples.append(sampled_classes.astype(np.float32)) prob_targets.append(exp_cnt_true.astype(np.float32).reshape((-1,1))) prob_samples.append(exp_cnt_sampled.astype(np.float32)) return samples, prob_samples, prob_targets
python
def generate_samples(label, num_splits, sampler): """ Split labels into `num_splits` and generate candidates based on log-uniform distribution. """ def listify(x): return x if isinstance(x, list) else [x] label_splits = listify(label.split(num_splits, axis=0)) prob_samples = [] prob_targets = [] samples = [] for label_split in label_splits: label_split_2d = label_split.reshape((-1,1)) sampled_value = sampler.draw(label_split_2d) sampled_classes, exp_cnt_true, exp_cnt_sampled = sampled_value samples.append(sampled_classes.astype(np.float32)) prob_targets.append(exp_cnt_true.astype(np.float32).reshape((-1,1))) prob_samples.append(exp_cnt_sampled.astype(np.float32)) return samples, prob_samples, prob_targets
[ "def", "generate_samples", "(", "label", ",", "num_splits", ",", "sampler", ")", ":", "def", "listify", "(", "x", ")", ":", "return", "x", "if", "isinstance", "(", "x", ",", "list", ")", "else", "[", "x", "]", "label_splits", "=", "listify", "(", "label", ".", "split", "(", "num_splits", ",", "axis", "=", "0", ")", ")", "prob_samples", "=", "[", "]", "prob_targets", "=", "[", "]", "samples", "=", "[", "]", "for", "label_split", "in", "label_splits", ":", "label_split_2d", "=", "label_split", ".", "reshape", "(", "(", "-", "1", ",", "1", ")", ")", "sampled_value", "=", "sampler", ".", "draw", "(", "label_split_2d", ")", "sampled_classes", ",", "exp_cnt_true", ",", "exp_cnt_sampled", "=", "sampled_value", "samples", ".", "append", "(", "sampled_classes", ".", "astype", "(", "np", ".", "float32", ")", ")", "prob_targets", ".", "append", "(", "exp_cnt_true", ".", "astype", "(", "np", ".", "float32", ")", ".", "reshape", "(", "(", "-", "1", ",", "1", ")", ")", ")", "prob_samples", ".", "append", "(", "exp_cnt_sampled", ".", "astype", "(", "np", ".", "float32", ")", ")", "return", "samples", ",", "prob_samples", ",", "prob_targets" ]
Split labels into `num_splits` and generate candidates based on log-uniform distribution.
[ "Split", "labels", "into", "num_splits", "and", "generate", "candidates", "based", "on", "log", "-", "uniform", "distribution", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/rnn/large_word_lm/model.py#L130-L147
23,736
apache/incubator-mxnet
python/mxnet/gluon/model_zoo/vision/__init__.py
get_model
def get_model(name, **kwargs): """Returns a pre-defined model by name Parameters ---------- name : str Name of the model. pretrained : bool Whether to load the pretrained weights for model. classes : int Number of classes for the output layer. ctx : Context, default CPU The context in which to load the pretrained weights. root : str, default '$MXNET_HOME/models' Location for keeping the model parameters. Returns ------- HybridBlock The model. """ models = {'resnet18_v1': resnet18_v1, 'resnet34_v1': resnet34_v1, 'resnet50_v1': resnet50_v1, 'resnet101_v1': resnet101_v1, 'resnet152_v1': resnet152_v1, 'resnet18_v2': resnet18_v2, 'resnet34_v2': resnet34_v2, 'resnet50_v2': resnet50_v2, 'resnet101_v2': resnet101_v2, 'resnet152_v2': resnet152_v2, 'vgg11': vgg11, 'vgg13': vgg13, 'vgg16': vgg16, 'vgg19': vgg19, 'vgg11_bn': vgg11_bn, 'vgg13_bn': vgg13_bn, 'vgg16_bn': vgg16_bn, 'vgg19_bn': vgg19_bn, 'alexnet': alexnet, 'densenet121': densenet121, 'densenet161': densenet161, 'densenet169': densenet169, 'densenet201': densenet201, 'squeezenet1.0': squeezenet1_0, 'squeezenet1.1': squeezenet1_1, 'inceptionv3': inception_v3, 'mobilenet1.0': mobilenet1_0, 'mobilenet0.75': mobilenet0_75, 'mobilenet0.5': mobilenet0_5, 'mobilenet0.25': mobilenet0_25, 'mobilenetv2_1.0': mobilenet_v2_1_0, 'mobilenetv2_0.75': mobilenet_v2_0_75, 'mobilenetv2_0.5': mobilenet_v2_0_5, 'mobilenetv2_0.25': mobilenet_v2_0_25 } name = name.lower() if name not in models: raise ValueError( 'Model %s is not supported. Available options are\n\t%s' % ( name, '\n\t'.join(sorted(models.keys())))) return models[name](**kwargs)
python
def get_model(name, **kwargs): """Returns a pre-defined model by name Parameters ---------- name : str Name of the model. pretrained : bool Whether to load the pretrained weights for model. classes : int Number of classes for the output layer. ctx : Context, default CPU The context in which to load the pretrained weights. root : str, default '$MXNET_HOME/models' Location for keeping the model parameters. Returns ------- HybridBlock The model. """ models = {'resnet18_v1': resnet18_v1, 'resnet34_v1': resnet34_v1, 'resnet50_v1': resnet50_v1, 'resnet101_v1': resnet101_v1, 'resnet152_v1': resnet152_v1, 'resnet18_v2': resnet18_v2, 'resnet34_v2': resnet34_v2, 'resnet50_v2': resnet50_v2, 'resnet101_v2': resnet101_v2, 'resnet152_v2': resnet152_v2, 'vgg11': vgg11, 'vgg13': vgg13, 'vgg16': vgg16, 'vgg19': vgg19, 'vgg11_bn': vgg11_bn, 'vgg13_bn': vgg13_bn, 'vgg16_bn': vgg16_bn, 'vgg19_bn': vgg19_bn, 'alexnet': alexnet, 'densenet121': densenet121, 'densenet161': densenet161, 'densenet169': densenet169, 'densenet201': densenet201, 'squeezenet1.0': squeezenet1_0, 'squeezenet1.1': squeezenet1_1, 'inceptionv3': inception_v3, 'mobilenet1.0': mobilenet1_0, 'mobilenet0.75': mobilenet0_75, 'mobilenet0.5': mobilenet0_5, 'mobilenet0.25': mobilenet0_25, 'mobilenetv2_1.0': mobilenet_v2_1_0, 'mobilenetv2_0.75': mobilenet_v2_0_75, 'mobilenetv2_0.5': mobilenet_v2_0_5, 'mobilenetv2_0.25': mobilenet_v2_0_25 } name = name.lower() if name not in models: raise ValueError( 'Model %s is not supported. Available options are\n\t%s' % ( name, '\n\t'.join(sorted(models.keys())))) return models[name](**kwargs)
[ "def", "get_model", "(", "name", ",", "*", "*", "kwargs", ")", ":", "models", "=", "{", "'resnet18_v1'", ":", "resnet18_v1", ",", "'resnet34_v1'", ":", "resnet34_v1", ",", "'resnet50_v1'", ":", "resnet50_v1", ",", "'resnet101_v1'", ":", "resnet101_v1", ",", "'resnet152_v1'", ":", "resnet152_v1", ",", "'resnet18_v2'", ":", "resnet18_v2", ",", "'resnet34_v2'", ":", "resnet34_v2", ",", "'resnet50_v2'", ":", "resnet50_v2", ",", "'resnet101_v2'", ":", "resnet101_v2", ",", "'resnet152_v2'", ":", "resnet152_v2", ",", "'vgg11'", ":", "vgg11", ",", "'vgg13'", ":", "vgg13", ",", "'vgg16'", ":", "vgg16", ",", "'vgg19'", ":", "vgg19", ",", "'vgg11_bn'", ":", "vgg11_bn", ",", "'vgg13_bn'", ":", "vgg13_bn", ",", "'vgg16_bn'", ":", "vgg16_bn", ",", "'vgg19_bn'", ":", "vgg19_bn", ",", "'alexnet'", ":", "alexnet", ",", "'densenet121'", ":", "densenet121", ",", "'densenet161'", ":", "densenet161", ",", "'densenet169'", ":", "densenet169", ",", "'densenet201'", ":", "densenet201", ",", "'squeezenet1.0'", ":", "squeezenet1_0", ",", "'squeezenet1.1'", ":", "squeezenet1_1", ",", "'inceptionv3'", ":", "inception_v3", ",", "'mobilenet1.0'", ":", "mobilenet1_0", ",", "'mobilenet0.75'", ":", "mobilenet0_75", ",", "'mobilenet0.5'", ":", "mobilenet0_5", ",", "'mobilenet0.25'", ":", "mobilenet0_25", ",", "'mobilenetv2_1.0'", ":", "mobilenet_v2_1_0", ",", "'mobilenetv2_0.75'", ":", "mobilenet_v2_0_75", ",", "'mobilenetv2_0.5'", ":", "mobilenet_v2_0_5", ",", "'mobilenetv2_0.25'", ":", "mobilenet_v2_0_25", "}", "name", "=", "name", ".", "lower", "(", ")", "if", "name", "not", "in", "models", ":", "raise", "ValueError", "(", "'Model %s is not supported. Available options are\\n\\t%s'", "%", "(", "name", ",", "'\\n\\t'", ".", "join", "(", "sorted", "(", "models", ".", "keys", "(", ")", ")", ")", ")", ")", "return", "models", "[", "name", "]", "(", "*", "*", "kwargs", ")" ]
Returns a pre-defined model by name Parameters ---------- name : str Name of the model. pretrained : bool Whether to load the pretrained weights for model. classes : int Number of classes for the output layer. ctx : Context, default CPU The context in which to load the pretrained weights. root : str, default '$MXNET_HOME/models' Location for keeping the model parameters. Returns ------- HybridBlock The model.
[ "Returns", "a", "pre", "-", "defined", "model", "by", "name" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/gluon/model_zoo/vision/__init__.py#L91-L152
23,737
apache/incubator-mxnet
python/mxnet/ndarray/sparse.py
_new_alloc_handle
def _new_alloc_handle(stype, shape, ctx, delay_alloc, dtype, aux_types, aux_shapes=None): """Return a new handle with specified storage type, shape, dtype and context. Empty handle is only used to hold results Returns ------- handle A new empty ndarray handle """ hdl = NDArrayHandle() for aux_t in aux_types: if np.dtype(aux_t) != np.dtype("int64"): raise NotImplementedError("only int64 is supported for aux types") aux_type_ids = [int(_DTYPE_NP_TO_MX[np.dtype(aux_t).type]) for aux_t in aux_types] aux_shapes = [(0,) for aux_t in aux_types] if aux_shapes is None else aux_shapes aux_shape_lens = [len(aux_shape) for aux_shape in aux_shapes] aux_shapes = py_sum(aux_shapes, ()) num_aux = mx_uint(len(aux_types)) check_call(_LIB.MXNDArrayCreateSparseEx( ctypes.c_int(int(_STORAGE_TYPE_STR_TO_ID[stype])), c_array_buf(mx_uint, native_array('I', shape)), mx_uint(len(shape)), ctypes.c_int(ctx.device_typeid), ctypes.c_int(ctx.device_id), ctypes.c_int(int(delay_alloc)), ctypes.c_int(int(_DTYPE_NP_TO_MX[np.dtype(dtype).type])), num_aux, c_array_buf(ctypes.c_int, native_array('i', aux_type_ids)), c_array_buf(mx_uint, native_array('I', aux_shape_lens)), c_array_buf(mx_uint, native_array('I', aux_shapes)), ctypes.byref(hdl))) return hdl
python
def _new_alloc_handle(stype, shape, ctx, delay_alloc, dtype, aux_types, aux_shapes=None): """Return a new handle with specified storage type, shape, dtype and context. Empty handle is only used to hold results Returns ------- handle A new empty ndarray handle """ hdl = NDArrayHandle() for aux_t in aux_types: if np.dtype(aux_t) != np.dtype("int64"): raise NotImplementedError("only int64 is supported for aux types") aux_type_ids = [int(_DTYPE_NP_TO_MX[np.dtype(aux_t).type]) for aux_t in aux_types] aux_shapes = [(0,) for aux_t in aux_types] if aux_shapes is None else aux_shapes aux_shape_lens = [len(aux_shape) for aux_shape in aux_shapes] aux_shapes = py_sum(aux_shapes, ()) num_aux = mx_uint(len(aux_types)) check_call(_LIB.MXNDArrayCreateSparseEx( ctypes.c_int(int(_STORAGE_TYPE_STR_TO_ID[stype])), c_array_buf(mx_uint, native_array('I', shape)), mx_uint(len(shape)), ctypes.c_int(ctx.device_typeid), ctypes.c_int(ctx.device_id), ctypes.c_int(int(delay_alloc)), ctypes.c_int(int(_DTYPE_NP_TO_MX[np.dtype(dtype).type])), num_aux, c_array_buf(ctypes.c_int, native_array('i', aux_type_ids)), c_array_buf(mx_uint, native_array('I', aux_shape_lens)), c_array_buf(mx_uint, native_array('I', aux_shapes)), ctypes.byref(hdl))) return hdl
[ "def", "_new_alloc_handle", "(", "stype", ",", "shape", ",", "ctx", ",", "delay_alloc", ",", "dtype", ",", "aux_types", ",", "aux_shapes", "=", "None", ")", ":", "hdl", "=", "NDArrayHandle", "(", ")", "for", "aux_t", "in", "aux_types", ":", "if", "np", ".", "dtype", "(", "aux_t", ")", "!=", "np", ".", "dtype", "(", "\"int64\"", ")", ":", "raise", "NotImplementedError", "(", "\"only int64 is supported for aux types\"", ")", "aux_type_ids", "=", "[", "int", "(", "_DTYPE_NP_TO_MX", "[", "np", ".", "dtype", "(", "aux_t", ")", ".", "type", "]", ")", "for", "aux_t", "in", "aux_types", "]", "aux_shapes", "=", "[", "(", "0", ",", ")", "for", "aux_t", "in", "aux_types", "]", "if", "aux_shapes", "is", "None", "else", "aux_shapes", "aux_shape_lens", "=", "[", "len", "(", "aux_shape", ")", "for", "aux_shape", "in", "aux_shapes", "]", "aux_shapes", "=", "py_sum", "(", "aux_shapes", ",", "(", ")", ")", "num_aux", "=", "mx_uint", "(", "len", "(", "aux_types", ")", ")", "check_call", "(", "_LIB", ".", "MXNDArrayCreateSparseEx", "(", "ctypes", ".", "c_int", "(", "int", "(", "_STORAGE_TYPE_STR_TO_ID", "[", "stype", "]", ")", ")", ",", "c_array_buf", "(", "mx_uint", ",", "native_array", "(", "'I'", ",", "shape", ")", ")", ",", "mx_uint", "(", "len", "(", "shape", ")", ")", ",", "ctypes", ".", "c_int", "(", "ctx", ".", "device_typeid", ")", ",", "ctypes", ".", "c_int", "(", "ctx", ".", "device_id", ")", ",", "ctypes", ".", "c_int", "(", "int", "(", "delay_alloc", ")", ")", ",", "ctypes", ".", "c_int", "(", "int", "(", "_DTYPE_NP_TO_MX", "[", "np", ".", "dtype", "(", "dtype", ")", ".", "type", "]", ")", ")", ",", "num_aux", ",", "c_array_buf", "(", "ctypes", ".", "c_int", ",", "native_array", "(", "'i'", ",", "aux_type_ids", ")", ")", ",", "c_array_buf", "(", "mx_uint", ",", "native_array", "(", "'I'", ",", "aux_shape_lens", ")", ")", ",", "c_array_buf", "(", "mx_uint", ",", "native_array", "(", "'I'", ",", "aux_shapes", ")", ")", ",", "ctypes", ".", "byref", "(", "hdl", ")", ")", ")", "return", "hdl" ]
Return a new handle with specified storage type, shape, dtype and context. Empty handle is only used to hold results Returns ------- handle A new empty ndarray handle
[ "Return", "a", "new", "handle", "with", "specified", "storage", "type", "shape", "dtype", "and", "context", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/ndarray/sparse.py#L72-L104
23,738
apache/incubator-mxnet
python/mxnet/ndarray/sparse.py
_prepare_src_array
def _prepare_src_array(source_array, dtype): """Prepare `source_array` so that it can be used to construct NDArray. `source_array` is converted to a `np.ndarray` if it's neither an `NDArray` \ nor an `np.ndarray`. """ if not isinstance(source_array, NDArray) and not isinstance(source_array, np.ndarray): try: source_array = np.array(source_array, dtype=dtype) except: raise TypeError('values must be array like object') return source_array
python
def _prepare_src_array(source_array, dtype): """Prepare `source_array` so that it can be used to construct NDArray. `source_array` is converted to a `np.ndarray` if it's neither an `NDArray` \ nor an `np.ndarray`. """ if not isinstance(source_array, NDArray) and not isinstance(source_array, np.ndarray): try: source_array = np.array(source_array, dtype=dtype) except: raise TypeError('values must be array like object') return source_array
[ "def", "_prepare_src_array", "(", "source_array", ",", "dtype", ")", ":", "if", "not", "isinstance", "(", "source_array", ",", "NDArray", ")", "and", "not", "isinstance", "(", "source_array", ",", "np", ".", "ndarray", ")", ":", "try", ":", "source_array", "=", "np", ".", "array", "(", "source_array", ",", "dtype", "=", "dtype", ")", "except", ":", "raise", "TypeError", "(", "'values must be array like object'", ")", "return", "source_array" ]
Prepare `source_array` so that it can be used to construct NDArray. `source_array` is converted to a `np.ndarray` if it's neither an `NDArray` \ nor an `np.ndarray`.
[ "Prepare", "source_array", "so", "that", "it", "can", "be", "used", "to", "construct", "NDArray", ".", "source_array", "is", "converted", "to", "a", "np", ".", "ndarray", "if", "it", "s", "neither", "an", "NDArray", "\\", "nor", "an", "np", ".", "ndarray", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/ndarray/sparse.py#L796-L806
23,739
apache/incubator-mxnet
python/mxnet/ndarray/sparse.py
_prepare_default_dtype
def _prepare_default_dtype(src_array, dtype): """Prepare the value of dtype if `dtype` is None. If `src_array` is an NDArray, numpy.ndarray or scipy.sparse.csr.csr_matrix, return src_array.dtype. float32 is returned otherwise.""" if dtype is None: if isinstance(src_array, (NDArray, np.ndarray)): dtype = src_array.dtype elif spsp and isinstance(src_array, spsp.csr.csr_matrix): dtype = src_array.dtype else: dtype = mx_real_t return dtype
python
def _prepare_default_dtype(src_array, dtype): """Prepare the value of dtype if `dtype` is None. If `src_array` is an NDArray, numpy.ndarray or scipy.sparse.csr.csr_matrix, return src_array.dtype. float32 is returned otherwise.""" if dtype is None: if isinstance(src_array, (NDArray, np.ndarray)): dtype = src_array.dtype elif spsp and isinstance(src_array, spsp.csr.csr_matrix): dtype = src_array.dtype else: dtype = mx_real_t return dtype
[ "def", "_prepare_default_dtype", "(", "src_array", ",", "dtype", ")", ":", "if", "dtype", "is", "None", ":", "if", "isinstance", "(", "src_array", ",", "(", "NDArray", ",", "np", ".", "ndarray", ")", ")", ":", "dtype", "=", "src_array", ".", "dtype", "elif", "spsp", "and", "isinstance", "(", "src_array", ",", "spsp", ".", "csr", ".", "csr_matrix", ")", ":", "dtype", "=", "src_array", ".", "dtype", "else", ":", "dtype", "=", "mx_real_t", "return", "dtype" ]
Prepare the value of dtype if `dtype` is None. If `src_array` is an NDArray, numpy.ndarray or scipy.sparse.csr.csr_matrix, return src_array.dtype. float32 is returned otherwise.
[ "Prepare", "the", "value", "of", "dtype", "if", "dtype", "is", "None", ".", "If", "src_array", "is", "an", "NDArray", "numpy", ".", "ndarray", "or", "scipy", ".", "sparse", ".", "csr", ".", "csr_matrix", "return", "src_array", ".", "dtype", ".", "float32", "is", "returned", "otherwise", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/ndarray/sparse.py#L808-L818
23,740
apache/incubator-mxnet
python/mxnet/ndarray/sparse.py
_check_shape
def _check_shape(s1, s2): """check s1 == s2 if both are not None""" if s1 and s2 and s1 != s2: raise ValueError("Shape mismatch detected. " + str(s1) + " v.s. " + str(s2))
python
def _check_shape(s1, s2): """check s1 == s2 if both are not None""" if s1 and s2 and s1 != s2: raise ValueError("Shape mismatch detected. " + str(s1) + " v.s. " + str(s2))
[ "def", "_check_shape", "(", "s1", ",", "s2", ")", ":", "if", "s1", "and", "s2", "and", "s1", "!=", "s2", ":", "raise", "ValueError", "(", "\"Shape mismatch detected. \"", "+", "str", "(", "s1", ")", "+", "\" v.s. \"", "+", "str", "(", "s2", ")", ")" ]
check s1 == s2 if both are not None
[ "check", "s1", "==", "s2", "if", "both", "are", "not", "None" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/ndarray/sparse.py#L820-L823
23,741
apache/incubator-mxnet
python/mxnet/ndarray/sparse.py
_csr_matrix_from_definition
def _csr_matrix_from_definition(data, indices, indptr, shape=None, ctx=None, dtype=None, indices_type=None, indptr_type=None): """Create a `CSRNDArray` based on data, indices and indptr""" # pylint: disable= no-member, protected-access storage_type = 'csr' # context ctx = current_context() if ctx is None else ctx # types dtype = _prepare_default_dtype(data, dtype) indptr_type = _STORAGE_AUX_TYPES[storage_type][0] if indptr_type is None else indptr_type indices_type = _STORAGE_AUX_TYPES[storage_type][1] if indices_type is None else indices_type # prepare src array and types data = _prepare_src_array(data, dtype) indptr = _prepare_src_array(indptr, indptr_type) indices = _prepare_src_array(indices, indices_type) # TODO(junwu): Convert data, indptr, and indices to mxnet NDArrays # if they are not for now. In the future, we should provide a c-api # to accept np.ndarray types to copy from to result.data and aux_data if not isinstance(data, NDArray): data = _array(data, ctx, dtype) if not isinstance(indptr, NDArray): indptr = _array(indptr, ctx, indptr_type) if not isinstance(indices, NDArray): indices = _array(indices, ctx, indices_type) if shape is None: if indices.shape[0] == 0: raise ValueError('invalid shape') shape = (len(indptr) - 1, op.max(indices).asscalar() + 1) # verify shapes aux_shapes = [indptr.shape, indices.shape] if data.ndim != 1 or indptr.ndim != 1 or indices.ndim != 1 or \ indptr.shape[0] == 0 or len(shape) != 2: raise ValueError('invalid shape') result = CSRNDArray(_new_alloc_handle(storage_type, shape, ctx, False, dtype, [indptr_type, indices_type], aux_shapes)) check_call(_LIB.MXNDArraySyncCopyFromNDArray(result.handle, data.handle, ctypes.c_int(-1))) check_call(_LIB.MXNDArraySyncCopyFromNDArray(result.handle, indptr.handle, ctypes.c_int(0))) check_call(_LIB.MXNDArraySyncCopyFromNDArray(result.handle, indices.handle, ctypes.c_int(1))) return result
python
def _csr_matrix_from_definition(data, indices, indptr, shape=None, ctx=None, dtype=None, indices_type=None, indptr_type=None): """Create a `CSRNDArray` based on data, indices and indptr""" # pylint: disable= no-member, protected-access storage_type = 'csr' # context ctx = current_context() if ctx is None else ctx # types dtype = _prepare_default_dtype(data, dtype) indptr_type = _STORAGE_AUX_TYPES[storage_type][0] if indptr_type is None else indptr_type indices_type = _STORAGE_AUX_TYPES[storage_type][1] if indices_type is None else indices_type # prepare src array and types data = _prepare_src_array(data, dtype) indptr = _prepare_src_array(indptr, indptr_type) indices = _prepare_src_array(indices, indices_type) # TODO(junwu): Convert data, indptr, and indices to mxnet NDArrays # if they are not for now. In the future, we should provide a c-api # to accept np.ndarray types to copy from to result.data and aux_data if not isinstance(data, NDArray): data = _array(data, ctx, dtype) if not isinstance(indptr, NDArray): indptr = _array(indptr, ctx, indptr_type) if not isinstance(indices, NDArray): indices = _array(indices, ctx, indices_type) if shape is None: if indices.shape[0] == 0: raise ValueError('invalid shape') shape = (len(indptr) - 1, op.max(indices).asscalar() + 1) # verify shapes aux_shapes = [indptr.shape, indices.shape] if data.ndim != 1 or indptr.ndim != 1 or indices.ndim != 1 or \ indptr.shape[0] == 0 or len(shape) != 2: raise ValueError('invalid shape') result = CSRNDArray(_new_alloc_handle(storage_type, shape, ctx, False, dtype, [indptr_type, indices_type], aux_shapes)) check_call(_LIB.MXNDArraySyncCopyFromNDArray(result.handle, data.handle, ctypes.c_int(-1))) check_call(_LIB.MXNDArraySyncCopyFromNDArray(result.handle, indptr.handle, ctypes.c_int(0))) check_call(_LIB.MXNDArraySyncCopyFromNDArray(result.handle, indices.handle, ctypes.c_int(1))) return result
[ "def", "_csr_matrix_from_definition", "(", "data", ",", "indices", ",", "indptr", ",", "shape", "=", "None", ",", "ctx", "=", "None", ",", "dtype", "=", "None", ",", "indices_type", "=", "None", ",", "indptr_type", "=", "None", ")", ":", "# pylint: disable= no-member, protected-access", "storage_type", "=", "'csr'", "# context", "ctx", "=", "current_context", "(", ")", "if", "ctx", "is", "None", "else", "ctx", "# types", "dtype", "=", "_prepare_default_dtype", "(", "data", ",", "dtype", ")", "indptr_type", "=", "_STORAGE_AUX_TYPES", "[", "storage_type", "]", "[", "0", "]", "if", "indptr_type", "is", "None", "else", "indptr_type", "indices_type", "=", "_STORAGE_AUX_TYPES", "[", "storage_type", "]", "[", "1", "]", "if", "indices_type", "is", "None", "else", "indices_type", "# prepare src array and types", "data", "=", "_prepare_src_array", "(", "data", ",", "dtype", ")", "indptr", "=", "_prepare_src_array", "(", "indptr", ",", "indptr_type", ")", "indices", "=", "_prepare_src_array", "(", "indices", ",", "indices_type", ")", "# TODO(junwu): Convert data, indptr, and indices to mxnet NDArrays", "# if they are not for now. In the future, we should provide a c-api", "# to accept np.ndarray types to copy from to result.data and aux_data", "if", "not", "isinstance", "(", "data", ",", "NDArray", ")", ":", "data", "=", "_array", "(", "data", ",", "ctx", ",", "dtype", ")", "if", "not", "isinstance", "(", "indptr", ",", "NDArray", ")", ":", "indptr", "=", "_array", "(", "indptr", ",", "ctx", ",", "indptr_type", ")", "if", "not", "isinstance", "(", "indices", ",", "NDArray", ")", ":", "indices", "=", "_array", "(", "indices", ",", "ctx", ",", "indices_type", ")", "if", "shape", "is", "None", ":", "if", "indices", ".", "shape", "[", "0", "]", "==", "0", ":", "raise", "ValueError", "(", "'invalid shape'", ")", "shape", "=", "(", "len", "(", "indptr", ")", "-", "1", ",", "op", ".", "max", "(", "indices", ")", ".", "asscalar", "(", ")", "+", "1", ")", "# verify shapes", "aux_shapes", "=", "[", "indptr", ".", "shape", ",", "indices", ".", "shape", "]", "if", "data", ".", "ndim", "!=", "1", "or", "indptr", ".", "ndim", "!=", "1", "or", "indices", ".", "ndim", "!=", "1", "or", "indptr", ".", "shape", "[", "0", "]", "==", "0", "or", "len", "(", "shape", ")", "!=", "2", ":", "raise", "ValueError", "(", "'invalid shape'", ")", "result", "=", "CSRNDArray", "(", "_new_alloc_handle", "(", "storage_type", ",", "shape", ",", "ctx", ",", "False", ",", "dtype", ",", "[", "indptr_type", ",", "indices_type", "]", ",", "aux_shapes", ")", ")", "check_call", "(", "_LIB", ".", "MXNDArraySyncCopyFromNDArray", "(", "result", ".", "handle", ",", "data", ".", "handle", ",", "ctypes", ".", "c_int", "(", "-", "1", ")", ")", ")", "check_call", "(", "_LIB", ".", "MXNDArraySyncCopyFromNDArray", "(", "result", ".", "handle", ",", "indptr", ".", "handle", ",", "ctypes", ".", "c_int", "(", "0", ")", ")", ")", "check_call", "(", "_LIB", ".", "MXNDArraySyncCopyFromNDArray", "(", "result", ".", "handle", ",", "indices", ".", "handle", ",", "ctypes", ".", "c_int", "(", "1", ")", ")", ")", "return", "result" ]
Create a `CSRNDArray` based on data, indices and indptr
[ "Create", "a", "CSRNDArray", "based", "on", "data", "indices", "and", "indptr" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/ndarray/sparse.py#L978-L1017
23,742
apache/incubator-mxnet
python/mxnet/ndarray/sparse.py
row_sparse_array
def row_sparse_array(arg1, shape=None, ctx=None, dtype=None): """Creates a `RowSparseNDArray`, a multidimensional row sparse array with a set of \ tensor slices at given indices. The RowSparseNDArray can be instantiated in several ways: - row_sparse_array(D): to construct a RowSparseNDArray with a dense ndarray ``D`` - **D** (*array_like*) - An object exposing the array interface, an object whose \ `__array__` method returns an array, or any (nested) sequence. - **ctx** (*Context, optional*) - Device context \ (default is the current default context). - **dtype** (*str or numpy.dtype, optional*) - The data type of the output array. \ The default dtype is ``D.dtype`` if ``D`` is an NDArray or numpy.ndarray, \ float32 otherwise. - row_sparse_array(S) to construct a RowSparseNDArray with a sparse ndarray ``S`` - **S** (*RowSparseNDArray*) - A sparse ndarray. - **ctx** (*Context, optional*) - Device context \ (default is the current default context). - **dtype** (*str or numpy.dtype, optional*) - The data type of the output array. \ The default dtype is ``S.dtype``. - row_sparse_array((D0, D1 .. Dn)) to construct an empty RowSparseNDArray with shape ``(D0, D1, ... Dn)`` - **D0, D1 .. Dn** (*int*) - The shape of the ndarray - **ctx** (*Context, optional*) - Device context \ (default is the current default context). - **dtype** (*str or numpy.dtype, optional*) - The data type of the output array. \ The default dtype is float32. - row_sparse_array((data, indices)) to construct a RowSparseNDArray based on the definition of row sparse format \ using two separate arrays, \ where the `indices` stores the indices of the row slices with non-zeros, while the values are stored in `data`. The corresponding NDArray ``dense`` represented by RowSparseNDArray ``rsp`` has \ ``dense[rsp.indices[i], :, :, :, ...] = rsp.data[i, :, :, :, ...]`` The row indices for are expected to be **sorted in ascending order.** \ - **data** (*array_like*) - An object exposing the array interface, which \ holds all the non-zero row slices of the array. - **indices** (*array_like*) - An object exposing the array interface, which \ stores the row index for each row slice with non-zero elements. - **shape** (*tuple of int, optional*) - The shape of the array. The default \ shape is inferred from the indices and indptr arrays. - **ctx** (*Context, optional*) - Device context \ (default is the current default context). - **dtype** (*str or numpy.dtype, optional*) - The data type of the output array. \ The default dtype is float32. Parameters ---------- arg1 : NDArray, numpy.ndarray, RowSparseNDArray, tuple of int or tuple of array_like The argument to help instantiate the row sparse ndarray. See above for further details. shape : tuple of int, optional The shape of the row sparse ndarray. (Default value = None) ctx : Context, optional Device context (default is the current default context). dtype : str or numpy.dtype, optional The data type of the output array. (Default value = None) Returns ------- RowSparseNDArray An `RowSparseNDArray` with the `row_sparse` storage representation. Examples -------- >>> a = mx.nd.sparse.row_sparse_array(([[1, 2], [3, 4]], [1, 4]), shape=(6, 2)) >>> a.asnumpy() array([[ 0., 0.], [ 1., 2.], [ 0., 0.], [ 0., 0.], [ 3., 4.], [ 0., 0.]], dtype=float32) See Also -------- RowSparseNDArray : MXNet NDArray in row sparse format. """ # construct a row sparse array from (D0, D1 ..) or (data, indices) if isinstance(arg1, tuple): arg_len = len(arg1) if arg_len < 2: raise ValueError("Unexpected length of input tuple: " + str(arg_len)) elif arg_len > 2: # empty ndarray with shape _check_shape(arg1, shape) return empty('row_sparse', arg1, ctx=ctx, dtype=dtype) else: # len(arg1) = 2, is either shape or (data, indices) if isinstance(arg1[0], integer_types) and isinstance(arg1[1], integer_types): # empty ndarray with shape _check_shape(arg1, shape) return empty('row_sparse', arg1, ctx=ctx, dtype=dtype) else: # data, indices, indptr return _row_sparse_ndarray_from_definition(arg1[0], arg1[1], shape=shape, ctx=ctx, dtype=dtype) else: # construct a row sparse ndarray from a dense / sparse array if isinstance(arg1, RowSparseNDArray): # construct a row sparse ndarray from RowSparseNDArray _check_shape(arg1.shape, shape) return array(arg1, ctx=ctx, dtype=dtype) elif isinstance(arg1, CSRNDArray): raise ValueError("Unexpected input type: CSRNDArray") else: # construct a csr matrix from a dense one # prepare default dtype since mx.nd.array doesn't use default values # based on source_array dtype = _prepare_default_dtype(arg1, dtype) # create dns array with provided dtype. ctx is not passed since copy across # ctx requires dtype to be the same dns = _array(arg1, dtype=dtype) if ctx is not None and dns.context != ctx: dns = dns.as_in_context(ctx) _check_shape(dns.shape, shape) return dns.tostype('row_sparse')
python
def row_sparse_array(arg1, shape=None, ctx=None, dtype=None): """Creates a `RowSparseNDArray`, a multidimensional row sparse array with a set of \ tensor slices at given indices. The RowSparseNDArray can be instantiated in several ways: - row_sparse_array(D): to construct a RowSparseNDArray with a dense ndarray ``D`` - **D** (*array_like*) - An object exposing the array interface, an object whose \ `__array__` method returns an array, or any (nested) sequence. - **ctx** (*Context, optional*) - Device context \ (default is the current default context). - **dtype** (*str or numpy.dtype, optional*) - The data type of the output array. \ The default dtype is ``D.dtype`` if ``D`` is an NDArray or numpy.ndarray, \ float32 otherwise. - row_sparse_array(S) to construct a RowSparseNDArray with a sparse ndarray ``S`` - **S** (*RowSparseNDArray*) - A sparse ndarray. - **ctx** (*Context, optional*) - Device context \ (default is the current default context). - **dtype** (*str or numpy.dtype, optional*) - The data type of the output array. \ The default dtype is ``S.dtype``. - row_sparse_array((D0, D1 .. Dn)) to construct an empty RowSparseNDArray with shape ``(D0, D1, ... Dn)`` - **D0, D1 .. Dn** (*int*) - The shape of the ndarray - **ctx** (*Context, optional*) - Device context \ (default is the current default context). - **dtype** (*str or numpy.dtype, optional*) - The data type of the output array. \ The default dtype is float32. - row_sparse_array((data, indices)) to construct a RowSparseNDArray based on the definition of row sparse format \ using two separate arrays, \ where the `indices` stores the indices of the row slices with non-zeros, while the values are stored in `data`. The corresponding NDArray ``dense`` represented by RowSparseNDArray ``rsp`` has \ ``dense[rsp.indices[i], :, :, :, ...] = rsp.data[i, :, :, :, ...]`` The row indices for are expected to be **sorted in ascending order.** \ - **data** (*array_like*) - An object exposing the array interface, which \ holds all the non-zero row slices of the array. - **indices** (*array_like*) - An object exposing the array interface, which \ stores the row index for each row slice with non-zero elements. - **shape** (*tuple of int, optional*) - The shape of the array. The default \ shape is inferred from the indices and indptr arrays. - **ctx** (*Context, optional*) - Device context \ (default is the current default context). - **dtype** (*str or numpy.dtype, optional*) - The data type of the output array. \ The default dtype is float32. Parameters ---------- arg1 : NDArray, numpy.ndarray, RowSparseNDArray, tuple of int or tuple of array_like The argument to help instantiate the row sparse ndarray. See above for further details. shape : tuple of int, optional The shape of the row sparse ndarray. (Default value = None) ctx : Context, optional Device context (default is the current default context). dtype : str or numpy.dtype, optional The data type of the output array. (Default value = None) Returns ------- RowSparseNDArray An `RowSparseNDArray` with the `row_sparse` storage representation. Examples -------- >>> a = mx.nd.sparse.row_sparse_array(([[1, 2], [3, 4]], [1, 4]), shape=(6, 2)) >>> a.asnumpy() array([[ 0., 0.], [ 1., 2.], [ 0., 0.], [ 0., 0.], [ 3., 4.], [ 0., 0.]], dtype=float32) See Also -------- RowSparseNDArray : MXNet NDArray in row sparse format. """ # construct a row sparse array from (D0, D1 ..) or (data, indices) if isinstance(arg1, tuple): arg_len = len(arg1) if arg_len < 2: raise ValueError("Unexpected length of input tuple: " + str(arg_len)) elif arg_len > 2: # empty ndarray with shape _check_shape(arg1, shape) return empty('row_sparse', arg1, ctx=ctx, dtype=dtype) else: # len(arg1) = 2, is either shape or (data, indices) if isinstance(arg1[0], integer_types) and isinstance(arg1[1], integer_types): # empty ndarray with shape _check_shape(arg1, shape) return empty('row_sparse', arg1, ctx=ctx, dtype=dtype) else: # data, indices, indptr return _row_sparse_ndarray_from_definition(arg1[0], arg1[1], shape=shape, ctx=ctx, dtype=dtype) else: # construct a row sparse ndarray from a dense / sparse array if isinstance(arg1, RowSparseNDArray): # construct a row sparse ndarray from RowSparseNDArray _check_shape(arg1.shape, shape) return array(arg1, ctx=ctx, dtype=dtype) elif isinstance(arg1, CSRNDArray): raise ValueError("Unexpected input type: CSRNDArray") else: # construct a csr matrix from a dense one # prepare default dtype since mx.nd.array doesn't use default values # based on source_array dtype = _prepare_default_dtype(arg1, dtype) # create dns array with provided dtype. ctx is not passed since copy across # ctx requires dtype to be the same dns = _array(arg1, dtype=dtype) if ctx is not None and dns.context != ctx: dns = dns.as_in_context(ctx) _check_shape(dns.shape, shape) return dns.tostype('row_sparse')
[ "def", "row_sparse_array", "(", "arg1", ",", "shape", "=", "None", ",", "ctx", "=", "None", ",", "dtype", "=", "None", ")", ":", "# construct a row sparse array from (D0, D1 ..) or (data, indices)", "if", "isinstance", "(", "arg1", ",", "tuple", ")", ":", "arg_len", "=", "len", "(", "arg1", ")", "if", "arg_len", "<", "2", ":", "raise", "ValueError", "(", "\"Unexpected length of input tuple: \"", "+", "str", "(", "arg_len", ")", ")", "elif", "arg_len", ">", "2", ":", "# empty ndarray with shape", "_check_shape", "(", "arg1", ",", "shape", ")", "return", "empty", "(", "'row_sparse'", ",", "arg1", ",", "ctx", "=", "ctx", ",", "dtype", "=", "dtype", ")", "else", ":", "# len(arg1) = 2, is either shape or (data, indices)", "if", "isinstance", "(", "arg1", "[", "0", "]", ",", "integer_types", ")", "and", "isinstance", "(", "arg1", "[", "1", "]", ",", "integer_types", ")", ":", "# empty ndarray with shape", "_check_shape", "(", "arg1", ",", "shape", ")", "return", "empty", "(", "'row_sparse'", ",", "arg1", ",", "ctx", "=", "ctx", ",", "dtype", "=", "dtype", ")", "else", ":", "# data, indices, indptr", "return", "_row_sparse_ndarray_from_definition", "(", "arg1", "[", "0", "]", ",", "arg1", "[", "1", "]", ",", "shape", "=", "shape", ",", "ctx", "=", "ctx", ",", "dtype", "=", "dtype", ")", "else", ":", "# construct a row sparse ndarray from a dense / sparse array", "if", "isinstance", "(", "arg1", ",", "RowSparseNDArray", ")", ":", "# construct a row sparse ndarray from RowSparseNDArray", "_check_shape", "(", "arg1", ".", "shape", ",", "shape", ")", "return", "array", "(", "arg1", ",", "ctx", "=", "ctx", ",", "dtype", "=", "dtype", ")", "elif", "isinstance", "(", "arg1", ",", "CSRNDArray", ")", ":", "raise", "ValueError", "(", "\"Unexpected input type: CSRNDArray\"", ")", "else", ":", "# construct a csr matrix from a dense one", "# prepare default dtype since mx.nd.array doesn't use default values", "# based on source_array", "dtype", "=", "_prepare_default_dtype", "(", "arg1", ",", "dtype", ")", "# create dns array with provided dtype. ctx is not passed since copy across", "# ctx requires dtype to be the same", "dns", "=", "_array", "(", "arg1", ",", "dtype", "=", "dtype", ")", "if", "ctx", "is", "not", "None", "and", "dns", ".", "context", "!=", "ctx", ":", "dns", "=", "dns", ".", "as_in_context", "(", "ctx", ")", "_check_shape", "(", "dns", ".", "shape", ",", "shape", ")", "return", "dns", ".", "tostype", "(", "'row_sparse'", ")" ]
Creates a `RowSparseNDArray`, a multidimensional row sparse array with a set of \ tensor slices at given indices. The RowSparseNDArray can be instantiated in several ways: - row_sparse_array(D): to construct a RowSparseNDArray with a dense ndarray ``D`` - **D** (*array_like*) - An object exposing the array interface, an object whose \ `__array__` method returns an array, or any (nested) sequence. - **ctx** (*Context, optional*) - Device context \ (default is the current default context). - **dtype** (*str or numpy.dtype, optional*) - The data type of the output array. \ The default dtype is ``D.dtype`` if ``D`` is an NDArray or numpy.ndarray, \ float32 otherwise. - row_sparse_array(S) to construct a RowSparseNDArray with a sparse ndarray ``S`` - **S** (*RowSparseNDArray*) - A sparse ndarray. - **ctx** (*Context, optional*) - Device context \ (default is the current default context). - **dtype** (*str or numpy.dtype, optional*) - The data type of the output array. \ The default dtype is ``S.dtype``. - row_sparse_array((D0, D1 .. Dn)) to construct an empty RowSparseNDArray with shape ``(D0, D1, ... Dn)`` - **D0, D1 .. Dn** (*int*) - The shape of the ndarray - **ctx** (*Context, optional*) - Device context \ (default is the current default context). - **dtype** (*str or numpy.dtype, optional*) - The data type of the output array. \ The default dtype is float32. - row_sparse_array((data, indices)) to construct a RowSparseNDArray based on the definition of row sparse format \ using two separate arrays, \ where the `indices` stores the indices of the row slices with non-zeros, while the values are stored in `data`. The corresponding NDArray ``dense`` represented by RowSparseNDArray ``rsp`` has \ ``dense[rsp.indices[i], :, :, :, ...] = rsp.data[i, :, :, :, ...]`` The row indices for are expected to be **sorted in ascending order.** \ - **data** (*array_like*) - An object exposing the array interface, which \ holds all the non-zero row slices of the array. - **indices** (*array_like*) - An object exposing the array interface, which \ stores the row index for each row slice with non-zero elements. - **shape** (*tuple of int, optional*) - The shape of the array. The default \ shape is inferred from the indices and indptr arrays. - **ctx** (*Context, optional*) - Device context \ (default is the current default context). - **dtype** (*str or numpy.dtype, optional*) - The data type of the output array. \ The default dtype is float32. Parameters ---------- arg1 : NDArray, numpy.ndarray, RowSparseNDArray, tuple of int or tuple of array_like The argument to help instantiate the row sparse ndarray. See above for further details. shape : tuple of int, optional The shape of the row sparse ndarray. (Default value = None) ctx : Context, optional Device context (default is the current default context). dtype : str or numpy.dtype, optional The data type of the output array. (Default value = None) Returns ------- RowSparseNDArray An `RowSparseNDArray` with the `row_sparse` storage representation. Examples -------- >>> a = mx.nd.sparse.row_sparse_array(([[1, 2], [3, 4]], [1, 4]), shape=(6, 2)) >>> a.asnumpy() array([[ 0., 0.], [ 1., 2.], [ 0., 0.], [ 0., 0.], [ 3., 4.], [ 0., 0.]], dtype=float32) See Also -------- RowSparseNDArray : MXNet NDArray in row sparse format.
[ "Creates", "a", "RowSparseNDArray", "a", "multidimensional", "row", "sparse", "array", "with", "a", "set", "of", "\\", "tensor", "slices", "at", "given", "indices", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/ndarray/sparse.py#L1020-L1140
23,743
apache/incubator-mxnet
python/mxnet/ndarray/sparse.py
_row_sparse_ndarray_from_definition
def _row_sparse_ndarray_from_definition(data, indices, shape=None, ctx=None, dtype=None, indices_type=None): """Create a `RowSparseNDArray` based on data and indices""" storage_type = 'row_sparse' # context ctx = current_context() if ctx is None else ctx # types dtype = _prepare_default_dtype(data, dtype) indices_type = _STORAGE_AUX_TYPES[storage_type][0] if indices_type is None else indices_type # prepare src array and types data = _prepare_src_array(data, dtype) indices = _prepare_src_array(indices, indices_type) # TODO(junwu): Convert data, indptr, and indices to mxnet NDArrays # if they are not for now. In the future, we should provide a c-api # to accept np.ndarray types to copy from to result.data and aux_data if not isinstance(data, NDArray): data = _array(data, ctx, dtype) if not isinstance(indices, NDArray): indices = _array(indices, ctx, indices_type) if shape is None: num_indices = indices.shape[0] if num_indices == 0: raise ValueError('invalid shape') dim0 = indices[num_indices - 1].asscalar() + 1 shape = (dim0, ) + data.shape[1:] # verify shapes if data.ndim != len(shape) or indices.ndim != 1 or np.prod(shape[1:]) == 0: raise ValueError("invalid shape") result = RowSparseNDArray(_new_alloc_handle(storage_type, shape, ctx, False, dtype, [indices_type], [indices.shape])) check_call(_LIB.MXNDArraySyncCopyFromNDArray(result.handle, data.handle, ctypes.c_int(-1))) check_call(_LIB.MXNDArraySyncCopyFromNDArray(result.handle, indices.handle, ctypes.c_int(0))) return result
python
def _row_sparse_ndarray_from_definition(data, indices, shape=None, ctx=None, dtype=None, indices_type=None): """Create a `RowSparseNDArray` based on data and indices""" storage_type = 'row_sparse' # context ctx = current_context() if ctx is None else ctx # types dtype = _prepare_default_dtype(data, dtype) indices_type = _STORAGE_AUX_TYPES[storage_type][0] if indices_type is None else indices_type # prepare src array and types data = _prepare_src_array(data, dtype) indices = _prepare_src_array(indices, indices_type) # TODO(junwu): Convert data, indptr, and indices to mxnet NDArrays # if they are not for now. In the future, we should provide a c-api # to accept np.ndarray types to copy from to result.data and aux_data if not isinstance(data, NDArray): data = _array(data, ctx, dtype) if not isinstance(indices, NDArray): indices = _array(indices, ctx, indices_type) if shape is None: num_indices = indices.shape[0] if num_indices == 0: raise ValueError('invalid shape') dim0 = indices[num_indices - 1].asscalar() + 1 shape = (dim0, ) + data.shape[1:] # verify shapes if data.ndim != len(shape) or indices.ndim != 1 or np.prod(shape[1:]) == 0: raise ValueError("invalid shape") result = RowSparseNDArray(_new_alloc_handle(storage_type, shape, ctx, False, dtype, [indices_type], [indices.shape])) check_call(_LIB.MXNDArraySyncCopyFromNDArray(result.handle, data.handle, ctypes.c_int(-1))) check_call(_LIB.MXNDArraySyncCopyFromNDArray(result.handle, indices.handle, ctypes.c_int(0))) return result
[ "def", "_row_sparse_ndarray_from_definition", "(", "data", ",", "indices", ",", "shape", "=", "None", ",", "ctx", "=", "None", ",", "dtype", "=", "None", ",", "indices_type", "=", "None", ")", ":", "storage_type", "=", "'row_sparse'", "# context", "ctx", "=", "current_context", "(", ")", "if", "ctx", "is", "None", "else", "ctx", "# types", "dtype", "=", "_prepare_default_dtype", "(", "data", ",", "dtype", ")", "indices_type", "=", "_STORAGE_AUX_TYPES", "[", "storage_type", "]", "[", "0", "]", "if", "indices_type", "is", "None", "else", "indices_type", "# prepare src array and types", "data", "=", "_prepare_src_array", "(", "data", ",", "dtype", ")", "indices", "=", "_prepare_src_array", "(", "indices", ",", "indices_type", ")", "# TODO(junwu): Convert data, indptr, and indices to mxnet NDArrays", "# if they are not for now. In the future, we should provide a c-api", "# to accept np.ndarray types to copy from to result.data and aux_data", "if", "not", "isinstance", "(", "data", ",", "NDArray", ")", ":", "data", "=", "_array", "(", "data", ",", "ctx", ",", "dtype", ")", "if", "not", "isinstance", "(", "indices", ",", "NDArray", ")", ":", "indices", "=", "_array", "(", "indices", ",", "ctx", ",", "indices_type", ")", "if", "shape", "is", "None", ":", "num_indices", "=", "indices", ".", "shape", "[", "0", "]", "if", "num_indices", "==", "0", ":", "raise", "ValueError", "(", "'invalid shape'", ")", "dim0", "=", "indices", "[", "num_indices", "-", "1", "]", ".", "asscalar", "(", ")", "+", "1", "shape", "=", "(", "dim0", ",", ")", "+", "data", ".", "shape", "[", "1", ":", "]", "# verify shapes", "if", "data", ".", "ndim", "!=", "len", "(", "shape", ")", "or", "indices", ".", "ndim", "!=", "1", "or", "np", ".", "prod", "(", "shape", "[", "1", ":", "]", ")", "==", "0", ":", "raise", "ValueError", "(", "\"invalid shape\"", ")", "result", "=", "RowSparseNDArray", "(", "_new_alloc_handle", "(", "storage_type", ",", "shape", ",", "ctx", ",", "False", ",", "dtype", ",", "[", "indices_type", "]", ",", "[", "indices", ".", "shape", "]", ")", ")", "check_call", "(", "_LIB", ".", "MXNDArraySyncCopyFromNDArray", "(", "result", ".", "handle", ",", "data", ".", "handle", ",", "ctypes", ".", "c_int", "(", "-", "1", ")", ")", ")", "check_call", "(", "_LIB", ".", "MXNDArraySyncCopyFromNDArray", "(", "result", ".", "handle", ",", "indices", ".", "handle", ",", "ctypes", ".", "c_int", "(", "0", ")", ")", ")", "return", "result" ]
Create a `RowSparseNDArray` based on data and indices
[ "Create", "a", "RowSparseNDArray", "based", "on", "data", "and", "indices" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/ndarray/sparse.py#L1142-L1175
23,744
apache/incubator-mxnet
python/mxnet/ndarray/sparse.py
array
def array(source_array, ctx=None, dtype=None): """Creates a sparse array from any object exposing the array interface. Parameters ---------- source_array : RowSparseNDArray, CSRNDArray or scipy.sparse.csr.csr_matrix The source sparse array ctx : Context, optional The default context is ``source_array.context`` if ``source_array`` is an NDArray. \ The current default context otherwise. dtype : str or numpy.dtype, optional The data type of the output array. The default dtype is ``source_array.dtype`` if `source_array` is an `NDArray`, `numpy.ndarray` or `scipy.sparse.csr.csr_matrix`, \ `float32` otherwise. Returns ------- RowSparseNDArray or CSRNDArray An array with the same contents as the `source_array`. Examples -------- >>> import scipy.sparse as spsp >>> csr = spsp.csr_matrix((2, 100)) >>> mx.nd.sparse.array(csr) <CSRNDArray 2x100 @cpu(0)> >>> mx.nd.sparse.array(mx.nd.sparse.zeros('csr', (3, 2))) <CSRNDArray 3x2 @cpu(0)> >>> mx.nd.sparse.array(mx.nd.sparse.zeros('row_sparse', (3, 2))) <RowSparseNDArray 3x2 @cpu(0)> """ ctx = current_context() if ctx is None else ctx if isinstance(source_array, NDArray): assert(source_array.stype != 'default'), \ "Please use `tostype` to create RowSparseNDArray or CSRNDArray from an NDArray" # prepare dtype and ctx based on source_array, if not provided dtype = _prepare_default_dtype(source_array, dtype) # if both dtype and ctx are different from source_array, we cannot copy directly if source_array.dtype != dtype and source_array.context != ctx: arr = empty(source_array.stype, source_array.shape, dtype=dtype) arr[:] = source_array arr = arr.as_in_context(ctx) else: arr = empty(source_array.stype, source_array.shape, dtype=dtype, ctx=ctx) arr[:] = source_array return arr elif spsp and isinstance(source_array, spsp.csr.csr_matrix): # TODO(haibin) implement `_sync_copy_from` with scipy csr object to reduce a copy # preprocess scipy csr to canonical form csr = source_array.sorted_indices() csr.sum_duplicates() dtype = _prepare_default_dtype(source_array, dtype) return csr_matrix((csr.data, csr.indices, csr.indptr), shape=csr.shape, \ dtype=dtype, ctx=ctx) elif isinstance(source_array, (np.ndarray, np.generic)): raise ValueError("Please use mx.nd.array to create an NDArray with source_array of type ", type(source_array)) else: raise ValueError("Unexpected source_array type: ", type(source_array))
python
def array(source_array, ctx=None, dtype=None): """Creates a sparse array from any object exposing the array interface. Parameters ---------- source_array : RowSparseNDArray, CSRNDArray or scipy.sparse.csr.csr_matrix The source sparse array ctx : Context, optional The default context is ``source_array.context`` if ``source_array`` is an NDArray. \ The current default context otherwise. dtype : str or numpy.dtype, optional The data type of the output array. The default dtype is ``source_array.dtype`` if `source_array` is an `NDArray`, `numpy.ndarray` or `scipy.sparse.csr.csr_matrix`, \ `float32` otherwise. Returns ------- RowSparseNDArray or CSRNDArray An array with the same contents as the `source_array`. Examples -------- >>> import scipy.sparse as spsp >>> csr = spsp.csr_matrix((2, 100)) >>> mx.nd.sparse.array(csr) <CSRNDArray 2x100 @cpu(0)> >>> mx.nd.sparse.array(mx.nd.sparse.zeros('csr', (3, 2))) <CSRNDArray 3x2 @cpu(0)> >>> mx.nd.sparse.array(mx.nd.sparse.zeros('row_sparse', (3, 2))) <RowSparseNDArray 3x2 @cpu(0)> """ ctx = current_context() if ctx is None else ctx if isinstance(source_array, NDArray): assert(source_array.stype != 'default'), \ "Please use `tostype` to create RowSparseNDArray or CSRNDArray from an NDArray" # prepare dtype and ctx based on source_array, if not provided dtype = _prepare_default_dtype(source_array, dtype) # if both dtype and ctx are different from source_array, we cannot copy directly if source_array.dtype != dtype and source_array.context != ctx: arr = empty(source_array.stype, source_array.shape, dtype=dtype) arr[:] = source_array arr = arr.as_in_context(ctx) else: arr = empty(source_array.stype, source_array.shape, dtype=dtype, ctx=ctx) arr[:] = source_array return arr elif spsp and isinstance(source_array, spsp.csr.csr_matrix): # TODO(haibin) implement `_sync_copy_from` with scipy csr object to reduce a copy # preprocess scipy csr to canonical form csr = source_array.sorted_indices() csr.sum_duplicates() dtype = _prepare_default_dtype(source_array, dtype) return csr_matrix((csr.data, csr.indices, csr.indptr), shape=csr.shape, \ dtype=dtype, ctx=ctx) elif isinstance(source_array, (np.ndarray, np.generic)): raise ValueError("Please use mx.nd.array to create an NDArray with source_array of type ", type(source_array)) else: raise ValueError("Unexpected source_array type: ", type(source_array))
[ "def", "array", "(", "source_array", ",", "ctx", "=", "None", ",", "dtype", "=", "None", ")", ":", "ctx", "=", "current_context", "(", ")", "if", "ctx", "is", "None", "else", "ctx", "if", "isinstance", "(", "source_array", ",", "NDArray", ")", ":", "assert", "(", "source_array", ".", "stype", "!=", "'default'", ")", ",", "\"Please use `tostype` to create RowSparseNDArray or CSRNDArray from an NDArray\"", "# prepare dtype and ctx based on source_array, if not provided", "dtype", "=", "_prepare_default_dtype", "(", "source_array", ",", "dtype", ")", "# if both dtype and ctx are different from source_array, we cannot copy directly", "if", "source_array", ".", "dtype", "!=", "dtype", "and", "source_array", ".", "context", "!=", "ctx", ":", "arr", "=", "empty", "(", "source_array", ".", "stype", ",", "source_array", ".", "shape", ",", "dtype", "=", "dtype", ")", "arr", "[", ":", "]", "=", "source_array", "arr", "=", "arr", ".", "as_in_context", "(", "ctx", ")", "else", ":", "arr", "=", "empty", "(", "source_array", ".", "stype", ",", "source_array", ".", "shape", ",", "dtype", "=", "dtype", ",", "ctx", "=", "ctx", ")", "arr", "[", ":", "]", "=", "source_array", "return", "arr", "elif", "spsp", "and", "isinstance", "(", "source_array", ",", "spsp", ".", "csr", ".", "csr_matrix", ")", ":", "# TODO(haibin) implement `_sync_copy_from` with scipy csr object to reduce a copy", "# preprocess scipy csr to canonical form", "csr", "=", "source_array", ".", "sorted_indices", "(", ")", "csr", ".", "sum_duplicates", "(", ")", "dtype", "=", "_prepare_default_dtype", "(", "source_array", ",", "dtype", ")", "return", "csr_matrix", "(", "(", "csr", ".", "data", ",", "csr", ".", "indices", ",", "csr", ".", "indptr", ")", ",", "shape", "=", "csr", ".", "shape", ",", "dtype", "=", "dtype", ",", "ctx", "=", "ctx", ")", "elif", "isinstance", "(", "source_array", ",", "(", "np", ".", "ndarray", ",", "np", ".", "generic", ")", ")", ":", "raise", "ValueError", "(", "\"Please use mx.nd.array to create an NDArray with source_array of type \"", ",", "type", "(", "source_array", ")", ")", "else", ":", "raise", "ValueError", "(", "\"Unexpected source_array type: \"", ",", "type", "(", "source_array", ")", ")" ]
Creates a sparse array from any object exposing the array interface. Parameters ---------- source_array : RowSparseNDArray, CSRNDArray or scipy.sparse.csr.csr_matrix The source sparse array ctx : Context, optional The default context is ``source_array.context`` if ``source_array`` is an NDArray. \ The current default context otherwise. dtype : str or numpy.dtype, optional The data type of the output array. The default dtype is ``source_array.dtype`` if `source_array` is an `NDArray`, `numpy.ndarray` or `scipy.sparse.csr.csr_matrix`, \ `float32` otherwise. Returns ------- RowSparseNDArray or CSRNDArray An array with the same contents as the `source_array`. Examples -------- >>> import scipy.sparse as spsp >>> csr = spsp.csr_matrix((2, 100)) >>> mx.nd.sparse.array(csr) <CSRNDArray 2x100 @cpu(0)> >>> mx.nd.sparse.array(mx.nd.sparse.zeros('csr', (3, 2))) <CSRNDArray 3x2 @cpu(0)> >>> mx.nd.sparse.array(mx.nd.sparse.zeros('row_sparse', (3, 2))) <RowSparseNDArray 3x2 @cpu(0)>
[ "Creates", "a", "sparse", "array", "from", "any", "object", "exposing", "the", "array", "interface", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/ndarray/sparse.py#L1579-L1637
23,745
apache/incubator-mxnet
python/mxnet/ndarray/sparse.py
BaseSparseNDArray._aux_type
def _aux_type(self, i): """Data-type of the array's ith aux data. Returns ------- numpy.dtype This BaseSparseNDArray's aux data type. """ aux_type = ctypes.c_int() check_call(_LIB.MXNDArrayGetAuxType(self.handle, i, ctypes.byref(aux_type))) return _DTYPE_MX_TO_NP[aux_type.value]
python
def _aux_type(self, i): """Data-type of the array's ith aux data. Returns ------- numpy.dtype This BaseSparseNDArray's aux data type. """ aux_type = ctypes.c_int() check_call(_LIB.MXNDArrayGetAuxType(self.handle, i, ctypes.byref(aux_type))) return _DTYPE_MX_TO_NP[aux_type.value]
[ "def", "_aux_type", "(", "self", ",", "i", ")", ":", "aux_type", "=", "ctypes", ".", "c_int", "(", ")", "check_call", "(", "_LIB", ".", "MXNDArrayGetAuxType", "(", "self", ".", "handle", ",", "i", ",", "ctypes", ".", "byref", "(", "aux_type", ")", ")", ")", "return", "_DTYPE_MX_TO_NP", "[", "aux_type", ".", "value", "]" ]
Data-type of the array's ith aux data. Returns ------- numpy.dtype This BaseSparseNDArray's aux data type.
[ "Data", "-", "type", "of", "the", "array", "s", "ith", "aux", "data", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/ndarray/sparse.py#L164-L174
23,746
apache/incubator-mxnet
python/mxnet/ndarray/sparse.py
BaseSparseNDArray._aux_types
def _aux_types(self): """The data types of the aux data for the BaseSparseNDArray. """ aux_types = [] num_aux = self._num_aux for i in range(num_aux): aux_types.append(self._aux_type(i)) return aux_types
python
def _aux_types(self): """The data types of the aux data for the BaseSparseNDArray. """ aux_types = [] num_aux = self._num_aux for i in range(num_aux): aux_types.append(self._aux_type(i)) return aux_types
[ "def", "_aux_types", "(", "self", ")", ":", "aux_types", "=", "[", "]", "num_aux", "=", "self", ".", "_num_aux", "for", "i", "in", "range", "(", "num_aux", ")", ":", "aux_types", ".", "append", "(", "self", ".", "_aux_type", "(", "i", ")", ")", "return", "aux_types" ]
The data types of the aux data for the BaseSparseNDArray.
[ "The", "data", "types", "of", "the", "aux", "data", "for", "the", "BaseSparseNDArray", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/ndarray/sparse.py#L183-L190
23,747
apache/incubator-mxnet
python/mxnet/ndarray/sparse.py
BaseSparseNDArray.astype
def astype(self, dtype, copy=True): """Return a copy of the array after casting to a specified type. Parameters ---------- dtype : numpy.dtype or str The type of the returned array. copy : bool Default `True`. By default, astype always returns a newly allocated ndarray on the same context. If this is set to `False`, and the dtype requested is the same as the ndarray's dtype, the ndarray is returned instead of a copy. Examples -------- >>> x = mx.nd.sparse.zeros('row_sparse', (2,3), dtype='float32') >>> y = x.astype('int32') >>> y.dtype <type 'numpy.int32'> """ if not copy and np.dtype(dtype) == self.dtype: return self res = zeros(shape=self.shape, ctx=self.context, dtype=dtype, stype=self.stype) self.copyto(res) return res
python
def astype(self, dtype, copy=True): """Return a copy of the array after casting to a specified type. Parameters ---------- dtype : numpy.dtype or str The type of the returned array. copy : bool Default `True`. By default, astype always returns a newly allocated ndarray on the same context. If this is set to `False`, and the dtype requested is the same as the ndarray's dtype, the ndarray is returned instead of a copy. Examples -------- >>> x = mx.nd.sparse.zeros('row_sparse', (2,3), dtype='float32') >>> y = x.astype('int32') >>> y.dtype <type 'numpy.int32'> """ if not copy and np.dtype(dtype) == self.dtype: return self res = zeros(shape=self.shape, ctx=self.context, dtype=dtype, stype=self.stype) self.copyto(res) return res
[ "def", "astype", "(", "self", ",", "dtype", ",", "copy", "=", "True", ")", ":", "if", "not", "copy", "and", "np", ".", "dtype", "(", "dtype", ")", "==", "self", ".", "dtype", ":", "return", "self", "res", "=", "zeros", "(", "shape", "=", "self", ".", "shape", ",", "ctx", "=", "self", ".", "context", ",", "dtype", "=", "dtype", ",", "stype", "=", "self", ".", "stype", ")", "self", ".", "copyto", "(", "res", ")", "return", "res" ]
Return a copy of the array after casting to a specified type. Parameters ---------- dtype : numpy.dtype or str The type of the returned array. copy : bool Default `True`. By default, astype always returns a newly allocated ndarray on the same context. If this is set to `False`, and the dtype requested is the same as the ndarray's dtype, the ndarray is returned instead of a copy. Examples -------- >>> x = mx.nd.sparse.zeros('row_sparse', (2,3), dtype='float32') >>> y = x.astype('int32') >>> y.dtype <type 'numpy.int32'>
[ "Return", "a", "copy", "of", "the", "array", "after", "casting", "to", "a", "specified", "type", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/ndarray/sparse.py#L197-L223
23,748
apache/incubator-mxnet
python/mxnet/ndarray/sparse.py
BaseSparseNDArray.check_format
def check_format(self, full_check=True): """Check whether the NDArray format is valid. Parameters ---------- full_check : bool, optional If `True`, rigorous check, O(N) operations. Otherwise basic check, O(1) operations (default True). """ check_call(_LIB.MXNDArraySyncCheckFormat(self.handle, ctypes.c_bool(full_check)))
python
def check_format(self, full_check=True): """Check whether the NDArray format is valid. Parameters ---------- full_check : bool, optional If `True`, rigorous check, O(N) operations. Otherwise basic check, O(1) operations (default True). """ check_call(_LIB.MXNDArraySyncCheckFormat(self.handle, ctypes.c_bool(full_check)))
[ "def", "check_format", "(", "self", ",", "full_check", "=", "True", ")", ":", "check_call", "(", "_LIB", ".", "MXNDArraySyncCheckFormat", "(", "self", ".", "handle", ",", "ctypes", ".", "c_bool", "(", "full_check", ")", ")", ")" ]
Check whether the NDArray format is valid. Parameters ---------- full_check : bool, optional If `True`, rigorous check, O(N) operations. Otherwise basic check, O(1) operations (default True).
[ "Check", "whether", "the", "NDArray", "format", "is", "valid", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/ndarray/sparse.py#L252-L261
23,749
apache/incubator-mxnet
python/mxnet/ndarray/sparse.py
BaseSparseNDArray._data
def _data(self): """A deep copy NDArray of the data array associated with the BaseSparseNDArray. This function blocks. Do not use it in performance critical code. """ self.wait_to_read() hdl = NDArrayHandle() check_call(_LIB.MXNDArrayGetDataNDArray(self.handle, ctypes.byref(hdl))) return NDArray(hdl)
python
def _data(self): """A deep copy NDArray of the data array associated with the BaseSparseNDArray. This function blocks. Do not use it in performance critical code. """ self.wait_to_read() hdl = NDArrayHandle() check_call(_LIB.MXNDArrayGetDataNDArray(self.handle, ctypes.byref(hdl))) return NDArray(hdl)
[ "def", "_data", "(", "self", ")", ":", "self", ".", "wait_to_read", "(", ")", "hdl", "=", "NDArrayHandle", "(", ")", "check_call", "(", "_LIB", ".", "MXNDArrayGetDataNDArray", "(", "self", ".", "handle", ",", "ctypes", ".", "byref", "(", "hdl", ")", ")", ")", "return", "NDArray", "(", "hdl", ")" ]
A deep copy NDArray of the data array associated with the BaseSparseNDArray. This function blocks. Do not use it in performance critical code.
[ "A", "deep", "copy", "NDArray", "of", "the", "data", "array", "associated", "with", "the", "BaseSparseNDArray", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/ndarray/sparse.py#L263-L271
23,750
apache/incubator-mxnet
python/mxnet/ndarray/sparse.py
BaseSparseNDArray._aux_data
def _aux_data(self, i): """ Get a deep copy NDArray of the i-th aux data array associated with the BaseSparseNDArray. This function blocks. Do not use it in performance critical code. """ self.wait_to_read() hdl = NDArrayHandle() check_call(_LIB.MXNDArrayGetAuxNDArray(self.handle, i, ctypes.byref(hdl))) return NDArray(hdl)
python
def _aux_data(self, i): """ Get a deep copy NDArray of the i-th aux data array associated with the BaseSparseNDArray. This function blocks. Do not use it in performance critical code. """ self.wait_to_read() hdl = NDArrayHandle() check_call(_LIB.MXNDArrayGetAuxNDArray(self.handle, i, ctypes.byref(hdl))) return NDArray(hdl)
[ "def", "_aux_data", "(", "self", ",", "i", ")", ":", "self", ".", "wait_to_read", "(", ")", "hdl", "=", "NDArrayHandle", "(", ")", "check_call", "(", "_LIB", ".", "MXNDArrayGetAuxNDArray", "(", "self", ".", "handle", ",", "i", ",", "ctypes", ".", "byref", "(", "hdl", ")", ")", ")", "return", "NDArray", "(", "hdl", ")" ]
Get a deep copy NDArray of the i-th aux data array associated with the BaseSparseNDArray. This function blocks. Do not use it in performance critical code.
[ "Get", "a", "deep", "copy", "NDArray", "of", "the", "i", "-", "th", "aux", "data", "array", "associated", "with", "the", "BaseSparseNDArray", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/ndarray/sparse.py#L274-L283
23,751
apache/incubator-mxnet
python/mxnet/ndarray/sparse.py
CSRNDArray.asscipy
def asscipy(self): """Returns a ``scipy.sparse.csr.csr_matrix`` object with value copied from this array Examples -------- >>> x = mx.nd.sparse.zeros('csr', (2,3)) >>> y = x.asscipy() >>> type(y) <type 'scipy.sparse.csr.csr_matrix'> >>> y <2x3 sparse matrix of type '<type 'numpy.float32'>' with 0 stored elements in Compressed Sparse Row format> """ data = self.data.asnumpy() indices = self.indices.asnumpy() indptr = self.indptr.asnumpy() if not spsp: raise ImportError("scipy is not available. \ Please check if the scipy python bindings are installed.") return spsp.csr_matrix((data, indices, indptr), shape=self.shape, dtype=self.dtype)
python
def asscipy(self): """Returns a ``scipy.sparse.csr.csr_matrix`` object with value copied from this array Examples -------- >>> x = mx.nd.sparse.zeros('csr', (2,3)) >>> y = x.asscipy() >>> type(y) <type 'scipy.sparse.csr.csr_matrix'> >>> y <2x3 sparse matrix of type '<type 'numpy.float32'>' with 0 stored elements in Compressed Sparse Row format> """ data = self.data.asnumpy() indices = self.indices.asnumpy() indptr = self.indptr.asnumpy() if not spsp: raise ImportError("scipy is not available. \ Please check if the scipy python bindings are installed.") return spsp.csr_matrix((data, indices, indptr), shape=self.shape, dtype=self.dtype)
[ "def", "asscipy", "(", "self", ")", ":", "data", "=", "self", ".", "data", ".", "asnumpy", "(", ")", "indices", "=", "self", ".", "indices", ".", "asnumpy", "(", ")", "indptr", "=", "self", ".", "indptr", ".", "asnumpy", "(", ")", "if", "not", "spsp", ":", "raise", "ImportError", "(", "\"scipy is not available. \\\n Please check if the scipy python bindings are installed.\"", ")", "return", "spsp", ".", "csr_matrix", "(", "(", "data", ",", "indices", ",", "indptr", ")", ",", "shape", "=", "self", ".", "shape", ",", "dtype", "=", "self", ".", "dtype", ")" ]
Returns a ``scipy.sparse.csr.csr_matrix`` object with value copied from this array Examples -------- >>> x = mx.nd.sparse.zeros('csr', (2,3)) >>> y = x.asscipy() >>> type(y) <type 'scipy.sparse.csr.csr_matrix'> >>> y <2x3 sparse matrix of type '<type 'numpy.float32'>' with 0 stored elements in Compressed Sparse Row format>
[ "Returns", "a", "scipy", ".", "sparse", ".", "csr", ".", "csr_matrix", "object", "with", "value", "copied", "from", "this", "array" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/ndarray/sparse.py#L539-L558
23,752
apache/incubator-mxnet
python/mxnet/ndarray/sparse.py
RowSparseNDArray.tostype
def tostype(self, stype): """Return a copy of the array with chosen storage type. Returns ------- NDArray or RowSparseNDArray A copy of the array with the chosen storage stype """ # pylint: disable= no-member, protected-access if stype == 'csr': raise ValueError("cast_storage from row_sparse to csr is not supported") return op.cast_storage(self, stype=stype)
python
def tostype(self, stype): """Return a copy of the array with chosen storage type. Returns ------- NDArray or RowSparseNDArray A copy of the array with the chosen storage stype """ # pylint: disable= no-member, protected-access if stype == 'csr': raise ValueError("cast_storage from row_sparse to csr is not supported") return op.cast_storage(self, stype=stype)
[ "def", "tostype", "(", "self", ",", "stype", ")", ":", "# pylint: disable= no-member, protected-access", "if", "stype", "==", "'csr'", ":", "raise", "ValueError", "(", "\"cast_storage from row_sparse to csr is not supported\"", ")", "return", "op", ".", "cast_storage", "(", "self", ",", "stype", "=", "stype", ")" ]
Return a copy of the array with chosen storage type. Returns ------- NDArray or RowSparseNDArray A copy of the array with the chosen storage stype
[ "Return", "a", "copy", "of", "the", "array", "with", "chosen", "storage", "type", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/ndarray/sparse.py#L740-L751
23,753
apache/incubator-mxnet
benchmark/python/sparse/memory_benchmark.py
bench_dot
def bench_dot(lhs_row_dim, lhs_col_dim, rhs_col_dim, density, rhs_density, dot_func, trans_lhs, lhs_stype, rhs_stype, only_storage, distribution="uniform"): """ Benchmarking both storage and dot """ lhs_nd = rand_ndarray((lhs_row_dim, lhs_col_dim), lhs_stype, density, distribution=distribution) if not only_storage: rhs_nd = rand_ndarray((lhs_col_dim, rhs_col_dim), rhs_stype, density=rhs_density, distribution=distribution) out = dot_func(lhs_nd, rhs_nd, trans_lhs) mx.nd.waitall()
python
def bench_dot(lhs_row_dim, lhs_col_dim, rhs_col_dim, density, rhs_density, dot_func, trans_lhs, lhs_stype, rhs_stype, only_storage, distribution="uniform"): """ Benchmarking both storage and dot """ lhs_nd = rand_ndarray((lhs_row_dim, lhs_col_dim), lhs_stype, density, distribution=distribution) if not only_storage: rhs_nd = rand_ndarray((lhs_col_dim, rhs_col_dim), rhs_stype, density=rhs_density, distribution=distribution) out = dot_func(lhs_nd, rhs_nd, trans_lhs) mx.nd.waitall()
[ "def", "bench_dot", "(", "lhs_row_dim", ",", "lhs_col_dim", ",", "rhs_col_dim", ",", "density", ",", "rhs_density", ",", "dot_func", ",", "trans_lhs", ",", "lhs_stype", ",", "rhs_stype", ",", "only_storage", ",", "distribution", "=", "\"uniform\"", ")", ":", "lhs_nd", "=", "rand_ndarray", "(", "(", "lhs_row_dim", ",", "lhs_col_dim", ")", ",", "lhs_stype", ",", "density", ",", "distribution", "=", "distribution", ")", "if", "not", "only_storage", ":", "rhs_nd", "=", "rand_ndarray", "(", "(", "lhs_col_dim", ",", "rhs_col_dim", ")", ",", "rhs_stype", ",", "density", "=", "rhs_density", ",", "distribution", "=", "distribution", ")", "out", "=", "dot_func", "(", "lhs_nd", ",", "rhs_nd", ",", "trans_lhs", ")", "mx", ".", "nd", ".", "waitall", "(", ")" ]
Benchmarking both storage and dot
[ "Benchmarking", "both", "storage", "and", "dot" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/benchmark/python/sparse/memory_benchmark.py#L79-L89
23,754
apache/incubator-mxnet
tools/caffe_converter/convert_mean.py
convert_mean
def convert_mean(binaryproto_fname, output=None): """Convert caffe mean Parameters ---------- binaryproto_fname : str Filename of the mean output : str, optional Save the mean into mxnet's format Returns ------- NDArray Mean in ndarray """ mean_blob = caffe_parser.caffe_pb2.BlobProto() with open(binaryproto_fname, 'rb') as f: mean_blob.ParseFromString(f.read()) img_mean_np = np.array(mean_blob.data) img_mean_np = img_mean_np.reshape( mean_blob.channels, mean_blob.height, mean_blob.width ) # swap channels from Caffe BGR to RGB img_mean_np[[0, 2], :, :] = img_mean_np[[2, 0], :, :] nd = mx.nd.array(img_mean_np) if output is not None: mx.nd.save(output, {"mean_image": nd}) return nd
python
def convert_mean(binaryproto_fname, output=None): """Convert caffe mean Parameters ---------- binaryproto_fname : str Filename of the mean output : str, optional Save the mean into mxnet's format Returns ------- NDArray Mean in ndarray """ mean_blob = caffe_parser.caffe_pb2.BlobProto() with open(binaryproto_fname, 'rb') as f: mean_blob.ParseFromString(f.read()) img_mean_np = np.array(mean_blob.data) img_mean_np = img_mean_np.reshape( mean_blob.channels, mean_blob.height, mean_blob.width ) # swap channels from Caffe BGR to RGB img_mean_np[[0, 2], :, :] = img_mean_np[[2, 0], :, :] nd = mx.nd.array(img_mean_np) if output is not None: mx.nd.save(output, {"mean_image": nd}) return nd
[ "def", "convert_mean", "(", "binaryproto_fname", ",", "output", "=", "None", ")", ":", "mean_blob", "=", "caffe_parser", ".", "caffe_pb2", ".", "BlobProto", "(", ")", "with", "open", "(", "binaryproto_fname", ",", "'rb'", ")", "as", "f", ":", "mean_blob", ".", "ParseFromString", "(", "f", ".", "read", "(", ")", ")", "img_mean_np", "=", "np", ".", "array", "(", "mean_blob", ".", "data", ")", "img_mean_np", "=", "img_mean_np", ".", "reshape", "(", "mean_blob", ".", "channels", ",", "mean_blob", ".", "height", ",", "mean_blob", ".", "width", ")", "# swap channels from Caffe BGR to RGB", "img_mean_np", "[", "[", "0", ",", "2", "]", ",", ":", ",", ":", "]", "=", "img_mean_np", "[", "[", "2", ",", "0", "]", ",", ":", ",", ":", "]", "nd", "=", "mx", ".", "nd", ".", "array", "(", "img_mean_np", ")", "if", "output", "is", "not", "None", ":", "mx", ".", "nd", ".", "save", "(", "output", ",", "{", "\"mean_image\"", ":", "nd", "}", ")", "return", "nd" ]
Convert caffe mean Parameters ---------- binaryproto_fname : str Filename of the mean output : str, optional Save the mean into mxnet's format Returns ------- NDArray Mean in ndarray
[ "Convert", "caffe", "mean" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/tools/caffe_converter/convert_mean.py#L25-L53
23,755
apache/incubator-mxnet
example/ssd/symbol/symbol_builder.py
import_module
def import_module(module_name): """Helper function to import module""" import sys, os import importlib sys.path.append(os.path.dirname(__file__)) return importlib.import_module(module_name)
python
def import_module(module_name): """Helper function to import module""" import sys, os import importlib sys.path.append(os.path.dirname(__file__)) return importlib.import_module(module_name)
[ "def", "import_module", "(", "module_name", ")", ":", "import", "sys", ",", "os", "import", "importlib", "sys", ".", "path", ".", "append", "(", "os", ".", "path", ".", "dirname", "(", "__file__", ")", ")", "return", "importlib", ".", "import_module", "(", "module_name", ")" ]
Helper function to import module
[ "Helper", "function", "to", "import", "module" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/ssd/symbol/symbol_builder.py#L22-L27
23,756
apache/incubator-mxnet
example/ssd/symbol/symbol_builder.py
get_symbol_train
def get_symbol_train(network, num_classes, from_layers, num_filters, strides, pads, sizes, ratios, normalizations=-1, steps=[], min_filter=128, nms_thresh=0.5, force_suppress=False, nms_topk=400, **kwargs): """Build network symbol for training SSD Parameters ---------- network : str base network symbol name num_classes : int number of object classes not including background from_layers : list of str feature extraction layers, use '' for add extra layers For example: from_layers = ['relu4_3', 'fc7', '', '', '', ''] which means extract feature from relu4_3 and fc7, adding 4 extra layers on top of fc7 num_filters : list of int number of filters for extra layers, you can use -1 for extracted features, however, if normalization and scale is applied, the number of filter for that layer must be provided. For example: num_filters = [512, -1, 512, 256, 256, 256] strides : list of int strides for the 3x3 convolution appended, -1 can be used for extracted feature layers pads : list of int paddings for the 3x3 convolution, -1 can be used for extracted layers sizes : list or list of list [min_size, max_size] for all layers or [[], [], []...] for specific layers ratios : list or list of list [ratio1, ratio2...] for all layers or [[], [], ...] for specific layers normalizations : int or list of int use normalizations value for all layers or [...] for specific layers, -1 indicate no normalizations and scales steps : list specify steps for each MultiBoxPrior layer, leave empty, it will calculate according to layer dimensions min_filter : int minimum number of filters used in 1x1 convolution nms_thresh : float non-maximum suppression threshold force_suppress : boolean whether suppress different class objects nms_topk : int apply NMS to top K detections Returns ------- mx.Symbol """ label = mx.sym.Variable('label') body = import_module(network).get_symbol(num_classes, **kwargs) layers = multi_layer_feature(body, from_layers, num_filters, strides, pads, min_filter=min_filter) loc_preds, cls_preds, anchor_boxes = multibox_layer(layers, \ num_classes, sizes=sizes, ratios=ratios, normalization=normalizations, \ num_channels=num_filters, clip=False, interm_layer=0, steps=steps) tmp = mx.symbol.contrib.MultiBoxTarget( *[anchor_boxes, label, cls_preds], overlap_threshold=.5, \ ignore_label=-1, negative_mining_ratio=3, minimum_negative_samples=0, \ negative_mining_thresh=.5, variances=(0.1, 0.1, 0.2, 0.2), name="multibox_target") loc_target = tmp[0] loc_target_mask = tmp[1] cls_target = tmp[2] cls_prob = mx.symbol.SoftmaxOutput(data=cls_preds, label=cls_target, \ ignore_label=-1, use_ignore=True, grad_scale=1., multi_output=True, \ normalization='valid', name="cls_prob") loc_loss_ = mx.symbol.smooth_l1(name="loc_loss_", \ data=loc_target_mask * (loc_preds - loc_target), scalar=1.0) loc_loss = mx.symbol.MakeLoss(loc_loss_, grad_scale=1., \ normalization='valid', name="loc_loss") # monitoring training status cls_label = mx.symbol.MakeLoss(data=cls_target, grad_scale=0, name="cls_label") det = mx.symbol.contrib.MultiBoxDetection(*[cls_prob, loc_preds, anchor_boxes], \ name="detection", nms_threshold=nms_thresh, force_suppress=force_suppress, variances=(0.1, 0.1, 0.2, 0.2), nms_topk=nms_topk) det = mx.symbol.MakeLoss(data=det, grad_scale=0, name="det_out") # group output out = mx.symbol.Group([cls_prob, loc_loss, cls_label, det]) return out
python
def get_symbol_train(network, num_classes, from_layers, num_filters, strides, pads, sizes, ratios, normalizations=-1, steps=[], min_filter=128, nms_thresh=0.5, force_suppress=False, nms_topk=400, **kwargs): """Build network symbol for training SSD Parameters ---------- network : str base network symbol name num_classes : int number of object classes not including background from_layers : list of str feature extraction layers, use '' for add extra layers For example: from_layers = ['relu4_3', 'fc7', '', '', '', ''] which means extract feature from relu4_3 and fc7, adding 4 extra layers on top of fc7 num_filters : list of int number of filters for extra layers, you can use -1 for extracted features, however, if normalization and scale is applied, the number of filter for that layer must be provided. For example: num_filters = [512, -1, 512, 256, 256, 256] strides : list of int strides for the 3x3 convolution appended, -1 can be used for extracted feature layers pads : list of int paddings for the 3x3 convolution, -1 can be used for extracted layers sizes : list or list of list [min_size, max_size] for all layers or [[], [], []...] for specific layers ratios : list or list of list [ratio1, ratio2...] for all layers or [[], [], ...] for specific layers normalizations : int or list of int use normalizations value for all layers or [...] for specific layers, -1 indicate no normalizations and scales steps : list specify steps for each MultiBoxPrior layer, leave empty, it will calculate according to layer dimensions min_filter : int minimum number of filters used in 1x1 convolution nms_thresh : float non-maximum suppression threshold force_suppress : boolean whether suppress different class objects nms_topk : int apply NMS to top K detections Returns ------- mx.Symbol """ label = mx.sym.Variable('label') body = import_module(network).get_symbol(num_classes, **kwargs) layers = multi_layer_feature(body, from_layers, num_filters, strides, pads, min_filter=min_filter) loc_preds, cls_preds, anchor_boxes = multibox_layer(layers, \ num_classes, sizes=sizes, ratios=ratios, normalization=normalizations, \ num_channels=num_filters, clip=False, interm_layer=0, steps=steps) tmp = mx.symbol.contrib.MultiBoxTarget( *[anchor_boxes, label, cls_preds], overlap_threshold=.5, \ ignore_label=-1, negative_mining_ratio=3, minimum_negative_samples=0, \ negative_mining_thresh=.5, variances=(0.1, 0.1, 0.2, 0.2), name="multibox_target") loc_target = tmp[0] loc_target_mask = tmp[1] cls_target = tmp[2] cls_prob = mx.symbol.SoftmaxOutput(data=cls_preds, label=cls_target, \ ignore_label=-1, use_ignore=True, grad_scale=1., multi_output=True, \ normalization='valid', name="cls_prob") loc_loss_ = mx.symbol.smooth_l1(name="loc_loss_", \ data=loc_target_mask * (loc_preds - loc_target), scalar=1.0) loc_loss = mx.symbol.MakeLoss(loc_loss_, grad_scale=1., \ normalization='valid', name="loc_loss") # monitoring training status cls_label = mx.symbol.MakeLoss(data=cls_target, grad_scale=0, name="cls_label") det = mx.symbol.contrib.MultiBoxDetection(*[cls_prob, loc_preds, anchor_boxes], \ name="detection", nms_threshold=nms_thresh, force_suppress=force_suppress, variances=(0.1, 0.1, 0.2, 0.2), nms_topk=nms_topk) det = mx.symbol.MakeLoss(data=det, grad_scale=0, name="det_out") # group output out = mx.symbol.Group([cls_prob, loc_loss, cls_label, det]) return out
[ "def", "get_symbol_train", "(", "network", ",", "num_classes", ",", "from_layers", ",", "num_filters", ",", "strides", ",", "pads", ",", "sizes", ",", "ratios", ",", "normalizations", "=", "-", "1", ",", "steps", "=", "[", "]", ",", "min_filter", "=", "128", ",", "nms_thresh", "=", "0.5", ",", "force_suppress", "=", "False", ",", "nms_topk", "=", "400", ",", "*", "*", "kwargs", ")", ":", "label", "=", "mx", ".", "sym", ".", "Variable", "(", "'label'", ")", "body", "=", "import_module", "(", "network", ")", ".", "get_symbol", "(", "num_classes", ",", "*", "*", "kwargs", ")", "layers", "=", "multi_layer_feature", "(", "body", ",", "from_layers", ",", "num_filters", ",", "strides", ",", "pads", ",", "min_filter", "=", "min_filter", ")", "loc_preds", ",", "cls_preds", ",", "anchor_boxes", "=", "multibox_layer", "(", "layers", ",", "num_classes", ",", "sizes", "=", "sizes", ",", "ratios", "=", "ratios", ",", "normalization", "=", "normalizations", ",", "num_channels", "=", "num_filters", ",", "clip", "=", "False", ",", "interm_layer", "=", "0", ",", "steps", "=", "steps", ")", "tmp", "=", "mx", ".", "symbol", ".", "contrib", ".", "MultiBoxTarget", "(", "*", "[", "anchor_boxes", ",", "label", ",", "cls_preds", "]", ",", "overlap_threshold", "=", ".5", ",", "ignore_label", "=", "-", "1", ",", "negative_mining_ratio", "=", "3", ",", "minimum_negative_samples", "=", "0", ",", "negative_mining_thresh", "=", ".5", ",", "variances", "=", "(", "0.1", ",", "0.1", ",", "0.2", ",", "0.2", ")", ",", "name", "=", "\"multibox_target\"", ")", "loc_target", "=", "tmp", "[", "0", "]", "loc_target_mask", "=", "tmp", "[", "1", "]", "cls_target", "=", "tmp", "[", "2", "]", "cls_prob", "=", "mx", ".", "symbol", ".", "SoftmaxOutput", "(", "data", "=", "cls_preds", ",", "label", "=", "cls_target", ",", "ignore_label", "=", "-", "1", ",", "use_ignore", "=", "True", ",", "grad_scale", "=", "1.", ",", "multi_output", "=", "True", ",", "normalization", "=", "'valid'", ",", "name", "=", "\"cls_prob\"", ")", "loc_loss_", "=", "mx", ".", "symbol", ".", "smooth_l1", "(", "name", "=", "\"loc_loss_\"", ",", "data", "=", "loc_target_mask", "*", "(", "loc_preds", "-", "loc_target", ")", ",", "scalar", "=", "1.0", ")", "loc_loss", "=", "mx", ".", "symbol", ".", "MakeLoss", "(", "loc_loss_", ",", "grad_scale", "=", "1.", ",", "normalization", "=", "'valid'", ",", "name", "=", "\"loc_loss\"", ")", "# monitoring training status", "cls_label", "=", "mx", ".", "symbol", ".", "MakeLoss", "(", "data", "=", "cls_target", ",", "grad_scale", "=", "0", ",", "name", "=", "\"cls_label\"", ")", "det", "=", "mx", ".", "symbol", ".", "contrib", ".", "MultiBoxDetection", "(", "*", "[", "cls_prob", ",", "loc_preds", ",", "anchor_boxes", "]", ",", "name", "=", "\"detection\"", ",", "nms_threshold", "=", "nms_thresh", ",", "force_suppress", "=", "force_suppress", ",", "variances", "=", "(", "0.1", ",", "0.1", ",", "0.2", ",", "0.2", ")", ",", "nms_topk", "=", "nms_topk", ")", "det", "=", "mx", ".", "symbol", ".", "MakeLoss", "(", "data", "=", "det", ",", "grad_scale", "=", "0", ",", "name", "=", "\"det_out\"", ")", "# group output", "out", "=", "mx", ".", "symbol", ".", "Group", "(", "[", "cls_prob", ",", "loc_loss", ",", "cls_label", ",", "det", "]", ")", "return", "out" ]
Build network symbol for training SSD Parameters ---------- network : str base network symbol name num_classes : int number of object classes not including background from_layers : list of str feature extraction layers, use '' for add extra layers For example: from_layers = ['relu4_3', 'fc7', '', '', '', ''] which means extract feature from relu4_3 and fc7, adding 4 extra layers on top of fc7 num_filters : list of int number of filters for extra layers, you can use -1 for extracted features, however, if normalization and scale is applied, the number of filter for that layer must be provided. For example: num_filters = [512, -1, 512, 256, 256, 256] strides : list of int strides for the 3x3 convolution appended, -1 can be used for extracted feature layers pads : list of int paddings for the 3x3 convolution, -1 can be used for extracted layers sizes : list or list of list [min_size, max_size] for all layers or [[], [], []...] for specific layers ratios : list or list of list [ratio1, ratio2...] for all layers or [[], [], ...] for specific layers normalizations : int or list of int use normalizations value for all layers or [...] for specific layers, -1 indicate no normalizations and scales steps : list specify steps for each MultiBoxPrior layer, leave empty, it will calculate according to layer dimensions min_filter : int minimum number of filters used in 1x1 convolution nms_thresh : float non-maximum suppression threshold force_suppress : boolean whether suppress different class objects nms_topk : int apply NMS to top K detections Returns ------- mx.Symbol
[ "Build", "network", "symbol", "for", "training", "SSD" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/ssd/symbol/symbol_builder.py#L29-L116
23,757
apache/incubator-mxnet
example/ssd/symbol/symbol_builder.py
get_symbol
def get_symbol(network, num_classes, from_layers, num_filters, sizes, ratios, strides, pads, normalizations=-1, steps=[], min_filter=128, nms_thresh=0.5, force_suppress=False, nms_topk=400, **kwargs): """Build network for testing SSD Parameters ---------- network : str base network symbol name num_classes : int number of object classes not including background from_layers : list of str feature extraction layers, use '' for add extra layers For example: from_layers = ['relu4_3', 'fc7', '', '', '', ''] which means extract feature from relu4_3 and fc7, adding 4 extra layers on top of fc7 num_filters : list of int number of filters for extra layers, you can use -1 for extracted features, however, if normalization and scale is applied, the number of filter for that layer must be provided. For example: num_filters = [512, -1, 512, 256, 256, 256] strides : list of int strides for the 3x3 convolution appended, -1 can be used for extracted feature layers pads : list of int paddings for the 3x3 convolution, -1 can be used for extracted layers sizes : list or list of list [min_size, max_size] for all layers or [[], [], []...] for specific layers ratios : list or list of list [ratio1, ratio2...] for all layers or [[], [], ...] for specific layers normalizations : int or list of int use normalizations value for all layers or [...] for specific layers, -1 indicate no normalizations and scales steps : list specify steps for each MultiBoxPrior layer, leave empty, it will calculate according to layer dimensions min_filter : int minimum number of filters used in 1x1 convolution nms_thresh : float non-maximum suppression threshold force_suppress : boolean whether suppress different class objects nms_topk : int apply NMS to top K detections Returns ------- mx.Symbol """ body = import_module(network).get_symbol(num_classes, **kwargs) layers = multi_layer_feature(body, from_layers, num_filters, strides, pads, min_filter=min_filter) loc_preds, cls_preds, anchor_boxes = multibox_layer(layers, \ num_classes, sizes=sizes, ratios=ratios, normalization=normalizations, \ num_channels=num_filters, clip=False, interm_layer=0, steps=steps) cls_prob = mx.symbol.softmax(data=cls_preds, axis=1, name='cls_prob') out = mx.symbol.contrib.MultiBoxDetection(*[cls_prob, loc_preds, anchor_boxes], \ name="detection", nms_threshold=nms_thresh, force_suppress=force_suppress, variances=(0.1, 0.1, 0.2, 0.2), nms_topk=nms_topk) return out
python
def get_symbol(network, num_classes, from_layers, num_filters, sizes, ratios, strides, pads, normalizations=-1, steps=[], min_filter=128, nms_thresh=0.5, force_suppress=False, nms_topk=400, **kwargs): """Build network for testing SSD Parameters ---------- network : str base network symbol name num_classes : int number of object classes not including background from_layers : list of str feature extraction layers, use '' for add extra layers For example: from_layers = ['relu4_3', 'fc7', '', '', '', ''] which means extract feature from relu4_3 and fc7, adding 4 extra layers on top of fc7 num_filters : list of int number of filters for extra layers, you can use -1 for extracted features, however, if normalization and scale is applied, the number of filter for that layer must be provided. For example: num_filters = [512, -1, 512, 256, 256, 256] strides : list of int strides for the 3x3 convolution appended, -1 can be used for extracted feature layers pads : list of int paddings for the 3x3 convolution, -1 can be used for extracted layers sizes : list or list of list [min_size, max_size] for all layers or [[], [], []...] for specific layers ratios : list or list of list [ratio1, ratio2...] for all layers or [[], [], ...] for specific layers normalizations : int or list of int use normalizations value for all layers or [...] for specific layers, -1 indicate no normalizations and scales steps : list specify steps for each MultiBoxPrior layer, leave empty, it will calculate according to layer dimensions min_filter : int minimum number of filters used in 1x1 convolution nms_thresh : float non-maximum suppression threshold force_suppress : boolean whether suppress different class objects nms_topk : int apply NMS to top K detections Returns ------- mx.Symbol """ body = import_module(network).get_symbol(num_classes, **kwargs) layers = multi_layer_feature(body, from_layers, num_filters, strides, pads, min_filter=min_filter) loc_preds, cls_preds, anchor_boxes = multibox_layer(layers, \ num_classes, sizes=sizes, ratios=ratios, normalization=normalizations, \ num_channels=num_filters, clip=False, interm_layer=0, steps=steps) cls_prob = mx.symbol.softmax(data=cls_preds, axis=1, name='cls_prob') out = mx.symbol.contrib.MultiBoxDetection(*[cls_prob, loc_preds, anchor_boxes], \ name="detection", nms_threshold=nms_thresh, force_suppress=force_suppress, variances=(0.1, 0.1, 0.2, 0.2), nms_topk=nms_topk) return out
[ "def", "get_symbol", "(", "network", ",", "num_classes", ",", "from_layers", ",", "num_filters", ",", "sizes", ",", "ratios", ",", "strides", ",", "pads", ",", "normalizations", "=", "-", "1", ",", "steps", "=", "[", "]", ",", "min_filter", "=", "128", ",", "nms_thresh", "=", "0.5", ",", "force_suppress", "=", "False", ",", "nms_topk", "=", "400", ",", "*", "*", "kwargs", ")", ":", "body", "=", "import_module", "(", "network", ")", ".", "get_symbol", "(", "num_classes", ",", "*", "*", "kwargs", ")", "layers", "=", "multi_layer_feature", "(", "body", ",", "from_layers", ",", "num_filters", ",", "strides", ",", "pads", ",", "min_filter", "=", "min_filter", ")", "loc_preds", ",", "cls_preds", ",", "anchor_boxes", "=", "multibox_layer", "(", "layers", ",", "num_classes", ",", "sizes", "=", "sizes", ",", "ratios", "=", "ratios", ",", "normalization", "=", "normalizations", ",", "num_channels", "=", "num_filters", ",", "clip", "=", "False", ",", "interm_layer", "=", "0", ",", "steps", "=", "steps", ")", "cls_prob", "=", "mx", ".", "symbol", ".", "softmax", "(", "data", "=", "cls_preds", ",", "axis", "=", "1", ",", "name", "=", "'cls_prob'", ")", "out", "=", "mx", ".", "symbol", ".", "contrib", ".", "MultiBoxDetection", "(", "*", "[", "cls_prob", ",", "loc_preds", ",", "anchor_boxes", "]", ",", "name", "=", "\"detection\"", ",", "nms_threshold", "=", "nms_thresh", ",", "force_suppress", "=", "force_suppress", ",", "variances", "=", "(", "0.1", ",", "0.1", ",", "0.2", ",", "0.2", ")", ",", "nms_topk", "=", "nms_topk", ")", "return", "out" ]
Build network for testing SSD Parameters ---------- network : str base network symbol name num_classes : int number of object classes not including background from_layers : list of str feature extraction layers, use '' for add extra layers For example: from_layers = ['relu4_3', 'fc7', '', '', '', ''] which means extract feature from relu4_3 and fc7, adding 4 extra layers on top of fc7 num_filters : list of int number of filters for extra layers, you can use -1 for extracted features, however, if normalization and scale is applied, the number of filter for that layer must be provided. For example: num_filters = [512, -1, 512, 256, 256, 256] strides : list of int strides for the 3x3 convolution appended, -1 can be used for extracted feature layers pads : list of int paddings for the 3x3 convolution, -1 can be used for extracted layers sizes : list or list of list [min_size, max_size] for all layers or [[], [], []...] for specific layers ratios : list or list of list [ratio1, ratio2...] for all layers or [[], [], ...] for specific layers normalizations : int or list of int use normalizations value for all layers or [...] for specific layers, -1 indicate no normalizations and scales steps : list specify steps for each MultiBoxPrior layer, leave empty, it will calculate according to layer dimensions min_filter : int minimum number of filters used in 1x1 convolution nms_thresh : float non-maximum suppression threshold force_suppress : boolean whether suppress different class objects nms_topk : int apply NMS to top K detections Returns ------- mx.Symbol
[ "Build", "network", "for", "testing", "SSD" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/ssd/symbol/symbol_builder.py#L118-L182
23,758
apache/incubator-mxnet
docs/tutorial_utils/vision/cnn_visualization/gradcam.py
get_conv_out_grad
def get_conv_out_grad(net, image, class_id=None, conv_layer_name=None): """Get the output and gradients of output of a convolutional layer. Parameters: ---------- net: Block Network to use for visualization. image: NDArray Preprocessed image to use for visualization. class_id: int Category ID this image belongs to. If not provided, network's prediction will be used. conv_layer_name: str Name of the convolutional layer whose output and output's gradients need to be acptured.""" return _get_grad(net, image, class_id, conv_layer_name, image_grad=False)
python
def get_conv_out_grad(net, image, class_id=None, conv_layer_name=None): """Get the output and gradients of output of a convolutional layer. Parameters: ---------- net: Block Network to use for visualization. image: NDArray Preprocessed image to use for visualization. class_id: int Category ID this image belongs to. If not provided, network's prediction will be used. conv_layer_name: str Name of the convolutional layer whose output and output's gradients need to be acptured.""" return _get_grad(net, image, class_id, conv_layer_name, image_grad=False)
[ "def", "get_conv_out_grad", "(", "net", ",", "image", ",", "class_id", "=", "None", ",", "conv_layer_name", "=", "None", ")", ":", "return", "_get_grad", "(", "net", ",", "image", ",", "class_id", ",", "conv_layer_name", ",", "image_grad", "=", "False", ")" ]
Get the output and gradients of output of a convolutional layer. Parameters: ---------- net: Block Network to use for visualization. image: NDArray Preprocessed image to use for visualization. class_id: int Category ID this image belongs to. If not provided, network's prediction will be used. conv_layer_name: str Name of the convolutional layer whose output and output's gradients need to be acptured.
[ "Get", "the", "output", "and", "gradients", "of", "output", "of", "a", "convolutional", "layer", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/docs/tutorial_utils/vision/cnn_visualization/gradcam.py#L169-L183
23,759
apache/incubator-mxnet
docs/tutorial_utils/vision/cnn_visualization/gradcam.py
get_image_grad
def get_image_grad(net, image, class_id=None): """Get the gradients of the image. Parameters: ---------- net: Block Network to use for visualization. image: NDArray Preprocessed image to use for visualization. class_id: int Category ID this image belongs to. If not provided, network's prediction will be used.""" return _get_grad(net, image, class_id, image_grad=True)
python
def get_image_grad(net, image, class_id=None): """Get the gradients of the image. Parameters: ---------- net: Block Network to use for visualization. image: NDArray Preprocessed image to use for visualization. class_id: int Category ID this image belongs to. If not provided, network's prediction will be used.""" return _get_grad(net, image, class_id, image_grad=True)
[ "def", "get_image_grad", "(", "net", ",", "image", ",", "class_id", "=", "None", ")", ":", "return", "_get_grad", "(", "net", ",", "image", ",", "class_id", ",", "image_grad", "=", "True", ")" ]
Get the gradients of the image. Parameters: ---------- net: Block Network to use for visualization. image: NDArray Preprocessed image to use for visualization. class_id: int Category ID this image belongs to. If not provided, network's prediction will be used.
[ "Get", "the", "gradients", "of", "the", "image", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/docs/tutorial_utils/vision/cnn_visualization/gradcam.py#L185-L197
23,760
apache/incubator-mxnet
docs/tutorial_utils/vision/cnn_visualization/gradcam.py
grad_to_image
def grad_to_image(gradient): """Convert gradients of image obtained using `get_image_grad` into image. This shows parts of the image that is most strongly activating the output neurons.""" gradient = gradient - gradient.min() gradient /= gradient.max() gradient = np.uint8(gradient * 255).transpose(1, 2, 0) gradient = gradient[..., ::-1] return gradient
python
def grad_to_image(gradient): """Convert gradients of image obtained using `get_image_grad` into image. This shows parts of the image that is most strongly activating the output neurons.""" gradient = gradient - gradient.min() gradient /= gradient.max() gradient = np.uint8(gradient * 255).transpose(1, 2, 0) gradient = gradient[..., ::-1] return gradient
[ "def", "grad_to_image", "(", "gradient", ")", ":", "gradient", "=", "gradient", "-", "gradient", ".", "min", "(", ")", "gradient", "/=", "gradient", ".", "max", "(", ")", "gradient", "=", "np", ".", "uint8", "(", "gradient", "*", "255", ")", ".", "transpose", "(", "1", ",", "2", ",", "0", ")", "gradient", "=", "gradient", "[", "...", ",", ":", ":", "-", "1", "]", "return", "gradient" ]
Convert gradients of image obtained using `get_image_grad` into image. This shows parts of the image that is most strongly activating the output neurons.
[ "Convert", "gradients", "of", "image", "obtained", "using", "get_image_grad", "into", "image", ".", "This", "shows", "parts", "of", "the", "image", "that", "is", "most", "strongly", "activating", "the", "output", "neurons", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/docs/tutorial_utils/vision/cnn_visualization/gradcam.py#L199-L207
23,761
apache/incubator-mxnet
docs/tutorial_utils/vision/cnn_visualization/gradcam.py
get_img_heatmap
def get_img_heatmap(orig_img, activation_map): """Draw a heatmap on top of the original image using intensities from activation_map""" heatmap = cv2.applyColorMap(activation_map, cv2.COLORMAP_COOL) heatmap = cv2.cvtColor(heatmap, cv2.COLOR_BGR2RGB) img_heatmap = np.float32(heatmap) + np.float32(orig_img) img_heatmap = img_heatmap / np.max(img_heatmap) img_heatmap *= 255 return img_heatmap.astype(int)
python
def get_img_heatmap(orig_img, activation_map): """Draw a heatmap on top of the original image using intensities from activation_map""" heatmap = cv2.applyColorMap(activation_map, cv2.COLORMAP_COOL) heatmap = cv2.cvtColor(heatmap, cv2.COLOR_BGR2RGB) img_heatmap = np.float32(heatmap) + np.float32(orig_img) img_heatmap = img_heatmap / np.max(img_heatmap) img_heatmap *= 255 return img_heatmap.astype(int)
[ "def", "get_img_heatmap", "(", "orig_img", ",", "activation_map", ")", ":", "heatmap", "=", "cv2", ".", "applyColorMap", "(", "activation_map", ",", "cv2", ".", "COLORMAP_COOL", ")", "heatmap", "=", "cv2", ".", "cvtColor", "(", "heatmap", ",", "cv2", ".", "COLOR_BGR2RGB", ")", "img_heatmap", "=", "np", ".", "float32", "(", "heatmap", ")", "+", "np", ".", "float32", "(", "orig_img", ")", "img_heatmap", "=", "img_heatmap", "/", "np", ".", "max", "(", "img_heatmap", ")", "img_heatmap", "*=", "255", "return", "img_heatmap", ".", "astype", "(", "int", ")" ]
Draw a heatmap on top of the original image using intensities from activation_map
[ "Draw", "a", "heatmap", "on", "top", "of", "the", "original", "image", "using", "intensities", "from", "activation_map" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/docs/tutorial_utils/vision/cnn_visualization/gradcam.py#L225-L232
23,762
apache/incubator-mxnet
docs/tutorial_utils/vision/cnn_visualization/gradcam.py
to_grayscale
def to_grayscale(cv2im): """Convert gradients to grayscale. This gives a saliency map.""" # How strongly does each position activate the output grayscale_im = np.sum(np.abs(cv2im), axis=0) # Normalize between min and 99th percentile im_max = np.percentile(grayscale_im, 99) im_min = np.min(grayscale_im) grayscale_im = np.clip((grayscale_im - im_min) / (im_max - im_min), 0, 1) grayscale_im = np.expand_dims(grayscale_im, axis=0) return grayscale_im
python
def to_grayscale(cv2im): """Convert gradients to grayscale. This gives a saliency map.""" # How strongly does each position activate the output grayscale_im = np.sum(np.abs(cv2im), axis=0) # Normalize between min and 99th percentile im_max = np.percentile(grayscale_im, 99) im_min = np.min(grayscale_im) grayscale_im = np.clip((grayscale_im - im_min) / (im_max - im_min), 0, 1) grayscale_im = np.expand_dims(grayscale_im, axis=0) return grayscale_im
[ "def", "to_grayscale", "(", "cv2im", ")", ":", "# How strongly does each position activate the output", "grayscale_im", "=", "np", ".", "sum", "(", "np", ".", "abs", "(", "cv2im", ")", ",", "axis", "=", "0", ")", "# Normalize between min and 99th percentile", "im_max", "=", "np", ".", "percentile", "(", "grayscale_im", ",", "99", ")", "im_min", "=", "np", ".", "min", "(", "grayscale_im", ")", "grayscale_im", "=", "np", ".", "clip", "(", "(", "grayscale_im", "-", "im_min", ")", "/", "(", "im_max", "-", "im_min", ")", ",", "0", ",", "1", ")", "grayscale_im", "=", "np", ".", "expand_dims", "(", "grayscale_im", ",", "axis", "=", "0", ")", "return", "grayscale_im" ]
Convert gradients to grayscale. This gives a saliency map.
[ "Convert", "gradients", "to", "grayscale", ".", "This", "gives", "a", "saliency", "map", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/docs/tutorial_utils/vision/cnn_visualization/gradcam.py#L234-L245
23,763
apache/incubator-mxnet
python/mxnet/metric.py
check_label_shapes
def check_label_shapes(labels, preds, wrap=False, shape=False): """Helper function for checking shape of label and prediction Parameters ---------- labels : list of `NDArray` The labels of the data. preds : list of `NDArray` Predicted values. wrap : boolean If True, wrap labels/preds in a list if they are single NDArray shape : boolean If True, check the shape of labels and preds; Otherwise only check their length. """ if not shape: 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)) if wrap: if isinstance(labels, ndarray.ndarray.NDArray): labels = [labels] if isinstance(preds, ndarray.ndarray.NDArray): preds = [preds] return labels, preds
python
def check_label_shapes(labels, preds, wrap=False, shape=False): """Helper function for checking shape of label and prediction Parameters ---------- labels : list of `NDArray` The labels of the data. preds : list of `NDArray` Predicted values. wrap : boolean If True, wrap labels/preds in a list if they are single NDArray shape : boolean If True, check the shape of labels and preds; Otherwise only check their length. """ if not shape: 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)) if wrap: if isinstance(labels, ndarray.ndarray.NDArray): labels = [labels] if isinstance(preds, ndarray.ndarray.NDArray): preds = [preds] return labels, preds
[ "def", "check_label_shapes", "(", "labels", ",", "preds", ",", "wrap", "=", "False", ",", "shape", "=", "False", ")", ":", "if", "not", "shape", ":", "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", ")", ")", "if", "wrap", ":", "if", "isinstance", "(", "labels", ",", "ndarray", ".", "ndarray", ".", "NDArray", ")", ":", "labels", "=", "[", "labels", "]", "if", "isinstance", "(", "preds", ",", "ndarray", ".", "ndarray", ".", "NDArray", ")", ":", "preds", "=", "[", "preds", "]", "return", "labels", ",", "preds" ]
Helper function for checking shape of label and prediction Parameters ---------- labels : list of `NDArray` The labels of the data. preds : list of `NDArray` Predicted values. wrap : boolean If True, wrap labels/preds in a list if they are single NDArray shape : boolean If True, check the shape of labels and preds; Otherwise only check their length.
[ "Helper", "function", "for", "checking", "shape", "of", "label", "and", "prediction" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/metric.py#L33-L66
23,764
apache/incubator-mxnet
python/mxnet/metric.py
create
def create(metric, *args, **kwargs): """Creates evaluation metric from metric names or instances of EvalMetric or a custom metric function. Parameters ---------- metric : str or callable Specifies the metric to create. This argument must be one of the below: - Name of a metric. - An instance of `EvalMetric`. - A list, each element of which is a metric or a metric name. - An evaluation function that computes custom metric for a given batch of labels and predictions. *args : list Additional arguments to metric constructor. Only used when metric is str. **kwargs : dict Additional arguments to metric constructor. Only used when metric is str Examples -------- >>> def custom_metric(label, pred): ... return np.mean(np.abs(label - pred)) ... >>> metric1 = mx.metric.create('acc') >>> metric2 = mx.metric.create(custom_metric) >>> metric3 = mx.metric.create([metric1, metric2, 'rmse']) """ if callable(metric): return CustomMetric(metric, *args, **kwargs) elif isinstance(metric, list): composite_metric = CompositeEvalMetric() for child_metric in metric: composite_metric.add(create(child_metric, *args, **kwargs)) return composite_metric return _create(metric, *args, **kwargs)
python
def create(metric, *args, **kwargs): """Creates evaluation metric from metric names or instances of EvalMetric or a custom metric function. Parameters ---------- metric : str or callable Specifies the metric to create. This argument must be one of the below: - Name of a metric. - An instance of `EvalMetric`. - A list, each element of which is a metric or a metric name. - An evaluation function that computes custom metric for a given batch of labels and predictions. *args : list Additional arguments to metric constructor. Only used when metric is str. **kwargs : dict Additional arguments to metric constructor. Only used when metric is str Examples -------- >>> def custom_metric(label, pred): ... return np.mean(np.abs(label - pred)) ... >>> metric1 = mx.metric.create('acc') >>> metric2 = mx.metric.create(custom_metric) >>> metric3 = mx.metric.create([metric1, metric2, 'rmse']) """ if callable(metric): return CustomMetric(metric, *args, **kwargs) elif isinstance(metric, list): composite_metric = CompositeEvalMetric() for child_metric in metric: composite_metric.add(create(child_metric, *args, **kwargs)) return composite_metric return _create(metric, *args, **kwargs)
[ "def", "create", "(", "metric", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "callable", "(", "metric", ")", ":", "return", "CustomMetric", "(", "metric", ",", "*", "args", ",", "*", "*", "kwargs", ")", "elif", "isinstance", "(", "metric", ",", "list", ")", ":", "composite_metric", "=", "CompositeEvalMetric", "(", ")", "for", "child_metric", "in", "metric", ":", "composite_metric", ".", "add", "(", "create", "(", "child_metric", ",", "*", "args", ",", "*", "*", "kwargs", ")", ")", "return", "composite_metric", "return", "_create", "(", "metric", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
Creates evaluation metric from metric names or instances of EvalMetric or a custom metric function. Parameters ---------- metric : str or callable Specifies the metric to create. This argument must be one of the below: - Name of a metric. - An instance of `EvalMetric`. - A list, each element of which is a metric or a metric name. - An evaluation function that computes custom metric for a given batch of labels and predictions. *args : list Additional arguments to metric constructor. Only used when metric is str. **kwargs : dict Additional arguments to metric constructor. Only used when metric is str Examples -------- >>> def custom_metric(label, pred): ... return np.mean(np.abs(label - pred)) ... >>> metric1 = mx.metric.create('acc') >>> metric2 = mx.metric.create(custom_metric) >>> metric3 = mx.metric.create([metric1, metric2, 'rmse'])
[ "Creates", "evaluation", "metric", "from", "metric", "names", "or", "instances", "of", "EvalMetric", "or", "a", "custom", "metric", "function", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/metric.py#L234-L273
23,765
apache/incubator-mxnet
python/mxnet/metric.py
np
def np(numpy_feval, name=None, allow_extra_outputs=False): """Creates a custom evaluation metric that receives its inputs as numpy arrays. Parameters ---------- numpy_feval : callable(label, pred) Custom evaluation function that receives labels and predictions for a minibatch as numpy arrays and returns the corresponding custom metric as a floating point number. name : str, optional Name of the custom metric. allow_extra_outputs : bool, optional Whether prediction output is allowed to have extra outputs. This is useful in cases like RNN where states are also part of output which can then be fed back to the RNN in the next step. By default, extra outputs are not allowed. Returns ------- float Custom metric corresponding to the provided labels and predictions. Example ------- >>> def custom_metric(label, pred): ... return np.mean(np.abs(label-pred)) ... >>> metric = mx.metric.np(custom_metric) """ def feval(label, pred): """Internal eval function.""" return numpy_feval(label, pred) feval.__name__ = numpy_feval.__name__ return CustomMetric(feval, name, allow_extra_outputs)
python
def np(numpy_feval, name=None, allow_extra_outputs=False): """Creates a custom evaluation metric that receives its inputs as numpy arrays. Parameters ---------- numpy_feval : callable(label, pred) Custom evaluation function that receives labels and predictions for a minibatch as numpy arrays and returns the corresponding custom metric as a floating point number. name : str, optional Name of the custom metric. allow_extra_outputs : bool, optional Whether prediction output is allowed to have extra outputs. This is useful in cases like RNN where states are also part of output which can then be fed back to the RNN in the next step. By default, extra outputs are not allowed. Returns ------- float Custom metric corresponding to the provided labels and predictions. Example ------- >>> def custom_metric(label, pred): ... return np.mean(np.abs(label-pred)) ... >>> metric = mx.metric.np(custom_metric) """ def feval(label, pred): """Internal eval function.""" return numpy_feval(label, pred) feval.__name__ = numpy_feval.__name__ return CustomMetric(feval, name, allow_extra_outputs)
[ "def", "np", "(", "numpy_feval", ",", "name", "=", "None", ",", "allow_extra_outputs", "=", "False", ")", ":", "def", "feval", "(", "label", ",", "pred", ")", ":", "\"\"\"Internal eval function.\"\"\"", "return", "numpy_feval", "(", "label", ",", "pred", ")", "feval", ".", "__name__", "=", "numpy_feval", ".", "__name__", "return", "CustomMetric", "(", "feval", ",", "name", ",", "allow_extra_outputs", ")" ]
Creates a custom evaluation metric that receives its inputs as numpy arrays. Parameters ---------- numpy_feval : callable(label, pred) Custom evaluation function that receives labels and predictions for a minibatch as numpy arrays and returns the corresponding custom metric as a floating point number. name : str, optional Name of the custom metric. allow_extra_outputs : bool, optional Whether prediction output is allowed to have extra outputs. This is useful in cases like RNN where states are also part of output which can then be fed back to the RNN in the next step. By default, extra outputs are not allowed. Returns ------- float Custom metric corresponding to the provided labels and predictions. Example ------- >>> def custom_metric(label, pred): ... return np.mean(np.abs(label-pred)) ... >>> metric = mx.metric.np(custom_metric)
[ "Creates", "a", "custom", "evaluation", "metric", "that", "receives", "its", "inputs", "as", "numpy", "arrays", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/metric.py#L1747-L1778
23,766
apache/incubator-mxnet
python/mxnet/metric.py
EvalMetric.update_dict
def update_dict(self, label, pred): """Update the internal evaluation with named label and pred Parameters ---------- labels : OrderedDict of str -> NDArray name to array mapping for labels. preds : OrderedDict of str -> NDArray name to array mapping of predicted outputs. """ if self.output_names is not None: pred = [pred[name] for name in self.output_names] else: pred = list(pred.values()) if self.label_names is not None: label = [label[name] for name in self.label_names] else: label = list(label.values()) self.update(label, pred)
python
def update_dict(self, label, pred): """Update the internal evaluation with named label and pred Parameters ---------- labels : OrderedDict of str -> NDArray name to array mapping for labels. preds : OrderedDict of str -> NDArray name to array mapping of predicted outputs. """ if self.output_names is not None: pred = [pred[name] for name in self.output_names] else: pred = list(pred.values()) if self.label_names is not None: label = [label[name] for name in self.label_names] else: label = list(label.values()) self.update(label, pred)
[ "def", "update_dict", "(", "self", ",", "label", ",", "pred", ")", ":", "if", "self", ".", "output_names", "is", "not", "None", ":", "pred", "=", "[", "pred", "[", "name", "]", "for", "name", "in", "self", ".", "output_names", "]", "else", ":", "pred", "=", "list", "(", "pred", ".", "values", "(", ")", ")", "if", "self", ".", "label_names", "is", "not", "None", ":", "label", "=", "[", "label", "[", "name", "]", "for", "name", "in", "self", ".", "label_names", "]", "else", ":", "label", "=", "list", "(", "label", ".", "values", "(", ")", ")", "self", ".", "update", "(", "label", ",", "pred", ")" ]
Update the internal evaluation with named label and pred Parameters ---------- labels : OrderedDict of str -> NDArray name to array mapping for labels. preds : OrderedDict of str -> NDArray name to array mapping of predicted outputs.
[ "Update", "the", "internal", "evaluation", "with", "named", "label", "and", "pred" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/metric.py#L112-L133
23,767
apache/incubator-mxnet
python/mxnet/metric.py
EvalMetric.reset
def reset(self): """Resets the internal evaluation result to initial state.""" self.num_inst = 0 self.sum_metric = 0.0 self.global_num_inst = 0 self.global_sum_metric = 0.0
python
def reset(self): """Resets the internal evaluation result to initial state.""" self.num_inst = 0 self.sum_metric = 0.0 self.global_num_inst = 0 self.global_sum_metric = 0.0
[ "def", "reset", "(", "self", ")", ":", "self", ".", "num_inst", "=", "0", "self", ".", "sum_metric", "=", "0.0", "self", ".", "global_num_inst", "=", "0", "self", ".", "global_sum_metric", "=", "0.0" ]
Resets the internal evaluation result to initial state.
[ "Resets", "the", "internal", "evaluation", "result", "to", "initial", "state", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/metric.py#L148-L153
23,768
apache/incubator-mxnet
python/mxnet/metric.py
EvalMetric.get
def get(self): """Gets the current evaluation result. Returns ------- names : list of str Name of the metrics. values : list of float Value of the evaluations. """ if self.num_inst == 0: return (self.name, float('nan')) else: return (self.name, self.sum_metric / self.num_inst)
python
def get(self): """Gets the current evaluation result. Returns ------- names : list of str Name of the metrics. values : list of float Value of the evaluations. """ if self.num_inst == 0: return (self.name, float('nan')) else: return (self.name, self.sum_metric / self.num_inst)
[ "def", "get", "(", "self", ")", ":", "if", "self", ".", "num_inst", "==", "0", ":", "return", "(", "self", ".", "name", ",", "float", "(", "'nan'", ")", ")", "else", ":", "return", "(", "self", ".", "name", ",", "self", ".", "sum_metric", "/", "self", ".", "num_inst", ")" ]
Gets the current evaluation result. Returns ------- names : list of str Name of the metrics. values : list of float Value of the evaluations.
[ "Gets", "the", "current", "evaluation", "result", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/metric.py#L161-L174
23,769
apache/incubator-mxnet
python/mxnet/metric.py
EvalMetric.get_global
def get_global(self): """Gets the current global evaluation result. Returns ------- names : list of str Name of the metrics. values : list of float Value of the evaluations. """ if self._has_global_stats: if self.global_num_inst == 0: return (self.name, float('nan')) else: return (self.name, self.global_sum_metric / self.global_num_inst) else: return self.get()
python
def get_global(self): """Gets the current global evaluation result. Returns ------- names : list of str Name of the metrics. values : list of float Value of the evaluations. """ if self._has_global_stats: if self.global_num_inst == 0: return (self.name, float('nan')) else: return (self.name, self.global_sum_metric / self.global_num_inst) else: return self.get()
[ "def", "get_global", "(", "self", ")", ":", "if", "self", ".", "_has_global_stats", ":", "if", "self", ".", "global_num_inst", "==", "0", ":", "return", "(", "self", ".", "name", ",", "float", "(", "'nan'", ")", ")", "else", ":", "return", "(", "self", ".", "name", ",", "self", ".", "global_sum_metric", "/", "self", ".", "global_num_inst", ")", "else", ":", "return", "self", ".", "get", "(", ")" ]
Gets the current global evaluation result. Returns ------- names : list of str Name of the metrics. values : list of float Value of the evaluations.
[ "Gets", "the", "current", "global", "evaluation", "result", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/metric.py#L176-L192
23,770
apache/incubator-mxnet
python/mxnet/metric.py
EvalMetric.get_name_value
def get_name_value(self): """Returns zipped name and value pairs. Returns ------- list of tuples A (name, value) tuple list. """ name, value = self.get() if not isinstance(name, list): name = [name] if not isinstance(value, list): value = [value] return list(zip(name, value))
python
def get_name_value(self): """Returns zipped name and value pairs. Returns ------- list of tuples A (name, value) tuple list. """ name, value = self.get() if not isinstance(name, list): name = [name] if not isinstance(value, list): value = [value] return list(zip(name, value))
[ "def", "get_name_value", "(", "self", ")", ":", "name", ",", "value", "=", "self", ".", "get", "(", ")", "if", "not", "isinstance", "(", "name", ",", "list", ")", ":", "name", "=", "[", "name", "]", "if", "not", "isinstance", "(", "value", ",", "list", ")", ":", "value", "=", "[", "value", "]", "return", "list", "(", "zip", "(", "name", ",", "value", ")", ")" ]
Returns zipped name and value pairs. Returns ------- list of tuples A (name, value) tuple list.
[ "Returns", "zipped", "name", "and", "value", "pairs", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/metric.py#L194-L207
23,771
apache/incubator-mxnet
python/mxnet/metric.py
EvalMetric.get_global_name_value
def get_global_name_value(self): """Returns zipped name and value pairs for global results. Returns ------- list of tuples A (name, value) tuple list. """ if self._has_global_stats: name, value = self.get_global() if not isinstance(name, list): name = [name] if not isinstance(value, list): value = [value] return list(zip(name, value)) else: return self.get_name_value()
python
def get_global_name_value(self): """Returns zipped name and value pairs for global results. Returns ------- list of tuples A (name, value) tuple list. """ if self._has_global_stats: name, value = self.get_global() if not isinstance(name, list): name = [name] if not isinstance(value, list): value = [value] return list(zip(name, value)) else: return self.get_name_value()
[ "def", "get_global_name_value", "(", "self", ")", ":", "if", "self", ".", "_has_global_stats", ":", "name", ",", "value", "=", "self", ".", "get_global", "(", ")", "if", "not", "isinstance", "(", "name", ",", "list", ")", ":", "name", "=", "[", "name", "]", "if", "not", "isinstance", "(", "value", ",", "list", ")", ":", "value", "=", "[", "value", "]", "return", "list", "(", "zip", "(", "name", ",", "value", ")", ")", "else", ":", "return", "self", ".", "get_name_value", "(", ")" ]
Returns zipped name and value pairs for global results. Returns ------- list of tuples A (name, value) tuple list.
[ "Returns", "zipped", "name", "and", "value", "pairs", "for", "global", "results", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/metric.py#L209-L225
23,772
apache/incubator-mxnet
python/mxnet/metric.py
_BinaryClassificationMetrics.matthewscc
def matthewscc(self, use_global=False): """ Calculate the Matthew's Correlation Coefficent """ if use_global: if not self.global_total_examples: return 0. true_pos = float(self.global_true_positives) false_pos = float(self.global_false_positives) false_neg = float(self.global_false_negatives) true_neg = float(self.global_true_negatives) else: if not self.total_examples: return 0. true_pos = float(self.true_positives) false_pos = float(self.false_positives) false_neg = float(self.false_negatives) true_neg = float(self.true_negatives) terms = [(true_pos + false_pos), (true_pos + false_neg), (true_neg + false_pos), (true_neg + false_neg)] denom = 1. for t in filter(lambda t: t != 0., terms): denom *= t return ((true_pos * true_neg) - (false_pos * false_neg)) / math.sqrt(denom)
python
def matthewscc(self, use_global=False): """ Calculate the Matthew's Correlation Coefficent """ if use_global: if not self.global_total_examples: return 0. true_pos = float(self.global_true_positives) false_pos = float(self.global_false_positives) false_neg = float(self.global_false_negatives) true_neg = float(self.global_true_negatives) else: if not self.total_examples: return 0. true_pos = float(self.true_positives) false_pos = float(self.false_positives) false_neg = float(self.false_negatives) true_neg = float(self.true_negatives) terms = [(true_pos + false_pos), (true_pos + false_neg), (true_neg + false_pos), (true_neg + false_neg)] denom = 1. for t in filter(lambda t: t != 0., terms): denom *= t return ((true_pos * true_neg) - (false_pos * false_neg)) / math.sqrt(denom)
[ "def", "matthewscc", "(", "self", ",", "use_global", "=", "False", ")", ":", "if", "use_global", ":", "if", "not", "self", ".", "global_total_examples", ":", "return", "0.", "true_pos", "=", "float", "(", "self", ".", "global_true_positives", ")", "false_pos", "=", "float", "(", "self", ".", "global_false_positives", ")", "false_neg", "=", "float", "(", "self", ".", "global_false_negatives", ")", "true_neg", "=", "float", "(", "self", ".", "global_true_negatives", ")", "else", ":", "if", "not", "self", ".", "total_examples", ":", "return", "0.", "true_pos", "=", "float", "(", "self", ".", "true_positives", ")", "false_pos", "=", "float", "(", "self", ".", "false_positives", ")", "false_neg", "=", "float", "(", "self", ".", "false_negatives", ")", "true_neg", "=", "float", "(", "self", ".", "true_negatives", ")", "terms", "=", "[", "(", "true_pos", "+", "false_pos", ")", ",", "(", "true_pos", "+", "false_neg", ")", ",", "(", "true_neg", "+", "false_pos", ")", ",", "(", "true_neg", "+", "false_neg", ")", "]", "denom", "=", "1.", "for", "t", "in", "filter", "(", "lambda", "t", ":", "t", "!=", "0.", ",", "terms", ")", ":", "denom", "*=", "t", "return", "(", "(", "true_pos", "*", "true_neg", ")", "-", "(", "false_pos", "*", "false_neg", ")", ")", "/", "math", ".", "sqrt", "(", "denom", ")" ]
Calculate the Matthew's Correlation Coefficent
[ "Calculate", "the", "Matthew", "s", "Correlation", "Coefficent" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/metric.py#L693-L721
23,773
apache/incubator-mxnet
python/mxnet/gluon/data/dataset.py
Dataset.transform
def transform(self, fn, lazy=True): """Returns a new dataset with each sample transformed by the transformer function `fn`. Parameters ---------- fn : callable A transformer function that takes a sample as input and returns the transformed sample. lazy : bool, default True If False, transforms all samples at once. Otherwise, transforms each sample on demand. Note that if `fn` is stochastic, you must set lazy to True or you will get the same result on all epochs. Returns ------- Dataset The transformed dataset. """ trans = _LazyTransformDataset(self, fn) if lazy: return trans return SimpleDataset([i for i in trans])
python
def transform(self, fn, lazy=True): """Returns a new dataset with each sample transformed by the transformer function `fn`. Parameters ---------- fn : callable A transformer function that takes a sample as input and returns the transformed sample. lazy : bool, default True If False, transforms all samples at once. Otherwise, transforms each sample on demand. Note that if `fn` is stochastic, you must set lazy to True or you will get the same result on all epochs. Returns ------- Dataset The transformed dataset. """ trans = _LazyTransformDataset(self, fn) if lazy: return trans return SimpleDataset([i for i in trans])
[ "def", "transform", "(", "self", ",", "fn", ",", "lazy", "=", "True", ")", ":", "trans", "=", "_LazyTransformDataset", "(", "self", ",", "fn", ")", "if", "lazy", ":", "return", "trans", "return", "SimpleDataset", "(", "[", "i", "for", "i", "in", "trans", "]", ")" ]
Returns a new dataset with each sample transformed by the transformer function `fn`. Parameters ---------- fn : callable A transformer function that takes a sample as input and returns the transformed sample. lazy : bool, default True If False, transforms all samples at once. Otherwise, transforms each sample on demand. Note that if `fn` is stochastic, you must set lazy to True or you will get the same result on all epochs. Returns ------- Dataset The transformed dataset.
[ "Returns", "a", "new", "dataset", "with", "each", "sample", "transformed", "by", "the", "transformer", "function", "fn", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/gluon/data/dataset.py#L43-L66
23,774
apache/incubator-mxnet
example/ctc/ocr_predict.py
lstm_ocr_model.forward_ocr
def forward_ocr(self, img_): """Forward the image through the LSTM network model Parameters ---------- img_: int of array Returns ---------- label_list: string of list """ img_ = cv2.resize(img_, (80, 30)) img_ = img_.transpose(1, 0) print(img_.shape) img_ = img_.reshape((1, 80, 30)) print(img_.shape) # img_ = img_.reshape((80 * 30)) img_ = np.multiply(img_, 1 / 255.0) self.predictor.forward(data=img_, **self.init_state_dict) prob = self.predictor.get_output(0) label_list = [] for p in prob: print(np.argsort(p)) max_index = np.argsort(p)[::-1][0] label_list.append(max_index) return self.__get_string(label_list)
python
def forward_ocr(self, img_): """Forward the image through the LSTM network model Parameters ---------- img_: int of array Returns ---------- label_list: string of list """ img_ = cv2.resize(img_, (80, 30)) img_ = img_.transpose(1, 0) print(img_.shape) img_ = img_.reshape((1, 80, 30)) print(img_.shape) # img_ = img_.reshape((80 * 30)) img_ = np.multiply(img_, 1 / 255.0) self.predictor.forward(data=img_, **self.init_state_dict) prob = self.predictor.get_output(0) label_list = [] for p in prob: print(np.argsort(p)) max_index = np.argsort(p)[::-1][0] label_list.append(max_index) return self.__get_string(label_list)
[ "def", "forward_ocr", "(", "self", ",", "img_", ")", ":", "img_", "=", "cv2", ".", "resize", "(", "img_", ",", "(", "80", ",", "30", ")", ")", "img_", "=", "img_", ".", "transpose", "(", "1", ",", "0", ")", "print", "(", "img_", ".", "shape", ")", "img_", "=", "img_", ".", "reshape", "(", "(", "1", ",", "80", ",", "30", ")", ")", "print", "(", "img_", ".", "shape", ")", "# img_ = img_.reshape((80 * 30))", "img_", "=", "np", ".", "multiply", "(", "img_", ",", "1", "/", "255.0", ")", "self", ".", "predictor", ".", "forward", "(", "data", "=", "img_", ",", "*", "*", "self", ".", "init_state_dict", ")", "prob", "=", "self", ".", "predictor", ".", "get_output", "(", "0", ")", "label_list", "=", "[", "]", "for", "p", "in", "prob", ":", "print", "(", "np", ".", "argsort", "(", "p", ")", ")", "max_index", "=", "np", ".", "argsort", "(", "p", ")", "[", ":", ":", "-", "1", "]", "[", "0", "]", "label_list", ".", "append", "(", "max_index", ")", "return", "self", ".", "__get_string", "(", "label_list", ")" ]
Forward the image through the LSTM network model Parameters ---------- img_: int of array Returns ---------- label_list: string of list
[ "Forward", "the", "image", "through", "the", "LSTM", "network", "model" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/ctc/ocr_predict.py#L63-L88
23,775
apache/incubator-mxnet
tools/caffe_converter/caffe_parser.py
read_prototxt
def read_prototxt(fname): """Return a caffe_pb2.NetParameter object that defined in a prototxt file """ proto = caffe_pb2.NetParameter() with open(fname, 'r') as f: text_format.Merge(str(f.read()), proto) return proto
python
def read_prototxt(fname): """Return a caffe_pb2.NetParameter object that defined in a prototxt file """ proto = caffe_pb2.NetParameter() with open(fname, 'r') as f: text_format.Merge(str(f.read()), proto) return proto
[ "def", "read_prototxt", "(", "fname", ")", ":", "proto", "=", "caffe_pb2", ".", "NetParameter", "(", ")", "with", "open", "(", "fname", ",", "'r'", ")", "as", "f", ":", "text_format", ".", "Merge", "(", "str", "(", "f", ".", "read", "(", ")", ")", ",", "proto", ")", "return", "proto" ]
Return a caffe_pb2.NetParameter object that defined in a prototxt file
[ "Return", "a", "caffe_pb2", ".", "NetParameter", "object", "that", "defined", "in", "a", "prototxt", "file" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/tools/caffe_converter/caffe_parser.py#L34-L40
23,776
apache/incubator-mxnet
tools/caffe_converter/caffe_parser.py
get_layers
def get_layers(proto): """Returns layers in a caffe_pb2.NetParameter object """ if len(proto.layer): return proto.layer elif len(proto.layers): return proto.layers else: raise ValueError('Invalid proto file.')
python
def get_layers(proto): """Returns layers in a caffe_pb2.NetParameter object """ if len(proto.layer): return proto.layer elif len(proto.layers): return proto.layers else: raise ValueError('Invalid proto file.')
[ "def", "get_layers", "(", "proto", ")", ":", "if", "len", "(", "proto", ".", "layer", ")", ":", "return", "proto", ".", "layer", "elif", "len", "(", "proto", ".", "layers", ")", ":", "return", "proto", ".", "layers", "else", ":", "raise", "ValueError", "(", "'Invalid proto file.'", ")" ]
Returns layers in a caffe_pb2.NetParameter object
[ "Returns", "layers", "in", "a", "caffe_pb2", ".", "NetParameter", "object" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/tools/caffe_converter/caffe_parser.py#L42-L50
23,777
apache/incubator-mxnet
tools/caffe_converter/caffe_parser.py
read_caffemodel
def read_caffemodel(prototxt_fname, caffemodel_fname): """Return a caffe_pb2.NetParameter object that defined in a binary caffemodel file """ if use_caffe: caffe.set_mode_cpu() net = caffe.Net(prototxt_fname, caffemodel_fname, caffe.TEST) layer_names = net._layer_names layers = net.layers return (layers, layer_names) else: proto = caffe_pb2.NetParameter() with open(caffemodel_fname, 'rb') as f: proto.ParseFromString(f.read()) return (get_layers(proto), None)
python
def read_caffemodel(prototxt_fname, caffemodel_fname): """Return a caffe_pb2.NetParameter object that defined in a binary caffemodel file """ if use_caffe: caffe.set_mode_cpu() net = caffe.Net(prototxt_fname, caffemodel_fname, caffe.TEST) layer_names = net._layer_names layers = net.layers return (layers, layer_names) else: proto = caffe_pb2.NetParameter() with open(caffemodel_fname, 'rb') as f: proto.ParseFromString(f.read()) return (get_layers(proto), None)
[ "def", "read_caffemodel", "(", "prototxt_fname", ",", "caffemodel_fname", ")", ":", "if", "use_caffe", ":", "caffe", ".", "set_mode_cpu", "(", ")", "net", "=", "caffe", ".", "Net", "(", "prototxt_fname", ",", "caffemodel_fname", ",", "caffe", ".", "TEST", ")", "layer_names", "=", "net", ".", "_layer_names", "layers", "=", "net", ".", "layers", "return", "(", "layers", ",", "layer_names", ")", "else", ":", "proto", "=", "caffe_pb2", ".", "NetParameter", "(", ")", "with", "open", "(", "caffemodel_fname", ",", "'rb'", ")", "as", "f", ":", "proto", ".", "ParseFromString", "(", "f", ".", "read", "(", ")", ")", "return", "(", "get_layers", "(", "proto", ")", ",", "None", ")" ]
Return a caffe_pb2.NetParameter object that defined in a binary caffemodel file
[ "Return", "a", "caffe_pb2", ".", "NetParameter", "object", "that", "defined", "in", "a", "binary", "caffemodel", "file" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/tools/caffe_converter/caffe_parser.py#L52-L66
23,778
apache/incubator-mxnet
tools/caffe_converter/caffe_parser.py
layer_iter
def layer_iter(layers, layer_names): """Iterate over all layers""" if use_caffe: for layer_idx, layer in enumerate(layers): layer_name = re.sub('[-/]', '_', layer_names[layer_idx]) layer_type = layer.type layer_blobs = layer.blobs yield (layer_name, layer_type, layer_blobs) else: for layer in layers: layer_name = re.sub('[-/]', '_', layer.name) layer_type = layer.type layer_blobs = layer.blobs yield (layer_name, layer_type, layer_blobs)
python
def layer_iter(layers, layer_names): """Iterate over all layers""" if use_caffe: for layer_idx, layer in enumerate(layers): layer_name = re.sub('[-/]', '_', layer_names[layer_idx]) layer_type = layer.type layer_blobs = layer.blobs yield (layer_name, layer_type, layer_blobs) else: for layer in layers: layer_name = re.sub('[-/]', '_', layer.name) layer_type = layer.type layer_blobs = layer.blobs yield (layer_name, layer_type, layer_blobs)
[ "def", "layer_iter", "(", "layers", ",", "layer_names", ")", ":", "if", "use_caffe", ":", "for", "layer_idx", ",", "layer", "in", "enumerate", "(", "layers", ")", ":", "layer_name", "=", "re", ".", "sub", "(", "'[-/]'", ",", "'_'", ",", "layer_names", "[", "layer_idx", "]", ")", "layer_type", "=", "layer", ".", "type", "layer_blobs", "=", "layer", ".", "blobs", "yield", "(", "layer_name", ",", "layer_type", ",", "layer_blobs", ")", "else", ":", "for", "layer", "in", "layers", ":", "layer_name", "=", "re", ".", "sub", "(", "'[-/]'", ",", "'_'", ",", "layer", ".", "name", ")", "layer_type", "=", "layer", ".", "type", "layer_blobs", "=", "layer", ".", "blobs", "yield", "(", "layer_name", ",", "layer_type", ",", "layer_blobs", ")" ]
Iterate over all layers
[ "Iterate", "over", "all", "layers" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/tools/caffe_converter/caffe_parser.py#L68-L81
23,779
apache/incubator-mxnet
python/mxnet/profiler.py
set_state
def set_state(state='stop', profile_process='worker'): """Set up the profiler state to 'run' or 'stop'. Parameters ---------- state : string, optional Indicates whether to run the profiler, can be 'stop' or 'run'. Default is `stop`. profile_process : string whether to profile kvstore `server` or `worker`. server can only be profiled when kvstore is of type dist. if this is not passed, defaults to `worker` """ state2int = {'stop': 0, 'run': 1} profile_process2int = {'worker': 0, 'server': 1} check_call(_LIB.MXSetProcessProfilerState(ctypes.c_int(state2int[state]), profile_process2int[profile_process], profiler_kvstore_handle))
python
def set_state(state='stop', profile_process='worker'): """Set up the profiler state to 'run' or 'stop'. Parameters ---------- state : string, optional Indicates whether to run the profiler, can be 'stop' or 'run'. Default is `stop`. profile_process : string whether to profile kvstore `server` or `worker`. server can only be profiled when kvstore is of type dist. if this is not passed, defaults to `worker` """ state2int = {'stop': 0, 'run': 1} profile_process2int = {'worker': 0, 'server': 1} check_call(_LIB.MXSetProcessProfilerState(ctypes.c_int(state2int[state]), profile_process2int[profile_process], profiler_kvstore_handle))
[ "def", "set_state", "(", "state", "=", "'stop'", ",", "profile_process", "=", "'worker'", ")", ":", "state2int", "=", "{", "'stop'", ":", "0", ",", "'run'", ":", "1", "}", "profile_process2int", "=", "{", "'worker'", ":", "0", ",", "'server'", ":", "1", "}", "check_call", "(", "_LIB", ".", "MXSetProcessProfilerState", "(", "ctypes", ".", "c_int", "(", "state2int", "[", "state", "]", ")", ",", "profile_process2int", "[", "profile_process", "]", ",", "profiler_kvstore_handle", ")", ")" ]
Set up the profiler state to 'run' or 'stop'. Parameters ---------- state : string, optional Indicates whether to run the profiler, can be 'stop' or 'run'. Default is `stop`. profile_process : string whether to profile kvstore `server` or `worker`. server can only be profiled when kvstore is of type dist. if this is not passed, defaults to `worker`
[ "Set", "up", "the", "profiler", "state", "to", "run", "or", "stop", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/profiler.py#L89-L106
23,780
apache/incubator-mxnet
python/mxnet/profiler.py
dump
def dump(finished=True, profile_process='worker'): """Dump profile and stop profiler. Use this to save profile in advance in case your program cannot exit normally. Parameters ---------- finished : boolean Indicates whether to stop statistic output (dumping) after this dump. Default is True profile_process : string whether to profile kvstore `server` or `worker`. server can only be profiled when kvstore is of type dist. if this is not passed, defaults to `worker` """ fin = 1 if finished is True else 0 profile_process2int = {'worker': 0, 'server': 1} check_call(_LIB.MXDumpProcessProfile(fin, profile_process2int[profile_process], profiler_kvstore_handle))
python
def dump(finished=True, profile_process='worker'): """Dump profile and stop profiler. Use this to save profile in advance in case your program cannot exit normally. Parameters ---------- finished : boolean Indicates whether to stop statistic output (dumping) after this dump. Default is True profile_process : string whether to profile kvstore `server` or `worker`. server can only be profiled when kvstore is of type dist. if this is not passed, defaults to `worker` """ fin = 1 if finished is True else 0 profile_process2int = {'worker': 0, 'server': 1} check_call(_LIB.MXDumpProcessProfile(fin, profile_process2int[profile_process], profiler_kvstore_handle))
[ "def", "dump", "(", "finished", "=", "True", ",", "profile_process", "=", "'worker'", ")", ":", "fin", "=", "1", "if", "finished", "is", "True", "else", "0", "profile_process2int", "=", "{", "'worker'", ":", "0", ",", "'server'", ":", "1", "}", "check_call", "(", "_LIB", ".", "MXDumpProcessProfile", "(", "fin", ",", "profile_process2int", "[", "profile_process", "]", ",", "profiler_kvstore_handle", ")", ")" ]
Dump profile and stop profiler. Use this to save profile in advance in case your program cannot exit normally. Parameters ---------- finished : boolean Indicates whether to stop statistic output (dumping) after this dump. Default is True profile_process : string whether to profile kvstore `server` or `worker`. server can only be profiled when kvstore is of type dist. if this is not passed, defaults to `worker`
[ "Dump", "profile", "and", "stop", "profiler", ".", "Use", "this", "to", "save", "profile", "in", "advance", "in", "case", "your", "program", "cannot", "exit", "normally", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/profiler.py#L122-L140
23,781
apache/incubator-mxnet
python/mxnet/profiler.py
dumps
def dumps(reset=False): """Return a printable string of aggregate profile stats. Parameters ---------- reset: boolean Indicates whether to clean aggeregate statistical data collected up to this point """ debug_str = ctypes.c_char_p() do_reset = 1 if reset is True else 0 check_call(_LIB.MXAggregateProfileStatsPrint(ctypes.byref(debug_str), int(do_reset))) return py_str(debug_str.value)
python
def dumps(reset=False): """Return a printable string of aggregate profile stats. Parameters ---------- reset: boolean Indicates whether to clean aggeregate statistical data collected up to this point """ debug_str = ctypes.c_char_p() do_reset = 1 if reset is True else 0 check_call(_LIB.MXAggregateProfileStatsPrint(ctypes.byref(debug_str), int(do_reset))) return py_str(debug_str.value)
[ "def", "dumps", "(", "reset", "=", "False", ")", ":", "debug_str", "=", "ctypes", ".", "c_char_p", "(", ")", "do_reset", "=", "1", "if", "reset", "is", "True", "else", "0", "check_call", "(", "_LIB", ".", "MXAggregateProfileStatsPrint", "(", "ctypes", ".", "byref", "(", "debug_str", ")", ",", "int", "(", "do_reset", ")", ")", ")", "return", "py_str", "(", "debug_str", ".", "value", ")" ]
Return a printable string of aggregate profile stats. Parameters ---------- reset: boolean Indicates whether to clean aggeregate statistical data collected up to this point
[ "Return", "a", "printable", "string", "of", "aggregate", "profile", "stats", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/profiler.py#L151-L162
23,782
apache/incubator-mxnet
python/mxnet/profiler.py
pause
def pause(profile_process='worker'): """Pause profiling. Parameters ---------- profile_process : string whether to profile kvstore `server` or `worker`. server can only be profiled when kvstore is of type dist. if this is not passed, defaults to `worker` """ profile_process2int = {'worker': 0, 'server': 1} check_call(_LIB.MXProcessProfilePause(int(1), profile_process2int[profile_process], profiler_kvstore_handle))
python
def pause(profile_process='worker'): """Pause profiling. Parameters ---------- profile_process : string whether to profile kvstore `server` or `worker`. server can only be profiled when kvstore is of type dist. if this is not passed, defaults to `worker` """ profile_process2int = {'worker': 0, 'server': 1} check_call(_LIB.MXProcessProfilePause(int(1), profile_process2int[profile_process], profiler_kvstore_handle))
[ "def", "pause", "(", "profile_process", "=", "'worker'", ")", ":", "profile_process2int", "=", "{", "'worker'", ":", "0", ",", "'server'", ":", "1", "}", "check_call", "(", "_LIB", ".", "MXProcessProfilePause", "(", "int", "(", "1", ")", ",", "profile_process2int", "[", "profile_process", "]", ",", "profiler_kvstore_handle", ")", ")" ]
Pause profiling. Parameters ---------- profile_process : string whether to profile kvstore `server` or `worker`. server can only be profiled when kvstore is of type dist. if this is not passed, defaults to `worker`
[ "Pause", "profiling", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/profiler.py#L165-L178
23,783
apache/incubator-mxnet
python/mxnet/profiler.py
resume
def resume(profile_process='worker'): """ Resume paused profiling. Parameters ---------- profile_process : string whether to profile kvstore `server` or `worker`. server can only be profiled when kvstore is of type dist. if this is not passed, defaults to `worker` """ profile_process2int = {'worker': 0, 'server': 1} check_call(_LIB.MXProcessProfilePause(int(0), profile_process2int[profile_process], profiler_kvstore_handle))
python
def resume(profile_process='worker'): """ Resume paused profiling. Parameters ---------- profile_process : string whether to profile kvstore `server` or `worker`. server can only be profiled when kvstore is of type dist. if this is not passed, defaults to `worker` """ profile_process2int = {'worker': 0, 'server': 1} check_call(_LIB.MXProcessProfilePause(int(0), profile_process2int[profile_process], profiler_kvstore_handle))
[ "def", "resume", "(", "profile_process", "=", "'worker'", ")", ":", "profile_process2int", "=", "{", "'worker'", ":", "0", ",", "'server'", ":", "1", "}", "check_call", "(", "_LIB", ".", "MXProcessProfilePause", "(", "int", "(", "0", ")", ",", "profile_process2int", "[", "profile_process", "]", ",", "profiler_kvstore_handle", ")", ")" ]
Resume paused profiling. Parameters ---------- profile_process : string whether to profile kvstore `server` or `worker`. server can only be profiled when kvstore is of type dist. if this is not passed, defaults to `worker`
[ "Resume", "paused", "profiling", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/profiler.py#L181-L195
23,784
apache/incubator-mxnet
python/mxnet/profiler.py
Counter.set_value
def set_value(self, value): """Set counter value. Parameters ---------- value : int Value for the counter """ check_call(_LIB.MXProfileSetCounter(self.handle, int(value)))
python
def set_value(self, value): """Set counter value. Parameters ---------- value : int Value for the counter """ check_call(_LIB.MXProfileSetCounter(self.handle, int(value)))
[ "def", "set_value", "(", "self", ",", "value", ")", ":", "check_call", "(", "_LIB", ".", "MXProfileSetCounter", "(", "self", ".", "handle", ",", "int", "(", "value", ")", ")", ")" ]
Set counter value. Parameters ---------- value : int Value for the counter
[ "Set", "counter", "value", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/profiler.py#L405-L413
23,785
apache/incubator-mxnet
python/mxnet/profiler.py
Counter.decrement
def decrement(self, delta=1): """Decrement counter value. Parameters ---------- value_change : int Amount by which to subtract from the counter """ check_call(_LIB.MXProfileAdjustCounter(self.handle, -int(delta)))
python
def decrement(self, delta=1): """Decrement counter value. Parameters ---------- value_change : int Amount by which to subtract from the counter """ check_call(_LIB.MXProfileAdjustCounter(self.handle, -int(delta)))
[ "def", "decrement", "(", "self", ",", "delta", "=", "1", ")", ":", "check_call", "(", "_LIB", ".", "MXProfileAdjustCounter", "(", "self", ".", "handle", ",", "-", "int", "(", "delta", ")", ")", ")" ]
Decrement counter value. Parameters ---------- value_change : int Amount by which to subtract from the counter
[ "Decrement", "counter", "value", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/profiler.py#L425-L433
23,786
apache/incubator-mxnet
python/mxnet/profiler.py
Marker.mark
def mark(self, scope='process'): """Set up the profiler state to record operator. Parameters ---------- scope : string, optional Indicates what scope the marker should refer to. Can be 'global', 'process', thread', task', and 'marker' Default is `process`. """ check_call(_LIB.MXProfileSetMarker(self.domain.handle, c_str(self.name), c_str(scope)))
python
def mark(self, scope='process'): """Set up the profiler state to record operator. Parameters ---------- scope : string, optional Indicates what scope the marker should refer to. Can be 'global', 'process', thread', task', and 'marker' Default is `process`. """ check_call(_LIB.MXProfileSetMarker(self.domain.handle, c_str(self.name), c_str(scope)))
[ "def", "mark", "(", "self", ",", "scope", "=", "'process'", ")", ":", "check_call", "(", "_LIB", ".", "MXProfileSetMarker", "(", "self", ".", "domain", ".", "handle", ",", "c_str", "(", "self", ".", "name", ")", ",", "c_str", "(", "scope", ")", ")", ")" ]
Set up the profiler state to record operator. Parameters ---------- scope : string, optional Indicates what scope the marker should refer to. Can be 'global', 'process', thread', task', and 'marker' Default is `process`.
[ "Set", "up", "the", "profiler", "state", "to", "record", "operator", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/profiler.py#L463-L473
23,787
apache/incubator-mxnet
python/mxnet/rtc.py
CudaModule.get_kernel
def get_kernel(self, name, signature): r"""Get CUDA kernel from compiled module. Parameters ---------- name : str String name of the kernel. signature : str Function signature for the kernel. For example, if a kernel is declared as:: extern "C" __global__ void axpy(const float *x, double *y, int alpha) Then its signature should be:: const float *x, double *y, int alpha or:: const float *, double *, int Note that `*` in signature marks an argument as array and `const` marks an argument as constant (input) array. Returns ------- CudaKernel CUDA kernels that can be launched on GPUs. """ hdl = CudaKernelHandle() is_ndarray = [] is_const = [] dtypes = [] pattern = re.compile(r"""^\s*(const)?\s*([\w_]+)\s*(\*)?\s*([\w_]+)?\s*$""") args = re.sub(r"\s+", " ", signature).split(",") for arg in args: match = pattern.match(arg) if not match or match.groups()[1] == 'const': raise ValueError( 'Invalid function prototype "%s". Must be in the ' 'form of "(const) type (*) (name)"'%arg) is_const.append(bool(match.groups()[0])) dtype = match.groups()[1] is_ndarray.append(bool(match.groups()[2])) if dtype not in _DTYPE_CPP_TO_NP: raise TypeError( "Unsupported kernel argument type %s. Supported types are: %s."%( arg, ','.join(_DTYPE_CPP_TO_NP.keys()))) dtypes.append(_DTYPE_NP_TO_MX[_DTYPE_CPP_TO_NP[dtype]]) check_call(_LIB.MXRtcCudaKernelCreate( self.handle, c_str(name), len(dtypes), c_array_buf(ctypes.c_int, array('i', is_ndarray)), c_array_buf(ctypes.c_int, array('i', is_const)), c_array_buf(ctypes.c_int, array('i', dtypes)), ctypes.byref(hdl))) return CudaKernel(hdl, name, is_ndarray, dtypes)
python
def get_kernel(self, name, signature): r"""Get CUDA kernel from compiled module. Parameters ---------- name : str String name of the kernel. signature : str Function signature for the kernel. For example, if a kernel is declared as:: extern "C" __global__ void axpy(const float *x, double *y, int alpha) Then its signature should be:: const float *x, double *y, int alpha or:: const float *, double *, int Note that `*` in signature marks an argument as array and `const` marks an argument as constant (input) array. Returns ------- CudaKernel CUDA kernels that can be launched on GPUs. """ hdl = CudaKernelHandle() is_ndarray = [] is_const = [] dtypes = [] pattern = re.compile(r"""^\s*(const)?\s*([\w_]+)\s*(\*)?\s*([\w_]+)?\s*$""") args = re.sub(r"\s+", " ", signature).split(",") for arg in args: match = pattern.match(arg) if not match or match.groups()[1] == 'const': raise ValueError( 'Invalid function prototype "%s". Must be in the ' 'form of "(const) type (*) (name)"'%arg) is_const.append(bool(match.groups()[0])) dtype = match.groups()[1] is_ndarray.append(bool(match.groups()[2])) if dtype not in _DTYPE_CPP_TO_NP: raise TypeError( "Unsupported kernel argument type %s. Supported types are: %s."%( arg, ','.join(_DTYPE_CPP_TO_NP.keys()))) dtypes.append(_DTYPE_NP_TO_MX[_DTYPE_CPP_TO_NP[dtype]]) check_call(_LIB.MXRtcCudaKernelCreate( self.handle, c_str(name), len(dtypes), c_array_buf(ctypes.c_int, array('i', is_ndarray)), c_array_buf(ctypes.c_int, array('i', is_const)), c_array_buf(ctypes.c_int, array('i', dtypes)), ctypes.byref(hdl))) return CudaKernel(hdl, name, is_ndarray, dtypes)
[ "def", "get_kernel", "(", "self", ",", "name", ",", "signature", ")", ":", "hdl", "=", "CudaKernelHandle", "(", ")", "is_ndarray", "=", "[", "]", "is_const", "=", "[", "]", "dtypes", "=", "[", "]", "pattern", "=", "re", ".", "compile", "(", "r\"\"\"^\\s*(const)?\\s*([\\w_]+)\\s*(\\*)?\\s*([\\w_]+)?\\s*$\"\"\"", ")", "args", "=", "re", ".", "sub", "(", "r\"\\s+\"", ",", "\" \"", ",", "signature", ")", ".", "split", "(", "\",\"", ")", "for", "arg", "in", "args", ":", "match", "=", "pattern", ".", "match", "(", "arg", ")", "if", "not", "match", "or", "match", ".", "groups", "(", ")", "[", "1", "]", "==", "'const'", ":", "raise", "ValueError", "(", "'Invalid function prototype \"%s\". Must be in the '", "'form of \"(const) type (*) (name)\"'", "%", "arg", ")", "is_const", ".", "append", "(", "bool", "(", "match", ".", "groups", "(", ")", "[", "0", "]", ")", ")", "dtype", "=", "match", ".", "groups", "(", ")", "[", "1", "]", "is_ndarray", ".", "append", "(", "bool", "(", "match", ".", "groups", "(", ")", "[", "2", "]", ")", ")", "if", "dtype", "not", "in", "_DTYPE_CPP_TO_NP", ":", "raise", "TypeError", "(", "\"Unsupported kernel argument type %s. Supported types are: %s.\"", "%", "(", "arg", ",", "','", ".", "join", "(", "_DTYPE_CPP_TO_NP", ".", "keys", "(", ")", ")", ")", ")", "dtypes", ".", "append", "(", "_DTYPE_NP_TO_MX", "[", "_DTYPE_CPP_TO_NP", "[", "dtype", "]", "]", ")", "check_call", "(", "_LIB", ".", "MXRtcCudaKernelCreate", "(", "self", ".", "handle", ",", "c_str", "(", "name", ")", ",", "len", "(", "dtypes", ")", ",", "c_array_buf", "(", "ctypes", ".", "c_int", ",", "array", "(", "'i'", ",", "is_ndarray", ")", ")", ",", "c_array_buf", "(", "ctypes", ".", "c_int", ",", "array", "(", "'i'", ",", "is_const", ")", ")", ",", "c_array_buf", "(", "ctypes", ".", "c_int", ",", "array", "(", "'i'", ",", "dtypes", ")", ")", ",", "ctypes", ".", "byref", "(", "hdl", ")", ")", ")", "return", "CudaKernel", "(", "hdl", ",", "name", ",", "is_ndarray", ",", "dtypes", ")" ]
r"""Get CUDA kernel from compiled module. Parameters ---------- name : str String name of the kernel. signature : str Function signature for the kernel. For example, if a kernel is declared as:: extern "C" __global__ void axpy(const float *x, double *y, int alpha) Then its signature should be:: const float *x, double *y, int alpha or:: const float *, double *, int Note that `*` in signature marks an argument as array and `const` marks an argument as constant (input) array. Returns ------- CudaKernel CUDA kernels that can be launched on GPUs.
[ "r", "Get", "CUDA", "kernel", "from", "compiled", "module", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/rtc.py#L112-L171
23,788
apache/incubator-mxnet
python/mxnet/rtc.py
CudaKernel.launch
def launch(self, args, ctx, grid_dims, block_dims, shared_mem=0): """Launch cuda kernel. Parameters ---------- args : tuple of NDArray or numbers List of arguments for kernel. NDArrays are expected for pointer types (e.g. `float*`, `double*`) while numbers are expected for non-pointer types (e.g. `int`, `float`). ctx : Context The context to launch kernel on. Must be GPU context. grid_dims : tuple of 3 integers Grid dimensions for CUDA kernel. block_dims : tuple of 3 integers Block dimensions for CUDA kernel. shared_mem : integer, optional Size of dynamically allocated shared memory. Defaults to 0. """ assert ctx.device_type == 'gpu', "Cuda kernel can only be launched on GPU" assert len(grid_dims) == 3, "grid_dims must be a tuple of 3 integers" assert len(block_dims) == 3, "grid_dims must be a tuple of 3 integers" assert len(args) == len(self._dtypes), \ "CudaKernel(%s) expects %d arguments but got %d"%( self._name, len(self._dtypes), len(args)) void_args = [] ref_holder = [] for i, (arg, is_nd, dtype) in enumerate(zip(args, self._is_ndarray, self._dtypes)): if is_nd: assert isinstance(arg, NDArray), \ "The %d-th argument is expected to be a NDArray but got %s"%( i, type(arg)) void_args.append(arg.handle) else: assert isinstance(arg, numeric_types), \ "The %d-th argument is expected to be a number, but got %s"%( i, type(arg)) ref_holder.append(np.array(arg, dtype=dtype)) void_args.append(ref_holder[-1].ctypes.data_as(ctypes.c_void_p)) check_call(_LIB.MXRtcCudaKernelCall( self.handle, ctx.device_id, c_array(ctypes.c_void_p, void_args), mx_uint(grid_dims[0]), mx_uint(grid_dims[1]), mx_uint(grid_dims[2]), mx_uint(block_dims[0]), mx_uint(block_dims[1]), mx_uint(block_dims[2]), mx_uint(shared_mem)))
python
def launch(self, args, ctx, grid_dims, block_dims, shared_mem=0): """Launch cuda kernel. Parameters ---------- args : tuple of NDArray or numbers List of arguments for kernel. NDArrays are expected for pointer types (e.g. `float*`, `double*`) while numbers are expected for non-pointer types (e.g. `int`, `float`). ctx : Context The context to launch kernel on. Must be GPU context. grid_dims : tuple of 3 integers Grid dimensions for CUDA kernel. block_dims : tuple of 3 integers Block dimensions for CUDA kernel. shared_mem : integer, optional Size of dynamically allocated shared memory. Defaults to 0. """ assert ctx.device_type == 'gpu', "Cuda kernel can only be launched on GPU" assert len(grid_dims) == 3, "grid_dims must be a tuple of 3 integers" assert len(block_dims) == 3, "grid_dims must be a tuple of 3 integers" assert len(args) == len(self._dtypes), \ "CudaKernel(%s) expects %d arguments but got %d"%( self._name, len(self._dtypes), len(args)) void_args = [] ref_holder = [] for i, (arg, is_nd, dtype) in enumerate(zip(args, self._is_ndarray, self._dtypes)): if is_nd: assert isinstance(arg, NDArray), \ "The %d-th argument is expected to be a NDArray but got %s"%( i, type(arg)) void_args.append(arg.handle) else: assert isinstance(arg, numeric_types), \ "The %d-th argument is expected to be a number, but got %s"%( i, type(arg)) ref_holder.append(np.array(arg, dtype=dtype)) void_args.append(ref_holder[-1].ctypes.data_as(ctypes.c_void_p)) check_call(_LIB.MXRtcCudaKernelCall( self.handle, ctx.device_id, c_array(ctypes.c_void_p, void_args), mx_uint(grid_dims[0]), mx_uint(grid_dims[1]), mx_uint(grid_dims[2]), mx_uint(block_dims[0]), mx_uint(block_dims[1]), mx_uint(block_dims[2]), mx_uint(shared_mem)))
[ "def", "launch", "(", "self", ",", "args", ",", "ctx", ",", "grid_dims", ",", "block_dims", ",", "shared_mem", "=", "0", ")", ":", "assert", "ctx", ".", "device_type", "==", "'gpu'", ",", "\"Cuda kernel can only be launched on GPU\"", "assert", "len", "(", "grid_dims", ")", "==", "3", ",", "\"grid_dims must be a tuple of 3 integers\"", "assert", "len", "(", "block_dims", ")", "==", "3", ",", "\"grid_dims must be a tuple of 3 integers\"", "assert", "len", "(", "args", ")", "==", "len", "(", "self", ".", "_dtypes", ")", ",", "\"CudaKernel(%s) expects %d arguments but got %d\"", "%", "(", "self", ".", "_name", ",", "len", "(", "self", ".", "_dtypes", ")", ",", "len", "(", "args", ")", ")", "void_args", "=", "[", "]", "ref_holder", "=", "[", "]", "for", "i", ",", "(", "arg", ",", "is_nd", ",", "dtype", ")", "in", "enumerate", "(", "zip", "(", "args", ",", "self", ".", "_is_ndarray", ",", "self", ".", "_dtypes", ")", ")", ":", "if", "is_nd", ":", "assert", "isinstance", "(", "arg", ",", "NDArray", ")", ",", "\"The %d-th argument is expected to be a NDArray but got %s\"", "%", "(", "i", ",", "type", "(", "arg", ")", ")", "void_args", ".", "append", "(", "arg", ".", "handle", ")", "else", ":", "assert", "isinstance", "(", "arg", ",", "numeric_types", ")", ",", "\"The %d-th argument is expected to be a number, but got %s\"", "%", "(", "i", ",", "type", "(", "arg", ")", ")", "ref_holder", ".", "append", "(", "np", ".", "array", "(", "arg", ",", "dtype", "=", "dtype", ")", ")", "void_args", ".", "append", "(", "ref_holder", "[", "-", "1", "]", ".", "ctypes", ".", "data_as", "(", "ctypes", ".", "c_void_p", ")", ")", "check_call", "(", "_LIB", ".", "MXRtcCudaKernelCall", "(", "self", ".", "handle", ",", "ctx", ".", "device_id", ",", "c_array", "(", "ctypes", ".", "c_void_p", ",", "void_args", ")", ",", "mx_uint", "(", "grid_dims", "[", "0", "]", ")", ",", "mx_uint", "(", "grid_dims", "[", "1", "]", ")", ",", "mx_uint", "(", "grid_dims", "[", "2", "]", ")", ",", "mx_uint", "(", "block_dims", "[", "0", "]", ")", ",", "mx_uint", "(", "block_dims", "[", "1", "]", ")", ",", "mx_uint", "(", "block_dims", "[", "2", "]", ")", ",", "mx_uint", "(", "shared_mem", ")", ")", ")" ]
Launch cuda kernel. Parameters ---------- args : tuple of NDArray or numbers List of arguments for kernel. NDArrays are expected for pointer types (e.g. `float*`, `double*`) while numbers are expected for non-pointer types (e.g. `int`, `float`). ctx : Context The context to launch kernel on. Must be GPU context. grid_dims : tuple of 3 integers Grid dimensions for CUDA kernel. block_dims : tuple of 3 integers Block dimensions for CUDA kernel. shared_mem : integer, optional Size of dynamically allocated shared memory. Defaults to 0.
[ "Launch", "cuda", "kernel", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/rtc.py#L185-L230
23,789
apache/incubator-mxnet
example/ssd/evaluate/eval_metric.py
MApMetric.reset
def reset(self): """Clear the internal statistics to initial state.""" if getattr(self, 'num', None) is None: self.num_inst = 0 self.sum_metric = 0.0 else: self.num_inst = [0] * self.num self.sum_metric = [0.0] * self.num self.records = dict() self.counts = dict()
python
def reset(self): """Clear the internal statistics to initial state.""" if getattr(self, 'num', None) is None: self.num_inst = 0 self.sum_metric = 0.0 else: self.num_inst = [0] * self.num self.sum_metric = [0.0] * self.num self.records = dict() self.counts = dict()
[ "def", "reset", "(", "self", ")", ":", "if", "getattr", "(", "self", ",", "'num'", ",", "None", ")", "is", "None", ":", "self", ".", "num_inst", "=", "0", "self", ".", "sum_metric", "=", "0.0", "else", ":", "self", ".", "num_inst", "=", "[", "0", "]", "*", "self", ".", "num", "self", ".", "sum_metric", "=", "[", "0.0", "]", "*", "self", ".", "num", "self", ".", "records", "=", "dict", "(", ")", "self", ".", "counts", "=", "dict", "(", ")" ]
Clear the internal statistics to initial state.
[ "Clear", "the", "internal", "statistics", "to", "initial", "state", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/ssd/evaluate/eval_metric.py#L53-L62
23,790
apache/incubator-mxnet
example/ssd/evaluate/eval_metric.py
MApMetric._update
def _update(self): """ update num_inst and sum_metric """ aps = [] for k, v in self.records.items(): recall, prec = self._recall_prec(v, self.counts[k]) ap = self._average_precision(recall, prec) aps.append(ap) if self.num is not None and k < (self.num - 1): self.sum_metric[k] = ap self.num_inst[k] = 1 if self.num is None: self.num_inst = 1 self.sum_metric = np.mean(aps) else: self.num_inst[-1] = 1 self.sum_metric[-1] = np.mean(aps)
python
def _update(self): """ update num_inst and sum_metric """ aps = [] for k, v in self.records.items(): recall, prec = self._recall_prec(v, self.counts[k]) ap = self._average_precision(recall, prec) aps.append(ap) if self.num is not None and k < (self.num - 1): self.sum_metric[k] = ap self.num_inst[k] = 1 if self.num is None: self.num_inst = 1 self.sum_metric = np.mean(aps) else: self.num_inst[-1] = 1 self.sum_metric[-1] = np.mean(aps)
[ "def", "_update", "(", "self", ")", ":", "aps", "=", "[", "]", "for", "k", ",", "v", "in", "self", ".", "records", ".", "items", "(", ")", ":", "recall", ",", "prec", "=", "self", ".", "_recall_prec", "(", "v", ",", "self", ".", "counts", "[", "k", "]", ")", "ap", "=", "self", ".", "_average_precision", "(", "recall", ",", "prec", ")", "aps", ".", "append", "(", "ap", ")", "if", "self", ".", "num", "is", "not", "None", "and", "k", "<", "(", "self", ".", "num", "-", "1", ")", ":", "self", ".", "sum_metric", "[", "k", "]", "=", "ap", "self", ".", "num_inst", "[", "k", "]", "=", "1", "if", "self", ".", "num", "is", "None", ":", "self", ".", "num_inst", "=", "1", "self", ".", "sum_metric", "=", "np", ".", "mean", "(", "aps", ")", "else", ":", "self", ".", "num_inst", "[", "-", "1", "]", "=", "1", "self", ".", "sum_metric", "[", "-", "1", "]", "=", "np", ".", "mean", "(", "aps", ")" ]
update num_inst and sum_metric
[ "update", "num_inst", "and", "sum_metric" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/ssd/evaluate/eval_metric.py#L197-L212
23,791
apache/incubator-mxnet
example/ssd/evaluate/eval_metric.py
MApMetric._recall_prec
def _recall_prec(self, record, count): """ get recall and precision from internal records """ record = np.delete(record, np.where(record[:, 1].astype(int) == 0)[0], axis=0) sorted_records = record[record[:,0].argsort()[::-1]] tp = np.cumsum(sorted_records[:, 1].astype(int) == 1) fp = np.cumsum(sorted_records[:, 1].astype(int) == 2) if count <= 0: recall = tp * 0.0 else: recall = tp / float(count) prec = tp.astype(float) / (tp + fp) return recall, prec
python
def _recall_prec(self, record, count): """ get recall and precision from internal records """ record = np.delete(record, np.where(record[:, 1].astype(int) == 0)[0], axis=0) sorted_records = record[record[:,0].argsort()[::-1]] tp = np.cumsum(sorted_records[:, 1].astype(int) == 1) fp = np.cumsum(sorted_records[:, 1].astype(int) == 2) if count <= 0: recall = tp * 0.0 else: recall = tp / float(count) prec = tp.astype(float) / (tp + fp) return recall, prec
[ "def", "_recall_prec", "(", "self", ",", "record", ",", "count", ")", ":", "record", "=", "np", ".", "delete", "(", "record", ",", "np", ".", "where", "(", "record", "[", ":", ",", "1", "]", ".", "astype", "(", "int", ")", "==", "0", ")", "[", "0", "]", ",", "axis", "=", "0", ")", "sorted_records", "=", "record", "[", "record", "[", ":", ",", "0", "]", ".", "argsort", "(", ")", "[", ":", ":", "-", "1", "]", "]", "tp", "=", "np", ".", "cumsum", "(", "sorted_records", "[", ":", ",", "1", "]", ".", "astype", "(", "int", ")", "==", "1", ")", "fp", "=", "np", ".", "cumsum", "(", "sorted_records", "[", ":", ",", "1", "]", ".", "astype", "(", "int", ")", "==", "2", ")", "if", "count", "<=", "0", ":", "recall", "=", "tp", "*", "0.0", "else", ":", "recall", "=", "tp", "/", "float", "(", "count", ")", "prec", "=", "tp", ".", "astype", "(", "float", ")", "/", "(", "tp", "+", "fp", ")", "return", "recall", ",", "prec" ]
get recall and precision from internal records
[ "get", "recall", "and", "precision", "from", "internal", "records" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/ssd/evaluate/eval_metric.py#L214-L225
23,792
apache/incubator-mxnet
example/ssd/evaluate/eval_metric.py
MApMetric._average_precision
def _average_precision(self, rec, prec): """ calculate average precision Params: ---------- rec : numpy.array cumulated recall prec : numpy.array cumulated precision Returns: ---------- ap as float """ # append sentinel values at both ends mrec = np.concatenate(([0.], rec, [1.])) mpre = np.concatenate(([0.], prec, [0.])) # compute precision integration ladder for i in range(mpre.size - 1, 0, -1): mpre[i - 1] = np.maximum(mpre[i - 1], mpre[i]) # look for recall value changes i = np.where(mrec[1:] != mrec[:-1])[0] # sum (\delta recall) * prec ap = np.sum((mrec[i + 1] - mrec[i]) * mpre[i + 1]) return ap
python
def _average_precision(self, rec, prec): """ calculate average precision Params: ---------- rec : numpy.array cumulated recall prec : numpy.array cumulated precision Returns: ---------- ap as float """ # append sentinel values at both ends mrec = np.concatenate(([0.], rec, [1.])) mpre = np.concatenate(([0.], prec, [0.])) # compute precision integration ladder for i in range(mpre.size - 1, 0, -1): mpre[i - 1] = np.maximum(mpre[i - 1], mpre[i]) # look for recall value changes i = np.where(mrec[1:] != mrec[:-1])[0] # sum (\delta recall) * prec ap = np.sum((mrec[i + 1] - mrec[i]) * mpre[i + 1]) return ap
[ "def", "_average_precision", "(", "self", ",", "rec", ",", "prec", ")", ":", "# append sentinel values at both ends", "mrec", "=", "np", ".", "concatenate", "(", "(", "[", "0.", "]", ",", "rec", ",", "[", "1.", "]", ")", ")", "mpre", "=", "np", ".", "concatenate", "(", "(", "[", "0.", "]", ",", "prec", ",", "[", "0.", "]", ")", ")", "# compute precision integration ladder", "for", "i", "in", "range", "(", "mpre", ".", "size", "-", "1", ",", "0", ",", "-", "1", ")", ":", "mpre", "[", "i", "-", "1", "]", "=", "np", ".", "maximum", "(", "mpre", "[", "i", "-", "1", "]", ",", "mpre", "[", "i", "]", ")", "# look for recall value changes", "i", "=", "np", ".", "where", "(", "mrec", "[", "1", ":", "]", "!=", "mrec", "[", ":", "-", "1", "]", ")", "[", "0", "]", "# sum (\\delta recall) * prec", "ap", "=", "np", ".", "sum", "(", "(", "mrec", "[", "i", "+", "1", "]", "-", "mrec", "[", "i", "]", ")", "*", "mpre", "[", "i", "+", "1", "]", ")", "return", "ap" ]
calculate average precision Params: ---------- rec : numpy.array cumulated recall prec : numpy.array cumulated precision Returns: ---------- ap as float
[ "calculate", "average", "precision" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/ssd/evaluate/eval_metric.py#L227-L254
23,793
apache/incubator-mxnet
example/ssd/evaluate/eval_metric.py
MApMetric._insert
def _insert(self, key, records, count): """ Insert records according to key """ if key not in self.records: assert key not in self.counts self.records[key] = records self.counts[key] = count else: self.records[key] = np.vstack((self.records[key], records)) assert key in self.counts self.counts[key] += count
python
def _insert(self, key, records, count): """ Insert records according to key """ if key not in self.records: assert key not in self.counts self.records[key] = records self.counts[key] = count else: self.records[key] = np.vstack((self.records[key], records)) assert key in self.counts self.counts[key] += count
[ "def", "_insert", "(", "self", ",", "key", ",", "records", ",", "count", ")", ":", "if", "key", "not", "in", "self", ".", "records", ":", "assert", "key", "not", "in", "self", ".", "counts", "self", ".", "records", "[", "key", "]", "=", "records", "self", ".", "counts", "[", "key", "]", "=", "count", "else", ":", "self", ".", "records", "[", "key", "]", "=", "np", ".", "vstack", "(", "(", "self", ".", "records", "[", "key", "]", ",", "records", ")", ")", "assert", "key", "in", "self", ".", "counts", "self", ".", "counts", "[", "key", "]", "+=", "count" ]
Insert records according to key
[ "Insert", "records", "according", "to", "key" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/ssd/evaluate/eval_metric.py#L256-L265
23,794
apache/incubator-mxnet
example/ssd/evaluate/eval_metric.py
VOC07MApMetric._average_precision
def _average_precision(self, rec, prec): """ calculate average precision, override the default one, special 11-point metric Params: ---------- rec : numpy.array cumulated recall prec : numpy.array cumulated precision Returns: ---------- ap as float """ ap = 0. for t in np.arange(0., 1.1, 0.1): if np.sum(rec >= t) == 0: p = 0 else: p = np.max(prec[rec >= t]) ap += p / 11. return ap
python
def _average_precision(self, rec, prec): """ calculate average precision, override the default one, special 11-point metric Params: ---------- rec : numpy.array cumulated recall prec : numpy.array cumulated precision Returns: ---------- ap as float """ ap = 0. for t in np.arange(0., 1.1, 0.1): if np.sum(rec >= t) == 0: p = 0 else: p = np.max(prec[rec >= t]) ap += p / 11. return ap
[ "def", "_average_precision", "(", "self", ",", "rec", ",", "prec", ")", ":", "ap", "=", "0.", "for", "t", "in", "np", ".", "arange", "(", "0.", ",", "1.1", ",", "0.1", ")", ":", "if", "np", ".", "sum", "(", "rec", ">=", "t", ")", "==", "0", ":", "p", "=", "0", "else", ":", "p", "=", "np", ".", "max", "(", "prec", "[", "rec", ">=", "t", "]", ")", "ap", "+=", "p", "/", "11.", "return", "ap" ]
calculate average precision, override the default one, special 11-point metric Params: ---------- rec : numpy.array cumulated recall prec : numpy.array cumulated precision Returns: ---------- ap as float
[ "calculate", "average", "precision", "override", "the", "default", "one", "special", "11", "-", "point", "metric" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/ssd/evaluate/eval_metric.py#L273-L295
23,795
apache/incubator-mxnet
python/mxnet/initializer.py
Initializer._verbose_print
def _verbose_print(self, desc, init, arr): """Internal verbose print function Parameters ---------- desc : InitDesc or str name of the array init : str initializer pattern arr : NDArray initialized array """ if self._verbose and self._print_func: logging.info('Initialized %s as %s: %s', desc, init, self._print_func(arr))
python
def _verbose_print(self, desc, init, arr): """Internal verbose print function Parameters ---------- desc : InitDesc or str name of the array init : str initializer pattern arr : NDArray initialized array """ if self._verbose and self._print_func: logging.info('Initialized %s as %s: %s', desc, init, self._print_func(arr))
[ "def", "_verbose_print", "(", "self", ",", "desc", ",", "init", ",", "arr", ")", ":", "if", "self", ".", "_verbose", "and", "self", ".", "_print_func", ":", "logging", ".", "info", "(", "'Initialized %s as %s: %s'", ",", "desc", ",", "init", ",", "self", ".", "_print_func", "(", "arr", ")", ")" ]
Internal verbose print function Parameters ---------- desc : InitDesc or str name of the array init : str initializer pattern arr : NDArray initialized array
[ "Internal", "verbose", "print", "function" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/initializer.py#L82-L95
23,796
apache/incubator-mxnet
python/mxnet/initializer.py
Initializer._legacy_init
def _legacy_init(self, name, arr): """Legacy initialization method. Parameters ---------- name : str Name of corresponding NDArray. arr : NDArray NDArray to be initialized. """ warnings.warn( "\033[91mCalling initializer with init(str, NDArray) has been deprecated." \ "please use init(mx.init.InitDesc(...), NDArray) instead.\033[0m", DeprecationWarning, stacklevel=3) if not isinstance(name, string_types): raise TypeError('name must be string') if not isinstance(arr, NDArray): raise TypeError('arr must be NDArray') if name.startswith('upsampling'): self._init_bilinear(name, arr) elif name.startswith('stn_loc') and name.endswith('weight'): self._init_zero(name, arr) elif name.startswith('stn_loc') and name.endswith('bias'): self._init_loc_bias(name, arr) elif name.endswith('bias'): self._init_bias(name, arr) elif name.endswith('gamma'): self._init_gamma(name, arr) elif name.endswith('beta'): self._init_beta(name, arr) elif name.endswith('weight'): self._init_weight(name, arr) elif name.endswith("moving_mean"): self._init_zero(name, arr) elif name.endswith("moving_var"): self._init_one(name, arr) elif name.endswith("moving_inv_var"): self._init_zero(name, arr) elif name.endswith("moving_avg"): self._init_zero(name, arr) elif name.endswith('min'): self._init_zero(name, arr) elif name.endswith('max'): self._init_one(name, arr) else: self._init_default(name, arr)
python
def _legacy_init(self, name, arr): """Legacy initialization method. Parameters ---------- name : str Name of corresponding NDArray. arr : NDArray NDArray to be initialized. """ warnings.warn( "\033[91mCalling initializer with init(str, NDArray) has been deprecated." \ "please use init(mx.init.InitDesc(...), NDArray) instead.\033[0m", DeprecationWarning, stacklevel=3) if not isinstance(name, string_types): raise TypeError('name must be string') if not isinstance(arr, NDArray): raise TypeError('arr must be NDArray') if name.startswith('upsampling'): self._init_bilinear(name, arr) elif name.startswith('stn_loc') and name.endswith('weight'): self._init_zero(name, arr) elif name.startswith('stn_loc') and name.endswith('bias'): self._init_loc_bias(name, arr) elif name.endswith('bias'): self._init_bias(name, arr) elif name.endswith('gamma'): self._init_gamma(name, arr) elif name.endswith('beta'): self._init_beta(name, arr) elif name.endswith('weight'): self._init_weight(name, arr) elif name.endswith("moving_mean"): self._init_zero(name, arr) elif name.endswith("moving_var"): self._init_one(name, arr) elif name.endswith("moving_inv_var"): self._init_zero(name, arr) elif name.endswith("moving_avg"): self._init_zero(name, arr) elif name.endswith('min'): self._init_zero(name, arr) elif name.endswith('max'): self._init_one(name, arr) else: self._init_default(name, arr)
[ "def", "_legacy_init", "(", "self", ",", "name", ",", "arr", ")", ":", "warnings", ".", "warn", "(", "\"\\033[91mCalling initializer with init(str, NDArray) has been deprecated.\"", "\"please use init(mx.init.InitDesc(...), NDArray) instead.\\033[0m\"", ",", "DeprecationWarning", ",", "stacklevel", "=", "3", ")", "if", "not", "isinstance", "(", "name", ",", "string_types", ")", ":", "raise", "TypeError", "(", "'name must be string'", ")", "if", "not", "isinstance", "(", "arr", ",", "NDArray", ")", ":", "raise", "TypeError", "(", "'arr must be NDArray'", ")", "if", "name", ".", "startswith", "(", "'upsampling'", ")", ":", "self", ".", "_init_bilinear", "(", "name", ",", "arr", ")", "elif", "name", ".", "startswith", "(", "'stn_loc'", ")", "and", "name", ".", "endswith", "(", "'weight'", ")", ":", "self", ".", "_init_zero", "(", "name", ",", "arr", ")", "elif", "name", ".", "startswith", "(", "'stn_loc'", ")", "and", "name", ".", "endswith", "(", "'bias'", ")", ":", "self", ".", "_init_loc_bias", "(", "name", ",", "arr", ")", "elif", "name", ".", "endswith", "(", "'bias'", ")", ":", "self", ".", "_init_bias", "(", "name", ",", "arr", ")", "elif", "name", ".", "endswith", "(", "'gamma'", ")", ":", "self", ".", "_init_gamma", "(", "name", ",", "arr", ")", "elif", "name", ".", "endswith", "(", "'beta'", ")", ":", "self", ".", "_init_beta", "(", "name", ",", "arr", ")", "elif", "name", ".", "endswith", "(", "'weight'", ")", ":", "self", ".", "_init_weight", "(", "name", ",", "arr", ")", "elif", "name", ".", "endswith", "(", "\"moving_mean\"", ")", ":", "self", ".", "_init_zero", "(", "name", ",", "arr", ")", "elif", "name", ".", "endswith", "(", "\"moving_var\"", ")", ":", "self", ".", "_init_one", "(", "name", ",", "arr", ")", "elif", "name", ".", "endswith", "(", "\"moving_inv_var\"", ")", ":", "self", ".", "_init_zero", "(", "name", ",", "arr", ")", "elif", "name", ".", "endswith", "(", "\"moving_avg\"", ")", ":", "self", ".", "_init_zero", "(", "name", ",", "arr", ")", "elif", "name", ".", "endswith", "(", "'min'", ")", ":", "self", ".", "_init_zero", "(", "name", ",", "arr", ")", "elif", "name", ".", "endswith", "(", "'max'", ")", ":", "self", ".", "_init_one", "(", "name", ",", "arr", ")", "else", ":", "self", ".", "_init_default", "(", "name", ",", "arr", ")" ]
Legacy initialization method. Parameters ---------- name : str Name of corresponding NDArray. arr : NDArray NDArray to be initialized.
[ "Legacy", "initialization", "method", "." ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/initializer.py#L171-L217
23,797
apache/incubator-mxnet
example/ssd/dataset/imdb.py
Imdb.save_imglist
def save_imglist(self, fname=None, root=None, shuffle=False): """ save imglist to disk Parameters: ---------- fname : str saved filename """ def progress_bar(count, total, suffix=''): import sys bar_len = 24 filled_len = int(round(bar_len * count / float(total))) percents = round(100.0 * count / float(total), 1) bar = '=' * filled_len + '-' * (bar_len - filled_len) sys.stdout.write('[%s] %s%s ...%s\r' % (bar, percents, '%', suffix)) sys.stdout.flush() str_list = [] for index in range(self.num_images): progress_bar(index, self.num_images) label = self.label_from_index(index) if label.size < 1: continue path = self.image_path_from_index(index) if root: path = osp.relpath(path, root) str_list.append('\t'.join([str(index), str(2), str(label.shape[1])] \ + ["{0:.4f}".format(x) for x in label.ravel()] + [path,]) + '\n') if str_list: if shuffle: import random random.shuffle(str_list) if not fname: fname = self.name + '.lst' with open(fname, 'w') as f: for line in str_list: f.write(line) else: raise RuntimeError("No image in imdb")
python
def save_imglist(self, fname=None, root=None, shuffle=False): """ save imglist to disk Parameters: ---------- fname : str saved filename """ def progress_bar(count, total, suffix=''): import sys bar_len = 24 filled_len = int(round(bar_len * count / float(total))) percents = round(100.0 * count / float(total), 1) bar = '=' * filled_len + '-' * (bar_len - filled_len) sys.stdout.write('[%s] %s%s ...%s\r' % (bar, percents, '%', suffix)) sys.stdout.flush() str_list = [] for index in range(self.num_images): progress_bar(index, self.num_images) label = self.label_from_index(index) if label.size < 1: continue path = self.image_path_from_index(index) if root: path = osp.relpath(path, root) str_list.append('\t'.join([str(index), str(2), str(label.shape[1])] \ + ["{0:.4f}".format(x) for x in label.ravel()] + [path,]) + '\n') if str_list: if shuffle: import random random.shuffle(str_list) if not fname: fname = self.name + '.lst' with open(fname, 'w') as f: for line in str_list: f.write(line) else: raise RuntimeError("No image in imdb")
[ "def", "save_imglist", "(", "self", ",", "fname", "=", "None", ",", "root", "=", "None", ",", "shuffle", "=", "False", ")", ":", "def", "progress_bar", "(", "count", ",", "total", ",", "suffix", "=", "''", ")", ":", "import", "sys", "bar_len", "=", "24", "filled_len", "=", "int", "(", "round", "(", "bar_len", "*", "count", "/", "float", "(", "total", ")", ")", ")", "percents", "=", "round", "(", "100.0", "*", "count", "/", "float", "(", "total", ")", ",", "1", ")", "bar", "=", "'='", "*", "filled_len", "+", "'-'", "*", "(", "bar_len", "-", "filled_len", ")", "sys", ".", "stdout", ".", "write", "(", "'[%s] %s%s ...%s\\r'", "%", "(", "bar", ",", "percents", ",", "'%'", ",", "suffix", ")", ")", "sys", ".", "stdout", ".", "flush", "(", ")", "str_list", "=", "[", "]", "for", "index", "in", "range", "(", "self", ".", "num_images", ")", ":", "progress_bar", "(", "index", ",", "self", ".", "num_images", ")", "label", "=", "self", ".", "label_from_index", "(", "index", ")", "if", "label", ".", "size", "<", "1", ":", "continue", "path", "=", "self", ".", "image_path_from_index", "(", "index", ")", "if", "root", ":", "path", "=", "osp", ".", "relpath", "(", "path", ",", "root", ")", "str_list", ".", "append", "(", "'\\t'", ".", "join", "(", "[", "str", "(", "index", ")", ",", "str", "(", "2", ")", ",", "str", "(", "label", ".", "shape", "[", "1", "]", ")", "]", "+", "[", "\"{0:.4f}\"", ".", "format", "(", "x", ")", "for", "x", "in", "label", ".", "ravel", "(", ")", "]", "+", "[", "path", ",", "]", ")", "+", "'\\n'", ")", "if", "str_list", ":", "if", "shuffle", ":", "import", "random", "random", ".", "shuffle", "(", "str_list", ")", "if", "not", "fname", ":", "fname", "=", "self", ".", "name", "+", "'.lst'", "with", "open", "(", "fname", ",", "'w'", ")", "as", "f", ":", "for", "line", "in", "str_list", ":", "f", ".", "write", "(", "line", ")", "else", ":", "raise", "RuntimeError", "(", "\"No image in imdb\"", ")" ]
save imglist to disk Parameters: ---------- fname : str saved filename
[ "save", "imglist", "to", "disk" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/ssd/dataset/imdb.py#L70-L110
23,798
apache/incubator-mxnet
example/ssd/dataset/imdb.py
Imdb._load_class_names
def _load_class_names(self, filename, dirname): """ load class names from text file Parameters: ---------- filename: str file stores class names dirname: str file directory """ full_path = osp.join(dirname, filename) classes = [] with open(full_path, 'r') as f: classes = [l.strip() for l in f.readlines()] return classes
python
def _load_class_names(self, filename, dirname): """ load class names from text file Parameters: ---------- filename: str file stores class names dirname: str file directory """ full_path = osp.join(dirname, filename) classes = [] with open(full_path, 'r') as f: classes = [l.strip() for l in f.readlines()] return classes
[ "def", "_load_class_names", "(", "self", ",", "filename", ",", "dirname", ")", ":", "full_path", "=", "osp", ".", "join", "(", "dirname", ",", "filename", ")", "classes", "=", "[", "]", "with", "open", "(", "full_path", ",", "'r'", ")", "as", "f", ":", "classes", "=", "[", "l", ".", "strip", "(", ")", "for", "l", "in", "f", ".", "readlines", "(", ")", "]", "return", "classes" ]
load class names from text file Parameters: ---------- filename: str file stores class names dirname: str file directory
[ "load", "class", "names", "from", "text", "file" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/ssd/dataset/imdb.py#L112-L127
23,799
apache/incubator-mxnet
example/image-classification/train_mnist.py
read_data
def read_data(label, image): """ download and read data into numpy """ base_url = 'http://yann.lecun.com/exdb/mnist/' with gzip.open(download_file(base_url+label, os.path.join('data',label))) as flbl: magic, num = struct.unpack(">II", flbl.read(8)) label = np.fromstring(flbl.read(), dtype=np.int8) with gzip.open(download_file(base_url+image, os.path.join('data',image)), 'rb') as fimg: magic, num, rows, cols = struct.unpack(">IIII", fimg.read(16)) image = np.fromstring(fimg.read(), dtype=np.uint8).reshape(len(label), rows, cols) return (label, image)
python
def read_data(label, image): """ download and read data into numpy """ base_url = 'http://yann.lecun.com/exdb/mnist/' with gzip.open(download_file(base_url+label, os.path.join('data',label))) as flbl: magic, num = struct.unpack(">II", flbl.read(8)) label = np.fromstring(flbl.read(), dtype=np.int8) with gzip.open(download_file(base_url+image, os.path.join('data',image)), 'rb') as fimg: magic, num, rows, cols = struct.unpack(">IIII", fimg.read(16)) image = np.fromstring(fimg.read(), dtype=np.uint8).reshape(len(label), rows, cols) return (label, image)
[ "def", "read_data", "(", "label", ",", "image", ")", ":", "base_url", "=", "'http://yann.lecun.com/exdb/mnist/'", "with", "gzip", ".", "open", "(", "download_file", "(", "base_url", "+", "label", ",", "os", ".", "path", ".", "join", "(", "'data'", ",", "label", ")", ")", ")", "as", "flbl", ":", "magic", ",", "num", "=", "struct", ".", "unpack", "(", "\">II\"", ",", "flbl", ".", "read", "(", "8", ")", ")", "label", "=", "np", ".", "fromstring", "(", "flbl", ".", "read", "(", ")", ",", "dtype", "=", "np", ".", "int8", ")", "with", "gzip", ".", "open", "(", "download_file", "(", "base_url", "+", "image", ",", "os", ".", "path", ".", "join", "(", "'data'", ",", "image", ")", ")", ",", "'rb'", ")", "as", "fimg", ":", "magic", ",", "num", ",", "rows", ",", "cols", "=", "struct", ".", "unpack", "(", "\">IIII\"", ",", "fimg", ".", "read", "(", "16", ")", ")", "image", "=", "np", ".", "fromstring", "(", "fimg", ".", "read", "(", ")", ",", "dtype", "=", "np", ".", "uint8", ")", ".", "reshape", "(", "len", "(", "label", ")", ",", "rows", ",", "cols", ")", "return", "(", "label", ",", "image", ")" ]
download and read data into numpy
[ "download", "and", "read", "data", "into", "numpy" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/image-classification/train_mnist.py#L31-L42