partition
stringclasses
3 values
func_name
stringlengths
1
134
docstring
stringlengths
1
46.9k
path
stringlengths
4
223
original_string
stringlengths
75
104k
code
stringlengths
75
104k
docstring_tokens
listlengths
1
1.97k
repo
stringlengths
7
55
language
stringclasses
1 value
url
stringlengths
87
315
code_tokens
listlengths
19
28.4k
sha
stringlengths
40
40
train
discriminator1
First part of the discriminator which takes a 32x32 image as input and output a convolutional feature map, this is required to calculate the layer loss
example/vae-gan/vaegan_mxnet.py
def discriminator1(ndf, no_bias=True, fix_gamma=True, eps=1e-5 + 1e-12): '''First part of the discriminator which takes a 32x32 image as input and output a convolutional feature map, this is required to calculate the layer loss''' BatchNorm = mx.sym.BatchNorm data = mx.sym.Variable('data') d1 ...
def discriminator1(ndf, no_bias=True, fix_gamma=True, eps=1e-5 + 1e-12): '''First part of the discriminator which takes a 32x32 image as input and output a convolutional feature map, this is required to calculate the layer loss''' BatchNorm = mx.sym.BatchNorm data = mx.sym.Variable('data') d1 ...
[ "First", "part", "of", "the", "discriminator", "which", "takes", "a", "32x32", "image", "as", "input", "and", "output", "a", "convolutional", "feature", "map", "this", "is", "required", "to", "calculate", "the", "layer", "loss" ]
apache/incubator-mxnet
python
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/vae-gan/vaegan_mxnet.py#L118-L137
[ "def", "discriminator1", "(", "ndf", ",", "no_bias", "=", "True", ",", "fix_gamma", "=", "True", ",", "eps", "=", "1e-5", "+", "1e-12", ")", ":", "BatchNorm", "=", "mx", ".", "sym", ".", "BatchNorm", "data", "=", "mx", ".", "sym", ".", "Variable", ...
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
train
discriminator2
Second part of the discriminator which takes a 256x8x8 feature map as input and generates the loss based on whether the input image was a real one or fake one
example/vae-gan/vaegan_mxnet.py
def discriminator2(ndf, no_bias=True, fix_gamma=True, eps=1e-5 + 1e-12): '''Second part of the discriminator which takes a 256x8x8 feature map as input and generates the loss based on whether the input image was a real one or fake one''' BatchNorm = mx.sym.BatchNorm data = mx.sym.Variable('data') ...
def discriminator2(ndf, no_bias=True, fix_gamma=True, eps=1e-5 + 1e-12): '''Second part of the discriminator which takes a 256x8x8 feature map as input and generates the loss based on whether the input image was a real one or fake one''' BatchNorm = mx.sym.BatchNorm data = mx.sym.Variable('data') ...
[ "Second", "part", "of", "the", "discriminator", "which", "takes", "a", "256x8x8", "feature", "map", "as", "input", "and", "generates", "the", "loss", "based", "on", "whether", "the", "input", "image", "was", "a", "real", "one", "or", "fake", "one" ]
apache/incubator-mxnet
python
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/vae-gan/vaegan_mxnet.py#L139-L159
[ "def", "discriminator2", "(", "ndf", ",", "no_bias", "=", "True", ",", "fix_gamma", "=", "True", ",", "eps", "=", "1e-5", "+", "1e-12", ")", ":", "BatchNorm", "=", "mx", ".", "sym", ".", "BatchNorm", "data", "=", "mx", ".", "sym", ".", "Variable", ...
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
train
GaussianLogDensity
GaussianLogDensity loss calculation for layer wise loss
example/vae-gan/vaegan_mxnet.py
def GaussianLogDensity(x, mu, log_var, name='GaussianLogDensity', EPSILON = 1e-6): '''GaussianLogDensity loss calculation for layer wise loss ''' c = mx.sym.ones_like(log_var)*2.0 * 3.1416 c = mx.symbol.log(c) var = mx.sym.exp(log_var) x_mu2 = mx.symbol.square(x - mu) # [Issue] not sure the di...
def GaussianLogDensity(x, mu, log_var, name='GaussianLogDensity', EPSILON = 1e-6): '''GaussianLogDensity loss calculation for layer wise loss ''' c = mx.sym.ones_like(log_var)*2.0 * 3.1416 c = mx.symbol.log(c) var = mx.sym.exp(log_var) x_mu2 = mx.symbol.square(x - mu) # [Issue] not sure the di...
[ "GaussianLogDensity", "loss", "calculation", "for", "layer", "wise", "loss" ]
apache/incubator-mxnet
python
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/vae-gan/vaegan_mxnet.py#L161-L171
[ "def", "GaussianLogDensity", "(", "x", ",", "mu", ",", "log_var", ",", "name", "=", "'GaussianLogDensity'", ",", "EPSILON", "=", "1e-6", ")", ":", "c", "=", "mx", ".", "sym", ".", "ones_like", "(", "log_var", ")", "*", "2.0", "*", "3.1416", "c", "=",...
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
train
DiscriminatorLayerLoss
Calculate the discriminator layer loss
example/vae-gan/vaegan_mxnet.py
def DiscriminatorLayerLoss(): '''Calculate the discriminator layer loss ''' data = mx.sym.Variable('data') label = mx.sym.Variable('label') data = mx.sym.Flatten(data) label = mx.sym.Flatten(label) label = mx.sym.BlockGrad(label) zeros = mx.sym.zeros_like(data) output = -Gaussi...
def DiscriminatorLayerLoss(): '''Calculate the discriminator layer loss ''' data = mx.sym.Variable('data') label = mx.sym.Variable('label') data = mx.sym.Flatten(data) label = mx.sym.Flatten(label) label = mx.sym.BlockGrad(label) zeros = mx.sym.zeros_like(data) output = -Gaussi...
[ "Calculate", "the", "discriminator", "layer", "loss" ]
apache/incubator-mxnet
python
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/vae-gan/vaegan_mxnet.py#L173-L192
[ "def", "DiscriminatorLayerLoss", "(", ")", ":", "data", "=", "mx", ".", "sym", ".", "Variable", "(", "'data'", ")", "label", "=", "mx", ".", "sym", ".", "Variable", "(", "'label'", ")", "data", "=", "mx", ".", "sym", ".", "Flatten", "(", "data", ")...
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
train
KLDivergenceLoss
KLDivergenceLoss loss
example/vae-gan/vaegan_mxnet.py
def KLDivergenceLoss(): '''KLDivergenceLoss loss ''' data = mx.sym.Variable('data') mu1, lv1 = mx.sym.split(data, num_outputs=2, axis=0) mu2 = mx.sym.zeros_like(mu1) lv2 = mx.sym.zeros_like(lv1) v1 = mx.sym.exp(lv1) v2 = mx.sym.exp(lv2) mu_diff_sq = mx.sym.square(mu1 - mu2) di...
def KLDivergenceLoss(): '''KLDivergenceLoss loss ''' data = mx.sym.Variable('data') mu1, lv1 = mx.sym.split(data, num_outputs=2, axis=0) mu2 = mx.sym.zeros_like(mu1) lv2 = mx.sym.zeros_like(lv1) v1 = mx.sym.exp(lv1) v2 = mx.sym.exp(lv2) mu_diff_sq = mx.sym.square(mu1 - mu2) di...
[ "KLDivergenceLoss", "loss" ]
apache/incubator-mxnet
python
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/vae-gan/vaegan_mxnet.py#L194-L211
[ "def", "KLDivergenceLoss", "(", ")", ":", "data", "=", "mx", ".", "sym", ".", "Variable", "(", "'data'", ")", "mu1", ",", "lv1", "=", "mx", ".", "sym", ".", "split", "(", "data", ",", "num_outputs", "=", "2", ",", "axis", "=", "0", ")", "mu2", ...
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
train
get_data
Get the dataset
example/vae-gan/vaegan_mxnet.py
def get_data(path, activation): '''Get the dataset ''' data = [] image_names = [] for filename in os.listdir(path): img = cv2.imread(os.path.join(path,filename), cv2.IMREAD_GRAYSCALE) image_names.append(filename) if img is not None: data.append(img) data = np...
def get_data(path, activation): '''Get the dataset ''' data = [] image_names = [] for filename in os.listdir(path): img = cv2.imread(os.path.join(path,filename), cv2.IMREAD_GRAYSCALE) image_names.append(filename) if img is not None: data.append(img) data = np...
[ "Get", "the", "dataset" ]
apache/incubator-mxnet
python
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/vae-gan/vaegan_mxnet.py#L213-L237
[ "def", "get_data", "(", "path", ",", "activation", ")", ":", "data", "=", "[", "]", "image_names", "=", "[", "]", "for", "filename", "in", "os", ".", "listdir", "(", "path", ")", ":", "img", "=", "cv2", ".", "imread", "(", "os", ".", "path", ".",...
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
train
fill_buf
fill the ith grid of the buffer matrix with the values from the img buf : buffer matrix i : serial of the image in the 2D grid img : image data shape : ( height width depth ) of image
example/vae-gan/vaegan_mxnet.py
def fill_buf(buf, i, img, shape): '''fill the ith grid of the buffer matrix with the values from the img buf : buffer matrix i : serial of the image in the 2D grid img : image data shape : ( height width depth ) of image''' # grid height is a multiple of individual image height m = buf.shap...
def fill_buf(buf, i, img, shape): '''fill the ith grid of the buffer matrix with the values from the img buf : buffer matrix i : serial of the image in the 2D grid img : image data shape : ( height width depth ) of image''' # grid height is a multiple of individual image height m = buf.shap...
[ "fill", "the", "ith", "grid", "of", "the", "buffer", "matrix", "with", "the", "values", "from", "the", "img", "buf", ":", "buffer", "matrix", "i", ":", "serial", "of", "the", "image", "in", "the", "2D", "grid", "img", ":", "image", "data", "shape", "...
apache/incubator-mxnet
python
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/vae-gan/vaegan_mxnet.py#L254-L268
[ "def", "fill_buf", "(", "buf", ",", "i", ",", "img", ",", "shape", ")", ":", "# grid height is a multiple of individual image height", "m", "=", "buf", ".", "shape", "[", "0", "]", "/", "shape", "[", "0", "]", "sx", "=", "(", "i", "%", "m", ")", "*",...
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
train
visual
create a grid of images and save it as a final image title : grid image name X : array of images
example/vae-gan/vaegan_mxnet.py
def visual(title, X, activation): '''create a grid of images and save it as a final image title : grid image name X : array of images ''' assert len(X.shape) == 4 X = X.transpose((0, 2, 3, 1)) if activation == 'sigmoid': X = np.clip((X)*(255.0), 0, 255).astype(np.uint8) elif act...
def visual(title, X, activation): '''create a grid of images and save it as a final image title : grid image name X : array of images ''' assert len(X.shape) == 4 X = X.transpose((0, 2, 3, 1)) if activation == 'sigmoid': X = np.clip((X)*(255.0), 0, 255).astype(np.uint8) elif act...
[ "create", "a", "grid", "of", "images", "and", "save", "it", "as", "a", "final", "image", "title", ":", "grid", "image", "name", "X", ":", "array", "of", "images" ]
apache/incubator-mxnet
python
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/vae-gan/vaegan_mxnet.py#L270-L286
[ "def", "visual", "(", "title", ",", "X", ",", "activation", ")", ":", "assert", "len", "(", "X", ".", "shape", ")", "==", "4", "X", "=", "X", ".", "transpose", "(", "(", "0", ",", "2", ",", "3", ",", "1", ")", ")", "if", "activation", "==", ...
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
train
train
adversarial training of the VAE
example/vae-gan/vaegan_mxnet.py
def train(dataset, nef, ndf, ngf, nc, batch_size, Z, lr, beta1, epsilon, ctx, check_point, g_dl_weight, output_path, checkpoint_path, data_path, activation,num_epoch, save_after_every, visualize_after_every, show_after_every): '''adversarial training of the VAE ''' #encoder z_mu, z_lv, z = encoder(nef,...
def train(dataset, nef, ndf, ngf, nc, batch_size, Z, lr, beta1, epsilon, ctx, check_point, g_dl_weight, output_path, checkpoint_path, data_path, activation,num_epoch, save_after_every, visualize_after_every, show_after_every): '''adversarial training of the VAE ''' #encoder z_mu, z_lv, z = encoder(nef,...
[ "adversarial", "training", "of", "the", "VAE" ]
apache/incubator-mxnet
python
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/vae-gan/vaegan_mxnet.py#L288-L613
[ "def", "train", "(", "dataset", ",", "nef", ",", "ndf", ",", "ngf", ",", "nc", ",", "batch_size", ",", "Z", ",", "lr", ",", "beta1", ",", "epsilon", ",", "ctx", ",", "check_point", ",", "g_dl_weight", ",", "output_path", ",", "checkpoint_path", ",", ...
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
train
create_and_validate_dir
Creates/Validates dir
example/vae-gan/vaegan_mxnet.py
def create_and_validate_dir(data_dir): '''Creates/Validates dir ''' if data_dir != "": if not os.path.exists(data_dir): try: logging.info('create directory %s', data_dir) os.makedirs(data_dir) except OSError as exc: if exc.errno...
def create_and_validate_dir(data_dir): '''Creates/Validates dir ''' if data_dir != "": if not os.path.exists(data_dir): try: logging.info('create directory %s', data_dir) os.makedirs(data_dir) except OSError as exc: if exc.errno...
[ "Creates", "/", "Validates", "dir" ]
apache/incubator-mxnet
python
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/vae-gan/vaegan_mxnet.py#L660-L670
[ "def", "create_and_validate_dir", "(", "data_dir", ")", ":", "if", "data_dir", "!=", "\"\"", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "data_dir", ")", ":", "try", ":", "logging", ".", "info", "(", "'create directory %s'", ",", "data_dir", ...
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
train
parse_args
Parse args
example/vae-gan/vaegan_mxnet.py
def parse_args(): '''Parse args ''' parser = argparse.ArgumentParser(description='Train and Test an Adversarial Variatiional Encoder') parser.add_argument('--train', help='train the network', action='store_true') parser.add_argument('--test', help='test the network', action='store_true') parser...
def parse_args(): '''Parse args ''' parser = argparse.ArgumentParser(description='Train and Test an Adversarial Variatiional Encoder') parser.add_argument('--train', help='train the network', action='store_true') parser.add_argument('--test', help='test the network', action='store_true') parser...
[ "Parse", "args" ]
apache/incubator-mxnet
python
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/vae-gan/vaegan_mxnet.py#L673-L708
[ "def", "parse_args", "(", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "'Train and Test an Adversarial Variatiional Encoder'", ")", "parser", ".", "add_argument", "(", "'--train'", ",", "help", "=", "'train the network'", ",", ...
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
train
get_rmse_log
Gets root mse between the logarithms of the prediction and the truth.
example/gluon/house_prices/kaggle_k_fold_cross_validation.py
def get_rmse_log(net, X_train, y_train): """Gets root mse between the logarithms of the prediction and the truth.""" num_train = X_train.shape[0] clipped_preds = nd.clip(net(X_train), 1, float('inf')) return np.sqrt(2 * nd.sum(square_loss( nd.log(clipped_preds), nd.log(y_train))).asscalar() / nu...
def get_rmse_log(net, X_train, y_train): """Gets root mse between the logarithms of the prediction and the truth.""" num_train = X_train.shape[0] clipped_preds = nd.clip(net(X_train), 1, float('inf')) return np.sqrt(2 * nd.sum(square_loss( nd.log(clipped_preds), nd.log(y_train))).asscalar() / nu...
[ "Gets", "root", "mse", "between", "the", "logarithms", "of", "the", "prediction", "and", "the", "truth", "." ]
apache/incubator-mxnet
python
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/gluon/house_prices/kaggle_k_fold_cross_validation.py#L66-L71
[ "def", "get_rmse_log", "(", "net", ",", "X_train", ",", "y_train", ")", ":", "num_train", "=", "X_train", ".", "shape", "[", "0", "]", "clipped_preds", "=", "nd", ".", "clip", "(", "net", "(", "X_train", ")", ",", "1", ",", "float", "(", "'inf'", "...
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
train
get_net
Gets a neural network. Better results are obtained with modifications.
example/gluon/house_prices/kaggle_k_fold_cross_validation.py
def get_net(): """Gets a neural network. Better results are obtained with modifications.""" net = gluon.nn.Sequential() with net.name_scope(): net.add(gluon.nn.Dense(50, activation="relu")) net.add(gluon.nn.Dense(1)) net.initialize() return net
def get_net(): """Gets a neural network. Better results are obtained with modifications.""" net = gluon.nn.Sequential() with net.name_scope(): net.add(gluon.nn.Dense(50, activation="relu")) net.add(gluon.nn.Dense(1)) net.initialize() return net
[ "Gets", "a", "neural", "network", ".", "Better", "results", "are", "obtained", "with", "modifications", "." ]
apache/incubator-mxnet
python
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/gluon/house_prices/kaggle_k_fold_cross_validation.py#L73-L80
[ "def", "get_net", "(", ")", ":", "net", "=", "gluon", ".", "nn", ".", "Sequential", "(", ")", "with", "net", ".", "name_scope", "(", ")", ":", "net", ".", "add", "(", "gluon", ".", "nn", ".", "Dense", "(", "50", ",", "activation", "=", "\"relu\""...
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
train
train
Trains the model.
example/gluon/house_prices/kaggle_k_fold_cross_validation.py
def train(net, X_train, y_train, epochs, verbose_epoch, learning_rate, weight_decay, batch_size): """Trains the model.""" dataset_train = gluon.data.ArrayDataset(X_train, y_train) data_iter_train = gluon.data.DataLoader(dataset_train, batch_size, shuffle...
def train(net, X_train, y_train, epochs, verbose_epoch, learning_rate, weight_decay, batch_size): """Trains the model.""" dataset_train = gluon.data.ArrayDataset(X_train, y_train) data_iter_train = gluon.data.DataLoader(dataset_train, batch_size, shuffle...
[ "Trains", "the", "model", "." ]
apache/incubator-mxnet
python
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/gluon/house_prices/kaggle_k_fold_cross_validation.py#L82-L102
[ "def", "train", "(", "net", ",", "X_train", ",", "y_train", ",", "epochs", ",", "verbose_epoch", ",", "learning_rate", ",", "weight_decay", ",", "batch_size", ")", ":", "dataset_train", "=", "gluon", ".", "data", ".", "ArrayDataset", "(", "X_train", ",", "...
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
train
k_fold_cross_valid
Conducts k-fold cross validation for the model.
example/gluon/house_prices/kaggle_k_fold_cross_validation.py
def k_fold_cross_valid(k, epochs, verbose_epoch, X_train, y_train, learning_rate, weight_decay, batch_size): """Conducts k-fold cross validation for the model.""" assert k > 1 fold_size = X_train.shape[0] // k train_loss_sum = 0.0 test_loss_sum = 0.0 for test_idx in range...
def k_fold_cross_valid(k, epochs, verbose_epoch, X_train, y_train, learning_rate, weight_decay, batch_size): """Conducts k-fold cross validation for the model.""" assert k > 1 fold_size = X_train.shape[0] // k train_loss_sum = 0.0 test_loss_sum = 0.0 for test_idx in range...
[ "Conducts", "k", "-", "fold", "cross", "validation", "for", "the", "model", "." ]
apache/incubator-mxnet
python
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/gluon/house_prices/kaggle_k_fold_cross_validation.py#L104-L135
[ "def", "k_fold_cross_valid", "(", "k", ",", "epochs", ",", "verbose_epoch", ",", "X_train", ",", "y_train", ",", "learning_rate", ",", "weight_decay", ",", "batch_size", ")", ":", "assert", "k", ">", "1", "fold_size", "=", "X_train", ".", "shape", "[", "0"...
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
train
learn
Trains the model and predicts on the test data set.
example/gluon/house_prices/kaggle_k_fold_cross_validation.py
def learn(epochs, verbose_epoch, X_train, y_train, test, learning_rate, weight_decay, batch_size): """Trains the model and predicts on the test data set.""" net = get_net() _ = train(net, X_train, y_train, epochs, verbose_epoch, learning_rate, weight_decay, batch_size) preds =...
def learn(epochs, verbose_epoch, X_train, y_train, test, learning_rate, weight_decay, batch_size): """Trains the model and predicts on the test data set.""" net = get_net() _ = train(net, X_train, y_train, epochs, verbose_epoch, learning_rate, weight_decay, batch_size) preds =...
[ "Trains", "the", "model", "and", "predicts", "on", "the", "test", "data", "set", "." ]
apache/incubator-mxnet
python
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/gluon/house_prices/kaggle_k_fold_cross_validation.py#L152-L161
[ "def", "learn", "(", "epochs", ",", "verbose_epoch", ",", "X_train", ",", "y_train", ",", "test", ",", "learning_rate", ",", "weight_decay", ",", "batch_size", ")", ":", "net", "=", "get_net", "(", ")", "_", "=", "train", "(", "net", ",", "X_train", ",...
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
train
capsnet
Create CapsNet
example/capsnet/capsulenet.py
def capsnet(batch_size, n_class, num_routing, recon_loss_weight): """Create CapsNet""" # data.shape = [batch_size, 1, 28, 28] data = mx.sym.Variable('data') input_shape = (1, 28, 28) # Conv2D layer # net.shape = [batch_size, 256, 20, 20] conv1 = mx.sym.Convolution(data=data, ...
def capsnet(batch_size, n_class, num_routing, recon_loss_weight): """Create CapsNet""" # data.shape = [batch_size, 1, 28, 28] data = mx.sym.Variable('data') input_shape = (1, 28, 28) # Conv2D layer # net.shape = [batch_size, 256, 20, 20] conv1 = mx.sym.Convolution(data=data, ...
[ "Create", "CapsNet" ]
apache/incubator-mxnet
python
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/capsnet/capsulenet.py#L39-L100
[ "def", "capsnet", "(", "batch_size", ",", "n_class", ",", "num_routing", ",", "recon_loss_weight", ")", ":", "# data.shape = [batch_size, 1, 28, 28]", "data", "=", "mx", ".", "sym", ".", "Variable", "(", "'data'", ")", "input_shape", "=", "(", "1", ",", "28", ...
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
train
do_training
Perform CapsNet training
example/capsnet/capsulenet.py
def do_training(num_epoch, optimizer, kvstore, learning_rate, model_prefix, decay): """Perform CapsNet training""" summary_writer = SummaryWriter(args.tblog_dir) lr_scheduler = SimpleLRScheduler(learning_rate) optimizer_params = {'lr_scheduler': lr_scheduler} module.init_params() module.init_opt...
def do_training(num_epoch, optimizer, kvstore, learning_rate, model_prefix, decay): """Perform CapsNet training""" summary_writer = SummaryWriter(args.tblog_dir) lr_scheduler = SimpleLRScheduler(learning_rate) optimizer_params = {'lr_scheduler': lr_scheduler} module.init_params() module.init_opt...
[ "Perform", "CapsNet", "training" ]
apache/incubator-mxnet
python
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/capsnet/capsulenet.py#L195-L238
[ "def", "do_training", "(", "num_epoch", ",", "optimizer", ",", "kvstore", ",", "learning_rate", ",", "model_prefix", ",", "decay", ")", ":", "summary_writer", "=", "SummaryWriter", "(", "args", ".", "tblog_dir", ")", "lr_scheduler", "=", "SimpleLRScheduler", "("...
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
train
_shuffle
Shuffle the data.
example/capsnet/capsulenet.py
def _shuffle(data, idx): """Shuffle the data.""" shuffle_data = [] for idx_k, idx_v in data: shuffle_data.append((idx_k, mx.ndarray.array(idx_v.asnumpy()[idx], idx_v.context))) return shuffle_data
def _shuffle(data, idx): """Shuffle the data.""" shuffle_data = [] for idx_k, idx_v in data: shuffle_data.append((idx_k, mx.ndarray.array(idx_v.asnumpy()[idx], idx_v.context))) return shuffle_data
[ "Shuffle", "the", "data", "." ]
apache/incubator-mxnet
python
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/capsnet/capsulenet.py#L268-L275
[ "def", "_shuffle", "(", "data", ",", "idx", ")", ":", "shuffle_data", "=", "[", "]", "for", "idx_k", ",", "idx_v", "in", "data", ":", "shuffle_data", ".", "append", "(", "(", "idx_k", ",", "mx", ".", "ndarray", ".", "array", "(", "idx_v", ".", "asn...
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
train
LossMetric.update
Update the hyper-parameters and loss of CapsNet
example/capsnet/capsulenet.py
def update(self, labels, preds): """Update the hyper-parameters and loss of CapsNet""" batch_sum_metric = 0 batch_num_inst = 0 for label, pred_outcaps in zip(labels[0], preds[0]): label_np = int(label.asnumpy()) pred_label = int(np.argmax(pred_outcaps.asnumpy())) ...
def update(self, labels, preds): """Update the hyper-parameters and loss of CapsNet""" batch_sum_metric = 0 batch_num_inst = 0 for label, pred_outcaps in zip(labels[0], preds[0]): label_np = int(label.asnumpy()) pred_label = int(np.argmax(pred_outcaps.asnumpy())) ...
[ "Update", "the", "hyper", "-", "parameters", "and", "loss", "of", "CapsNet" ]
apache/incubator-mxnet
python
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/capsnet/capsulenet.py#L140-L158
[ "def", "update", "(", "self", ",", "labels", ",", "preds", ")", ":", "batch_sum_metric", "=", "0", "batch_num_inst", "=", "0", "for", "label", ",", "pred_outcaps", "in", "zip", "(", "labels", "[", "0", "]", ",", "preds", "[", "0", "]", ")", ":", "l...
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
train
MNISTCustomIter.reset
Reset class MNISTCustomIter(mx.io.NDArrayIter):
example/capsnet/capsulenet.py
def reset(self): """Reset class MNISTCustomIter(mx.io.NDArrayIter):""" # shuffle data if self.is_train: np.random.shuffle(self.idx) self.data = _shuffle(self.data, self.idx) self.label = _shuffle(self.label, self.idx) if self.last_batch_handle == 'rol...
def reset(self): """Reset class MNISTCustomIter(mx.io.NDArrayIter):""" # shuffle data if self.is_train: np.random.shuffle(self.idx) self.data = _shuffle(self.data, self.idx) self.label = _shuffle(self.label, self.idx) if self.last_batch_handle == 'rol...
[ "Reset", "class", "MNISTCustomIter", "(", "mx", ".", "io", ".", "NDArrayIter", ")", ":" ]
apache/incubator-mxnet
python
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/capsnet/capsulenet.py#L287-L298
[ "def", "reset", "(", "self", ")", ":", "# shuffle data", "if", "self", ".", "is_train", ":", "np", ".", "random", ".", "shuffle", "(", "self", ".", "idx", ")", "self", ".", "data", "=", "_shuffle", "(", "self", ".", "data", ",", "self", ".", "idx",...
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
train
MNISTCustomIter.next
Generate next of iterator
example/capsnet/capsulenet.py
def next(self): """Generate next of iterator""" if self.iter_next(): if self.is_train: data_raw_list = self.getdata() data_shifted = [] for data_raw in data_raw_list[0]: data_shifted.append(random_shift(data_raw.asnumpy(), 0...
def next(self): """Generate next of iterator""" if self.iter_next(): if self.is_train: data_raw_list = self.getdata() data_shifted = [] for data_raw in data_raw_list[0]: data_shifted.append(random_shift(data_raw.asnumpy(), 0...
[ "Generate", "next", "of", "iterator" ]
apache/incubator-mxnet
python
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/capsnet/capsulenet.py#L304-L318
[ "def", "next", "(", "self", ")", ":", "if", "self", ".", "iter_next", "(", ")", ":", "if", "self", ".", "is_train", ":", "data_raw_list", "=", "self", ".", "getdata", "(", ")", "data_shifted", "=", "[", "]", "for", "data_raw", "in", "data_raw_list", ...
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
train
AttrScope.get
Get the attribute dict given the attribute set by the symbol. Parameters ---------- attr : dict of string to string The attribute passed in by user during symbol creation. Returns ------- attr : dict of string to string Updated attributes to add ...
python/mxnet/attribute.py
def get(self, attr): """ Get the attribute dict given the attribute set by the symbol. Parameters ---------- attr : dict of string to string The attribute passed in by user during symbol creation. Returns ------- attr : dict of string to stri...
def get(self, attr): """ Get the attribute dict given the attribute set by the symbol. Parameters ---------- attr : dict of string to string The attribute passed in by user during symbol creation. Returns ------- attr : dict of string to stri...
[ "Get", "the", "attribute", "dict", "given", "the", "attribute", "set", "by", "the", "symbol", "." ]
apache/incubator-mxnet
python
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/attribute.py#L47-L67
[ "def", "get", "(", "self", ",", "attr", ")", ":", "if", "self", ".", "_attr", ":", "ret", "=", "self", ".", "_attr", ".", "copy", "(", ")", "if", "attr", ":", "ret", ".", "update", "(", "attr", ")", "return", "ret", "else", ":", "return", "attr...
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
train
_create_sparse_kvstore
Create kvstore assuming some parameters' storage types are row_sparse. Parameters ---------- kvstore : KVStore or str The kvstore. Returns ------- kvstore : KVStore update_on_kvstore : bool. Always True.
python/mxnet/model.py
def _create_sparse_kvstore(kvstore): """Create kvstore assuming some parameters' storage types are row_sparse. Parameters ---------- kvstore : KVStore or str The kvstore. Returns ------- kvstore : KVStore update_on_kvstore : bool. Always True. """ # always update on kvs...
def _create_sparse_kvstore(kvstore): """Create kvstore assuming some parameters' storage types are row_sparse. Parameters ---------- kvstore : KVStore or str The kvstore. Returns ------- kvstore : KVStore update_on_kvstore : bool. Always True. """ # always update on kvs...
[ "Create", "kvstore", "assuming", "some", "parameters", "storage", "types", "are", "row_sparse", "." ]
apache/incubator-mxnet
python
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/model.py#L58-L80
[ "def", "_create_sparse_kvstore", "(", "kvstore", ")", ":", "# always update on kvstore", "update_on_kvstore", "=", "True", "if", "isinstance", "(", "kvstore", ",", "kvs", ".", "KVStore", ")", ":", "kv", "=", "kvstore", "elif", "isinstance", "(", "kvstore", ",", ...
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
train
_create_kvstore
Create kvstore This function select and create a proper kvstore if given the kvstore type. Parameters ---------- kvstore : KVStore or str The kvstore. num_device : int The number of devices arg_params : dict of str to `NDArray`. Model parameter, dict of name to `NDArray`...
python/mxnet/model.py
def _create_kvstore(kvstore, num_device, arg_params): """Create kvstore This function select and create a proper kvstore if given the kvstore type. Parameters ---------- kvstore : KVStore or str The kvstore. num_device : int The number of devices arg_params : dict of str to ...
def _create_kvstore(kvstore, num_device, arg_params): """Create kvstore This function select and create a proper kvstore if given the kvstore type. Parameters ---------- kvstore : KVStore or str The kvstore. num_device : int The number of devices arg_params : dict of str to ...
[ "Create", "kvstore", "This", "function", "select", "and", "create", "a", "proper", "kvstore", "if", "given", "the", "kvstore", "type", "." ]
apache/incubator-mxnet
python
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/model.py#L82-L119
[ "def", "_create_kvstore", "(", "kvstore", ",", "num_device", ",", "arg_params", ")", ":", "update_on_kvstore", "=", "bool", "(", "int", "(", "os", ".", "getenv", "(", "'MXNET_UPDATE_ON_KVSTORE'", ",", "\"1\"", ")", ")", ")", "if", "kvstore", "is", "None", ...
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
train
_initialize_kvstore
Initialize kvstore
python/mxnet/model.py
def _initialize_kvstore(kvstore, param_arrays, arg_params, param_names, update_on_kvstore): """Initialize kvstore""" for idx, param_on_devs in enumerate(param_arrays): name = param_names[idx] kvstore.init(name, arg_params[name]) if update_on_kvstore: kvstore.pull(name, param...
def _initialize_kvstore(kvstore, param_arrays, arg_params, param_names, update_on_kvstore): """Initialize kvstore""" for idx, param_on_devs in enumerate(param_arrays): name = param_names[idx] kvstore.init(name, arg_params[name]) if update_on_kvstore: kvstore.pull(name, param...
[ "Initialize", "kvstore" ]
apache/incubator-mxnet
python
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/model.py#L121-L128
[ "def", "_initialize_kvstore", "(", "kvstore", ",", "param_arrays", ",", "arg_params", ",", "param_names", ",", "update_on_kvstore", ")", ":", "for", "idx", ",", "param_on_devs", "in", "enumerate", "(", "param_arrays", ")", ":", "name", "=", "param_names", "[", ...
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
train
_update_params_on_kvstore_nccl
Perform update of param_arrays from grad_arrays on NCCL kvstore.
python/mxnet/model.py
def _update_params_on_kvstore_nccl(param_arrays, grad_arrays, kvstore, param_names): """Perform update of param_arrays from grad_arrays on NCCL kvstore.""" valid_indices = [index for index, grad_list in enumerate(grad_arrays) if grad_list[0] is not None] valid_grad_arrays = [grad_arrays...
def _update_params_on_kvstore_nccl(param_arrays, grad_arrays, kvstore, param_names): """Perform update of param_arrays from grad_arrays on NCCL kvstore.""" valid_indices = [index for index, grad_list in enumerate(grad_arrays) if grad_list[0] is not None] valid_grad_arrays = [grad_arrays...
[ "Perform", "update", "of", "param_arrays", "from", "grad_arrays", "on", "NCCL", "kvstore", "." ]
apache/incubator-mxnet
python
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/model.py#L130-L148
[ "def", "_update_params_on_kvstore_nccl", "(", "param_arrays", ",", "grad_arrays", ",", "kvstore", ",", "param_names", ")", ":", "valid_indices", "=", "[", "index", "for", "index", ",", "grad_list", "in", "enumerate", "(", "grad_arrays", ")", "if", "grad_list", "...
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
train
_update_params_on_kvstore
Perform update of param_arrays from grad_arrays on kvstore.
python/mxnet/model.py
def _update_params_on_kvstore(param_arrays, grad_arrays, kvstore, param_names): """Perform update of param_arrays from grad_arrays on kvstore.""" for index, pair in enumerate(zip(param_arrays, grad_arrays)): arg_list, grad_list = pair if grad_list[0] is None: continue name = ...
def _update_params_on_kvstore(param_arrays, grad_arrays, kvstore, param_names): """Perform update of param_arrays from grad_arrays on kvstore.""" for index, pair in enumerate(zip(param_arrays, grad_arrays)): arg_list, grad_list = pair if grad_list[0] is None: continue name = ...
[ "Perform", "update", "of", "param_arrays", "from", "grad_arrays", "on", "kvstore", "." ]
apache/incubator-mxnet
python
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/model.py#L150-L160
[ "def", "_update_params_on_kvstore", "(", "param_arrays", ",", "grad_arrays", ",", "kvstore", ",", "param_names", ")", ":", "for", "index", ",", "pair", "in", "enumerate", "(", "zip", "(", "param_arrays", ",", "grad_arrays", ")", ")", ":", "arg_list", ",", "g...
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
train
_update_params
Perform update of param_arrays from grad_arrays not on kvstore.
python/mxnet/model.py
def _update_params(param_arrays, grad_arrays, updater, num_device, kvstore=None, param_names=None): """Perform update of param_arrays from grad_arrays not on kvstore.""" updates = [[] for _ in range(num_device)] for i, pair in enumerate(zip(param_arrays, grad_arrays)): arg_list, g...
def _update_params(param_arrays, grad_arrays, updater, num_device, kvstore=None, param_names=None): """Perform update of param_arrays from grad_arrays not on kvstore.""" updates = [[] for _ in range(num_device)] for i, pair in enumerate(zip(param_arrays, grad_arrays)): arg_list, g...
[ "Perform", "update", "of", "param_arrays", "from", "grad_arrays", "not", "on", "kvstore", "." ]
apache/incubator-mxnet
python
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/model.py#L162-L187
[ "def", "_update_params", "(", "param_arrays", ",", "grad_arrays", ",", "updater", ",", "num_device", ",", "kvstore", "=", "None", ",", "param_names", "=", "None", ")", ":", "updates", "=", "[", "[", "]", "for", "_", "in", "range", "(", "num_device", ")",...
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
train
_multiple_callbacks
Sends args and kwargs to any configured callbacks. This handles the cases where the 'callbacks' variable is ``None``, a single function, or a list.
python/mxnet/model.py
def _multiple_callbacks(callbacks, *args, **kwargs): """Sends args and kwargs to any configured callbacks. This handles the cases where the 'callbacks' variable is ``None``, a single function, or a list. """ if isinstance(callbacks, list): for cb in callbacks: cb(*args, **kwargs)...
def _multiple_callbacks(callbacks, *args, **kwargs): """Sends args and kwargs to any configured callbacks. This handles the cases where the 'callbacks' variable is ``None``, a single function, or a list. """ if isinstance(callbacks, list): for cb in callbacks: cb(*args, **kwargs)...
[ "Sends", "args", "and", "kwargs", "to", "any", "configured", "callbacks", ".", "This", "handles", "the", "cases", "where", "the", "callbacks", "variable", "is", "None", "a", "single", "function", "or", "a", "list", "." ]
apache/incubator-mxnet
python
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/model.py#L190-L200
[ "def", "_multiple_callbacks", "(", "callbacks", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "isinstance", "(", "callbacks", ",", "list", ")", ":", "for", "cb", "in", "callbacks", ":", "cb", "(", "*", "args", ",", "*", "*", "kwargs", ...
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
train
_train_multi_device
Internal training function on multiple devices. This function will also work for single device as well. Parameters ---------- symbol : Symbol The network configuration. ctx : list of Context The training devices. arg_names: list of str Name of all arguments of the networ...
python/mxnet/model.py
def _train_multi_device(symbol, ctx, arg_names, param_names, aux_names, arg_params, aux_params, begin_epoch, end_epoch, epoch_size, optimizer, kvstore, update_on_kvstore, train_data, eval_data=None, eval_metric=None, ...
def _train_multi_device(symbol, ctx, arg_names, param_names, aux_names, arg_params, aux_params, begin_epoch, end_epoch, epoch_size, optimizer, kvstore, update_on_kvstore, train_data, eval_data=None, eval_metric=None, ...
[ "Internal", "training", "function", "on", "multiple", "devices", ".", "This", "function", "will", "also", "work", "for", "single", "device", "as", "well", "." ]
apache/incubator-mxnet
python
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/model.py#L203-L390
[ "def", "_train_multi_device", "(", "symbol", ",", "ctx", ",", "arg_names", ",", "param_names", ",", "aux_names", ",", "arg_params", ",", "aux_params", ",", "begin_epoch", ",", "end_epoch", ",", "epoch_size", ",", "optimizer", ",", "kvstore", ",", "update_on_kvst...
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
train
save_checkpoint
Checkpoint the model data into file. Parameters ---------- prefix : str Prefix of model name. epoch : int The epoch number of the model. symbol : Symbol The input Symbol. arg_params : dict of str to NDArray Model parameter, dict of name to NDArray of net's weight...
python/mxnet/model.py
def save_checkpoint(prefix, epoch, symbol, arg_params, aux_params): """Checkpoint the model data into file. Parameters ---------- prefix : str Prefix of model name. epoch : int The epoch number of the model. symbol : Symbol The input Symbol. arg_params : dict of str ...
def save_checkpoint(prefix, epoch, symbol, arg_params, aux_params): """Checkpoint the model data into file. Parameters ---------- prefix : str Prefix of model name. epoch : int The epoch number of the model. symbol : Symbol The input Symbol. arg_params : dict of str ...
[ "Checkpoint", "the", "model", "data", "into", "file", "." ]
apache/incubator-mxnet
python
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/model.py#L394-L421
[ "def", "save_checkpoint", "(", "prefix", ",", "epoch", ",", "symbol", ",", "arg_params", ",", "aux_params", ")", ":", "if", "symbol", "is", "not", "None", ":", "symbol", ".", "save", "(", "'%s-symbol.json'", "%", "prefix", ")", "save_dict", "=", "{", "("...
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
train
load_checkpoint
Load model checkpoint from file. Parameters ---------- prefix : str Prefix of model name. epoch : int Epoch number of model we would like to load. Returns ------- symbol : Symbol The symbol configuration of computation network. arg_params : dict of str to NDArra...
python/mxnet/model.py
def load_checkpoint(prefix, epoch): """Load model checkpoint from file. Parameters ---------- prefix : str Prefix of model name. epoch : int Epoch number of model we would like to load. Returns ------- symbol : Symbol The symbol configuration of computation netw...
def load_checkpoint(prefix, epoch): """Load model checkpoint from file. Parameters ---------- prefix : str Prefix of model name. epoch : int Epoch number of model we would like to load. Returns ------- symbol : Symbol The symbol configuration of computation netw...
[ "Load", "model", "checkpoint", "from", "file", "." ]
apache/incubator-mxnet
python
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/model.py#L424-L458
[ "def", "load_checkpoint", "(", "prefix", ",", "epoch", ")", ":", "symbol", "=", "sym", ".", "load", "(", "'%s-symbol.json'", "%", "prefix", ")", "save_dict", "=", "nd", ".", "load", "(", "'%s-%04d.params'", "%", "(", "prefix", ",", "epoch", ")", ")", "...
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
train
FeedForward._check_arguments
verify the argument of the default symbol and user provided parameters
python/mxnet/model.py
def _check_arguments(self): """verify the argument of the default symbol and user provided parameters""" if self.argument_checked: return assert(self.symbol is not None) self.argument_checked = True # check if symbol contain duplicated names. _check_argument...
def _check_arguments(self): """verify the argument of the default symbol and user provided parameters""" if self.argument_checked: return assert(self.symbol is not None) self.argument_checked = True # check if symbol contain duplicated names. _check_argument...
[ "verify", "the", "argument", "of", "the", "default", "symbol", "and", "user", "provided", "parameters" ]
apache/incubator-mxnet
python
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/model.py#L546-L565
[ "def", "_check_arguments", "(", "self", ")", ":", "if", "self", ".", "argument_checked", ":", "return", "assert", "(", "self", ".", "symbol", "is", "not", "None", ")", "self", ".", "argument_checked", "=", "True", "# check if symbol contain duplicated names.", "...
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
train
FeedForward._init_params
Initialize weight parameters and auxiliary states.
python/mxnet/model.py
def _init_params(self, inputs, overwrite=False): """Initialize weight parameters and auxiliary states.""" inputs = [x if isinstance(x, DataDesc) else DataDesc(*x) for x in inputs] input_shapes = {item.name: item.shape for item in inputs} arg_shapes, _, aux_shapes = self.symbol.infer_shap...
def _init_params(self, inputs, overwrite=False): """Initialize weight parameters and auxiliary states.""" inputs = [x if isinstance(x, DataDesc) else DataDesc(*x) for x in inputs] input_shapes = {item.name: item.shape for item in inputs} arg_shapes, _, aux_shapes = self.symbol.infer_shap...
[ "Initialize", "weight", "parameters", "and", "auxiliary", "states", "." ]
apache/incubator-mxnet
python
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/model.py#L573-L611
[ "def", "_init_params", "(", "self", ",", "inputs", ",", "overwrite", "=", "False", ")", ":", "inputs", "=", "[", "x", "if", "isinstance", "(", "x", ",", "DataDesc", ")", "else", "DataDesc", "(", "*", "x", ")", "for", "x", "in", "inputs", "]", "inpu...
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
train
FeedForward._init_predictor
Initialize the predictor module for running prediction.
python/mxnet/model.py
def _init_predictor(self, input_shapes, type_dict=None): """Initialize the predictor module for running prediction.""" shapes = {name: self.arg_params[name].shape for name in self.arg_params} shapes.update(dict(input_shapes)) if self._pred_exec is not None: arg_shapes, _, _ =...
def _init_predictor(self, input_shapes, type_dict=None): """Initialize the predictor module for running prediction.""" shapes = {name: self.arg_params[name].shape for name in self.arg_params} shapes.update(dict(input_shapes)) if self._pred_exec is not None: arg_shapes, _, _ =...
[ "Initialize", "the", "predictor", "module", "for", "running", "prediction", "." ]
apache/incubator-mxnet
python
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/model.py#L621-L637
[ "def", "_init_predictor", "(", "self", ",", "input_shapes", ",", "type_dict", "=", "None", ")", ":", "shapes", "=", "{", "name", ":", "self", ".", "arg_params", "[", "name", "]", ".", "shape", "for", "name", "in", "self", ".", "arg_params", "}", "shape...
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
train
FeedForward._init_iter
Initialize the iterator given input.
python/mxnet/model.py
def _init_iter(self, X, y, is_train): """Initialize the iterator given input.""" if isinstance(X, (np.ndarray, nd.NDArray)): if y is None: if is_train: raise ValueError('y must be specified when X is numpy.ndarray') else: ...
def _init_iter(self, X, y, is_train): """Initialize the iterator given input.""" if isinstance(X, (np.ndarray, nd.NDArray)): if y is None: if is_train: raise ValueError('y must be specified when X is numpy.ndarray') else: ...
[ "Initialize", "the", "iterator", "given", "input", "." ]
apache/incubator-mxnet
python
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/model.py#L639-L662
[ "def", "_init_iter", "(", "self", ",", "X", ",", "y", ",", "is_train", ")", ":", "if", "isinstance", "(", "X", ",", "(", "np", ".", "ndarray", ",", "nd", ".", "NDArray", ")", ")", ":", "if", "y", "is", "None", ":", "if", "is_train", ":", "raise...
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
train
FeedForward._init_eval_iter
Initialize the iterator given eval_data.
python/mxnet/model.py
def _init_eval_iter(self, eval_data): """Initialize the iterator given eval_data.""" if eval_data is None: return eval_data if isinstance(eval_data, (tuple, list)) and len(eval_data) == 2: if eval_data[0] is not None: if eval_data[1] is None and isinstance...
def _init_eval_iter(self, eval_data): """Initialize the iterator given eval_data.""" if eval_data is None: return eval_data if isinstance(eval_data, (tuple, list)) and len(eval_data) == 2: if eval_data[0] is not None: if eval_data[1] is None and isinstance...
[ "Initialize", "the", "iterator", "given", "eval_data", "." ]
apache/incubator-mxnet
python
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/model.py#L664-L682
[ "def", "_init_eval_iter", "(", "self", ",", "eval_data", ")", ":", "if", "eval_data", "is", "None", ":", "return", "eval_data", "if", "isinstance", "(", "eval_data", ",", "(", "tuple", ",", "list", ")", ")", "and", "len", "(", "eval_data", ")", "==", "...
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
train
FeedForward.predict
Run the prediction, always only use one device. Parameters ---------- X : mxnet.DataIter num_batch : int or None The number of batch to run. Go though all batches if ``None``. Returns ------- y : numpy.ndarray or a list of numpy.ndarray if the network...
python/mxnet/model.py
def predict(self, X, num_batch=None, return_data=False, reset=True): """Run the prediction, always only use one device. Parameters ---------- X : mxnet.DataIter num_batch : int or None The number of batch to run. Go though all batches if ``None``. Returns ...
def predict(self, X, num_batch=None, return_data=False, reset=True): """Run the prediction, always only use one device. Parameters ---------- X : mxnet.DataIter num_batch : int or None The number of batch to run. Go though all batches if ``None``. Returns ...
[ "Run", "the", "prediction", "always", "only", "use", "one", "device", "." ]
apache/incubator-mxnet
python
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/model.py#L684-L751
[ "def", "predict", "(", "self", ",", "X", ",", "num_batch", "=", "None", ",", "return_data", "=", "False", ",", "reset", "=", "True", ")", ":", "X", "=", "self", ".", "_init_iter", "(", "X", ",", "None", ",", "is_train", "=", "False", ")", "if", "...
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
train
FeedForward.score
Run the model given an input and calculate the score as assessed by an evaluation metric. Parameters ---------- X : mxnet.DataIter eval_metric : metric.metric The metric for calculating score. num_batch : int or None The number of batches to run. ...
python/mxnet/model.py
def score(self, X, eval_metric='acc', num_batch=None, batch_end_callback=None, reset=True): """Run the model given an input and calculate the score as assessed by an evaluation metric. Parameters ---------- X : mxnet.DataIter eval_metric : metric.metric The m...
def score(self, X, eval_metric='acc', num_batch=None, batch_end_callback=None, reset=True): """Run the model given an input and calculate the score as assessed by an evaluation metric. Parameters ---------- X : mxnet.DataIter eval_metric : metric.metric The m...
[ "Run", "the", "model", "given", "an", "input", "and", "calculate", "the", "score", "as", "assessed", "by", "an", "evaluation", "metric", "." ]
apache/incubator-mxnet
python
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/model.py#L753-L802
[ "def", "score", "(", "self", ",", "X", ",", "eval_metric", "=", "'acc'", ",", "num_batch", "=", "None", ",", "batch_end_callback", "=", "None", ",", "reset", "=", "True", ")", ":", "# setup metric", "if", "not", "isinstance", "(", "eval_metric", ",", "me...
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
train
FeedForward.fit
Fit the model. Parameters ---------- X : DataIter, or numpy.ndarray/NDArray Training data. If `X` is a `DataIter`, the name or (if name not available) the position of its outputs should match the corresponding variable names defined in the symbolic graph. ...
python/mxnet/model.py
def fit(self, X, y=None, eval_data=None, eval_metric='acc', epoch_end_callback=None, batch_end_callback=None, kvstore='local', logger=None, work_load_list=None, monitor=None, eval_end_callback=LogValidationMetricsCallback(), eval_batch_end_callback=None): """Fit the model. ...
def fit(self, X, y=None, eval_data=None, eval_metric='acc', epoch_end_callback=None, batch_end_callback=None, kvstore='local', logger=None, work_load_list=None, monitor=None, eval_end_callback=LogValidationMetricsCallback(), eval_batch_end_callback=None): """Fit the model. ...
[ "Fit", "the", "model", "." ]
apache/incubator-mxnet
python
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/model.py#L804-L905
[ "def", "fit", "(", "self", ",", "X", ",", "y", "=", "None", ",", "eval_data", "=", "None", ",", "eval_metric", "=", "'acc'", ",", "epoch_end_callback", "=", "None", ",", "batch_end_callback", "=", "None", ",", "kvstore", "=", "'local'", ",", "logger", ...
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
train
FeedForward.save
Checkpoint the model checkpoint into file. You can also use `pickle` to do the job if you only work on Python. The advantage of `load` and `save` (as compared to `pickle`) is that the resulting file can be loaded from other MXNet language bindings. One can also directly `load`/`save` fro...
python/mxnet/model.py
def save(self, prefix, epoch=None): """Checkpoint the model checkpoint into file. You can also use `pickle` to do the job if you only work on Python. The advantage of `load` and `save` (as compared to `pickle`) is that the resulting file can be loaded from other MXNet language bindings. ...
def save(self, prefix, epoch=None): """Checkpoint the model checkpoint into file. You can also use `pickle` to do the job if you only work on Python. The advantage of `load` and `save` (as compared to `pickle`) is that the resulting file can be loaded from other MXNet language bindings. ...
[ "Checkpoint", "the", "model", "checkpoint", "into", "file", ".", "You", "can", "also", "use", "pickle", "to", "do", "the", "job", "if", "you", "only", "work", "on", "Python", ".", "The", "advantage", "of", "load", "and", "save", "(", "as", "compared", ...
apache/incubator-mxnet
python
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/model.py#L908-L928
[ "def", "save", "(", "self", ",", "prefix", ",", "epoch", "=", "None", ")", ":", "if", "epoch", "is", "None", ":", "epoch", "=", "self", ".", "num_epoch", "assert", "epoch", "is", "not", "None", "save_checkpoint", "(", "prefix", ",", "epoch", ",", "se...
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
train
FeedForward.load
Load model checkpoint from file. Parameters ---------- prefix : str Prefix of model name. epoch : int epoch number of model we would like to load. ctx : Context or list of Context, optional The device context of training and prediction. ...
python/mxnet/model.py
def load(prefix, epoch, ctx=None, **kwargs): """Load model checkpoint from file. Parameters ---------- prefix : str Prefix of model name. epoch : int epoch number of model we would like to load. ctx : Context or list of Context, optional ...
def load(prefix, epoch, ctx=None, **kwargs): """Load model checkpoint from file. Parameters ---------- prefix : str Prefix of model name. epoch : int epoch number of model we would like to load. ctx : Context or list of Context, optional ...
[ "Load", "model", "checkpoint", "from", "file", "." ]
apache/incubator-mxnet
python
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/model.py#L931-L959
[ "def", "load", "(", "prefix", ",", "epoch", ",", "ctx", "=", "None", ",", "*", "*", "kwargs", ")", ":", "symbol", ",", "arg_params", ",", "aux_params", "=", "load_checkpoint", "(", "prefix", ",", "epoch", ")", "return", "FeedForward", "(", "symbol", ",...
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
train
FeedForward.create
Functional style to create a model. This function is more consistent with functional languages such as R, where mutation is not allowed. Parameters ---------- symbol : Symbol The symbol configuration of a computation network. X : DataIter Training...
python/mxnet/model.py
def create(symbol, X, y=None, ctx=None, num_epoch=None, epoch_size=None, optimizer='sgd', initializer=Uniform(0.01), eval_data=None, eval_metric='acc', epoch_end_callback=None, batch_end_callback=None, kvstore='local', logger=None, work_load_list=None, ...
def create(symbol, X, y=None, ctx=None, num_epoch=None, epoch_size=None, optimizer='sgd', initializer=Uniform(0.01), eval_data=None, eval_metric='acc', epoch_end_callback=None, batch_end_callback=None, kvstore='local', logger=None, work_load_list=None, ...
[ "Functional", "style", "to", "create", "a", "model", ".", "This", "function", "is", "more", "consistent", "with", "functional", "languages", "such", "as", "R", "where", "mutation", "is", "not", "allowed", "." ]
apache/incubator-mxnet
python
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/model.py#L962-L1025
[ "def", "create", "(", "symbol", ",", "X", ",", "y", "=", "None", ",", "ctx", "=", "None", ",", "num_epoch", "=", "None", ",", "epoch_size", "=", "None", ",", "optimizer", "=", "'sgd'", ",", "initializer", "=", "Uniform", "(", "0.01", ")", ",", "eva...
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
train
build_save_containers
Entry point to build and upload all built dockerimages in parallel :param platforms: List of platforms :param registry: Docker registry name :param load_cache: Load cache before building :return: 1 if error occurred, 0 otherwise
ci/docker_cache.py
def build_save_containers(platforms, registry, load_cache) -> int: """ Entry point to build and upload all built dockerimages in parallel :param platforms: List of platforms :param registry: Docker registry name :param load_cache: Load cache before building :return: 1 if error occurred, 0 otherw...
def build_save_containers(platforms, registry, load_cache) -> int: """ Entry point to build and upload all built dockerimages in parallel :param platforms: List of platforms :param registry: Docker registry name :param load_cache: Load cache before building :return: 1 if error occurred, 0 otherw...
[ "Entry", "point", "to", "build", "and", "upload", "all", "built", "dockerimages", "in", "parallel", ":", "param", "platforms", ":", "List", "of", "platforms", ":", "param", "registry", ":", "Docker", "registry", "name", ":", "param", "load_cache", ":", "Load...
apache/incubator-mxnet
python
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/ci/docker_cache.py#L44-L66
[ "def", "build_save_containers", "(", "platforms", ",", "registry", ",", "load_cache", ")", "->", "int", ":", "from", "joblib", "import", "Parallel", ",", "delayed", "if", "len", "(", "platforms", ")", "==", "0", ":", "return", "0", "platform_results", "=", ...
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
train
_build_save_container
Build image for passed platform and upload the cache to the specified S3 bucket :param platform: Platform :param registry: Docker registry name :param load_cache: Load cache before building :return: Platform if failed, None otherwise
ci/docker_cache.py
def _build_save_container(platform, registry, load_cache) -> Optional[str]: """ Build image for passed platform and upload the cache to the specified S3 bucket :param platform: Platform :param registry: Docker registry name :param load_cache: Load cache before building :return: Platform if faile...
def _build_save_container(platform, registry, load_cache) -> Optional[str]: """ Build image for passed platform and upload the cache to the specified S3 bucket :param platform: Platform :param registry: Docker registry name :param load_cache: Load cache before building :return: Platform if faile...
[ "Build", "image", "for", "passed", "platform", "and", "upload", "the", "cache", "to", "the", "specified", "S3", "bucket", ":", "param", "platform", ":", "Platform", ":", "param", "registry", ":", "Docker", "registry", "name", ":", "param", "load_cache", ":",...
apache/incubator-mxnet
python
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/ci/docker_cache.py#L69-L95
[ "def", "_build_save_container", "(", "platform", ",", "registry", ",", "load_cache", ")", "->", "Optional", "[", "str", "]", ":", "docker_tag", "=", "build_util", ".", "get_docker_tag", "(", "platform", "=", "platform", ",", "registry", "=", "registry", ")", ...
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
train
_upload_image
Upload the passed image by id, tag it with docker tag and upload to S3 bucket :param registry: Docker registry name :param docker_tag: Docker tag :param image_id: Image id :return: None
ci/docker_cache.py
def _upload_image(registry, docker_tag, image_id) -> None: """ Upload the passed image by id, tag it with docker tag and upload to S3 bucket :param registry: Docker registry name :param docker_tag: Docker tag :param image_id: Image id :return: None """ # We don't have to retag the image ...
def _upload_image(registry, docker_tag, image_id) -> None: """ Upload the passed image by id, tag it with docker tag and upload to S3 bucket :param registry: Docker registry name :param docker_tag: Docker tag :param image_id: Image id :return: None """ # We don't have to retag the image ...
[ "Upload", "the", "passed", "image", "by", "id", "tag", "it", "with", "docker", "tag", "and", "upload", "to", "S3", "bucket", ":", "param", "registry", ":", "Docker", "registry", "name", ":", "param", "docker_tag", ":", "Docker", "tag", ":", "param", "ima...
apache/incubator-mxnet
python
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/ci/docker_cache.py#L100-L111
[ "def", "_upload_image", "(", "registry", ",", "docker_tag", ",", "image_id", ")", "->", "None", ":", "# We don't have to retag the image since it is already in the right format", "logging", ".", "info", "(", "'Uploading %s (%s) to %s'", ",", "docker_tag", ",", "image_id", ...
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
train
_login_dockerhub
Login to the Docker Hub account :return: None
ci/docker_cache.py
def _login_dockerhub(): """ Login to the Docker Hub account :return: None """ dockerhub_credentials = _get_dockerhub_credentials() logging.info('Logging in to DockerHub') # We use password-stdin instead of --password to avoid leaking passwords in case of an error. # This method will pro...
def _login_dockerhub(): """ Login to the Docker Hub account :return: None """ dockerhub_credentials = _get_dockerhub_credentials() logging.info('Logging in to DockerHub') # We use password-stdin instead of --password to avoid leaking passwords in case of an error. # This method will pro...
[ "Login", "to", "the", "Docker", "Hub", "account", ":", "return", ":", "None" ]
apache/incubator-mxnet
python
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/ci/docker_cache.py#L116-L134
[ "def", "_login_dockerhub", "(", ")", ":", "dockerhub_credentials", "=", "_get_dockerhub_credentials", "(", ")", "logging", ".", "info", "(", "'Logging in to DockerHub'", ")", "# We use password-stdin instead of --password to avoid leaking passwords in case of an error.", "# This me...
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
train
load_docker_cache
Load the precompiled docker cache from the registry :param registry: Docker registry name :param docker_tag: Docker tag to load :return: None
ci/docker_cache.py
def load_docker_cache(registry, docker_tag) -> None: """ Load the precompiled docker cache from the registry :param registry: Docker registry name :param docker_tag: Docker tag to load :return: None """ # We don't have to retag the image since it's already in the right format if not regi...
def load_docker_cache(registry, docker_tag) -> None: """ Load the precompiled docker cache from the registry :param registry: Docker registry name :param docker_tag: Docker tag to load :return: None """ # We don't have to retag the image since it's already in the right format if not regi...
[ "Load", "the", "precompiled", "docker", "cache", "from", "the", "registry", ":", "param", "registry", ":", "Docker", "registry", "name", ":", "param", "docker_tag", ":", "Docker", "tag", "to", "load", ":", "return", ":", "None" ]
apache/incubator-mxnet
python
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/ci/docker_cache.py#L149-L166
[ "def", "load_docker_cache", "(", "registry", ",", "docker_tag", ")", "->", "None", ":", "# We don't have to retag the image since it's already in the right format", "if", "not", "registry", ":", "return", "assert", "docker_tag", "logging", ".", "info", "(", "'Loading Dock...
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
train
delete_local_docker_cache
Delete the local docker cache for the entire docker image chain :param docker_tag: Docker tag :return: None
ci/docker_cache.py
def delete_local_docker_cache(docker_tag): """ Delete the local docker cache for the entire docker image chain :param docker_tag: Docker tag :return: None """ history_cmd = ['docker', 'history', '-q', docker_tag] try: image_ids_b = subprocess.check_output(history_cmd) image_...
def delete_local_docker_cache(docker_tag): """ Delete the local docker cache for the entire docker image chain :param docker_tag: Docker tag :return: None """ history_cmd = ['docker', 'history', '-q', docker_tag] try: image_ids_b = subprocess.check_output(history_cmd) image_...
[ "Delete", "the", "local", "docker", "cache", "for", "the", "entire", "docker", "image", "chain", ":", "param", "docker_tag", ":", "Docker", "tag", ":", "return", ":", "None" ]
apache/incubator-mxnet
python
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/ci/docker_cache.py#L169-L187
[ "def", "delete_local_docker_cache", "(", "docker_tag", ")", ":", "history_cmd", "=", "[", "'docker'", ",", "'history'", ",", "'-q'", ",", "docker_tag", "]", "try", ":", "image_ids_b", "=", "subprocess", ".", "check_output", "(", "history_cmd", ")", "image_ids_st...
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
train
main
Utility to create and publish the Docker cache to Docker Hub :return:
ci/docker_cache.py
def main() -> int: """ Utility to create and publish the Docker cache to Docker Hub :return: """ # We need to be in the same directory than the script so the commands in the dockerfiles work as # expected. But the script can be invoked from a different path base = os.path.split(os.path.realp...
def main() -> int: """ Utility to create and publish the Docker cache to Docker Hub :return: """ # We need to be in the same directory than the script so the commands in the dockerfiles work as # expected. But the script can be invoked from a different path base = os.path.split(os.path.realp...
[ "Utility", "to", "create", "and", "publish", "the", "Docker", "cache", "to", "Docker", "Hub", ":", "return", ":" ]
apache/incubator-mxnet
python
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/ci/docker_cache.py#L221-L255
[ "def", "main", "(", ")", "->", "int", ":", "# We need to be in the same directory than the script so the commands in the dockerfiles work as", "# expected. But the script can be invoked from a different path", "base", "=", "os", ".", "path", ".", "split", "(", "os", ".", "path"...
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
train
get_chinese_text
Download the chinese_text dataset and unzip it
example/cnn_chinese_text_classification/data_helpers.py
def get_chinese_text(): """Download the chinese_text dataset and unzip it""" if not os.path.isdir("data/"): os.system("mkdir data/") if (not os.path.exists('data/pos.txt')) or \ (not os.path.exists('data/neg')): os.system("wget -q https://raw.githubusercontent.com/dmlc/web-data/master...
def get_chinese_text(): """Download the chinese_text dataset and unzip it""" if not os.path.isdir("data/"): os.system("mkdir data/") if (not os.path.exists('data/pos.txt')) or \ (not os.path.exists('data/neg')): os.system("wget -q https://raw.githubusercontent.com/dmlc/web-data/master...
[ "Download", "the", "chinese_text", "dataset", "and", "unzip", "it" ]
apache/incubator-mxnet
python
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/cnn_chinese_text_classification/data_helpers.py#L51-L61
[ "def", "get_chinese_text", "(", ")", ":", "if", "not", "os", ".", "path", ".", "isdir", "(", "\"data/\"", ")", ":", "os", ".", "system", "(", "\"mkdir data/\"", ")", "if", "(", "not", "os", ".", "path", ".", "exists", "(", "'data/pos.txt'", ")", ")",...
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
train
load_data_and_labels
Loads MR polarity data from files, splits the data into words and generates labels. Returns split sentences and labels.
example/cnn_chinese_text_classification/data_helpers.py
def load_data_and_labels(): """Loads MR polarity data from files, splits the data into words and generates labels. Returns split sentences and labels. """ # download dataset get_chinese_text() # Load data from files positive_examples = list(codecs.open("./data/pos.txt", "r", "utf-8").readli...
def load_data_and_labels(): """Loads MR polarity data from files, splits the data into words and generates labels. Returns split sentences and labels. """ # download dataset get_chinese_text() # Load data from files positive_examples = list(codecs.open("./data/pos.txt", "r", "utf-8").readli...
[ "Loads", "MR", "polarity", "data", "from", "files", "splits", "the", "data", "into", "words", "and", "generates", "labels", ".", "Returns", "split", "sentences", "and", "labels", "." ]
apache/incubator-mxnet
python
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/cnn_chinese_text_classification/data_helpers.py#L64-L87
[ "def", "load_data_and_labels", "(", ")", ":", "# download dataset", "get_chinese_text", "(", ")", "# Load data from files", "positive_examples", "=", "list", "(", "codecs", ".", "open", "(", "\"./data/pos.txt\"", ",", "\"r\"", ",", "\"utf-8\"", ")", ".", "readlines"...
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
train
MultiBoxMetric.reset
override reset behavior
example/ssd/train/metric.py
def reset(self): """ override reset behavior """ if getattr(self, 'num', None) is None: self.num_inst = 0 self.sum_metric = 0.0 else: self.num_inst = [0] * self.num self.sum_metric = [0.0] * self.num
def reset(self): """ override reset behavior """ if getattr(self, 'num', None) is None: self.num_inst = 0 self.sum_metric = 0.0 else: self.num_inst = [0] * self.num self.sum_metric = [0.0] * self.num
[ "override", "reset", "behavior" ]
apache/incubator-mxnet
python
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/ssd/train/metric.py#L31-L40
[ "def", "reset", "(", "self", ")", ":", "if", "getattr", "(", "self", ",", "'num'", ",", "None", ")", "is", "None", ":", "self", ".", "num_inst", "=", "0", "self", ".", "sum_metric", "=", "0.0", "else", ":", "self", ".", "num_inst", "=", "[", "0",...
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
train
MultiBoxMetric.reset_local
override reset behavior
example/ssd/train/metric.py
def reset_local(self): """ override reset behavior """ if getattr(self, 'num', None) is None: self.num_inst = 0 self.sum_metric = 0.0 else: self.num_inst = [0] * self.num self.sum_metric = [0.0] * self.num
def reset_local(self): """ override reset behavior """ if getattr(self, 'num', None) is None: self.num_inst = 0 self.sum_metric = 0.0 else: self.num_inst = [0] * self.num self.sum_metric = [0.0] * self.num
[ "override", "reset", "behavior" ]
apache/incubator-mxnet
python
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/ssd/train/metric.py#L42-L51
[ "def", "reset_local", "(", "self", ")", ":", "if", "getattr", "(", "self", ",", "'num'", ",", "None", ")", "is", "None", ":", "self", ".", "num_inst", "=", "0", "self", ".", "sum_metric", "=", "0.0", "else", ":", "self", ".", "num_inst", "=", "[", ...
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
train
MultiBoxMetric.update
Implementation of updating metrics
example/ssd/train/metric.py
def update(self, labels, preds): """ Implementation of updating metrics """ # get generated multi label from network cls_prob = preds[0].asnumpy() loc_loss = preds[1].asnumpy() cls_label = preds[2].asnumpy() valid_count = np.sum(cls_label >= 0) # o...
def update(self, labels, preds): """ Implementation of updating metrics """ # get generated multi label from network cls_prob = preds[0].asnumpy() loc_loss = preds[1].asnumpy() cls_label = preds[2].asnumpy() valid_count = np.sum(cls_label >= 0) # o...
[ "Implementation", "of", "updating", "metrics" ]
apache/incubator-mxnet
python
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/ssd/train/metric.py#L53-L72
[ "def", "update", "(", "self", ",", "labels", ",", "preds", ")", ":", "# get generated multi label from network", "cls_prob", "=", "preds", "[", "0", "]", ".", "asnumpy", "(", ")", "loc_loss", "=", "preds", "[", "1", "]", ".", "asnumpy", "(", ")", "cls_la...
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
train
MultiBoxMetric.get
Get the current evaluation result. Override the default behavior Returns ------- name : str Name of the metric. value : float Value of the evaluation.
example/ssd/train/metric.py
def get(self): """Get the current evaluation result. Override the default behavior Returns ------- name : str Name of the metric. value : float Value of the evaluation. """ if self.num is None: if self.num_inst == 0: ...
def get(self): """Get the current evaluation result. Override the default behavior Returns ------- name : str Name of the metric. value : float Value of the evaluation. """ if self.num is None: if self.num_inst == 0: ...
[ "Get", "the", "current", "evaluation", "result", ".", "Override", "the", "default", "behavior" ]
apache/incubator-mxnet
python
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/ssd/train/metric.py#L74-L94
[ "def", "get", "(", "self", ")", ":", "if", "self", ".", "num", "is", "None", ":", "if", "self", ".", "num_inst", "==", "0", ":", "return", "(", "self", ".", "name", ",", "float", "(", "'nan'", ")", ")", "else", ":", "return", "(", "self", ".", ...
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
train
dqn_sym_nips
Structure of the Deep Q Network in the NIPS 2013 workshop paper: Playing Atari with Deep Reinforcement Learning (https://www.cs.toronto.edu/~vmnih/docs/dqn.pdf) Parameters ---------- action_num : int data : mxnet.sym.Symbol, optional name : str, optional
example/reinforcement-learning/dqn/operators.py
def dqn_sym_nips(action_num, data=None, name='dqn'): """Structure of the Deep Q Network in the NIPS 2013 workshop paper: Playing Atari with Deep Reinforcement Learning (https://www.cs.toronto.edu/~vmnih/docs/dqn.pdf) Parameters ---------- action_num : int data : mxnet.sym.Symbol, optional n...
def dqn_sym_nips(action_num, data=None, name='dqn'): """Structure of the Deep Q Network in the NIPS 2013 workshop paper: Playing Atari with Deep Reinforcement Learning (https://www.cs.toronto.edu/~vmnih/docs/dqn.pdf) Parameters ---------- action_num : int data : mxnet.sym.Symbol, optional n...
[ "Structure", "of", "the", "Deep", "Q", "Network", "in", "the", "NIPS", "2013", "workshop", "paper", ":", "Playing", "Atari", "with", "Deep", "Reinforcement", "Learning", "(", "https", ":", "//", "www", ".", "cs", ".", "toronto", ".", "edu", "/", "~vmnih"...
apache/incubator-mxnet
python
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/reinforcement-learning/dqn/operators.py#L98-L121
[ "def", "dqn_sym_nips", "(", "action_num", ",", "data", "=", "None", ",", "name", "=", "'dqn'", ")", ":", "if", "data", "is", "None", ":", "net", "=", "mx", ".", "symbol", ".", "Variable", "(", "'data'", ")", "else", ":", "net", "=", "data", "net", ...
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
train
_monitor_callback_wrapper
A wrapper for the user-defined handle.
python/mxnet/executor.py
def _monitor_callback_wrapper(callback): """A wrapper for the user-defined handle.""" def callback_handle(name, array, _): """ ctypes function """ callback(name, array) return callback_handle
def _monitor_callback_wrapper(callback): """A wrapper for the user-defined handle.""" def callback_handle(name, array, _): """ ctypes function """ callback(name, array) return callback_handle
[ "A", "wrapper", "for", "the", "user", "-", "defined", "handle", "." ]
apache/incubator-mxnet
python
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/executor.py#L38-L43
[ "def", "_monitor_callback_wrapper", "(", "callback", ")", ":", "def", "callback_handle", "(", "name", ",", "array", ",", "_", ")", ":", "\"\"\" ctypes function \"\"\"", "callback", "(", "name", ",", "array", ")", "return", "callback_handle" ]
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
train
Executor._get_dict
Get the dictionary given name and ndarray pairs.
python/mxnet/executor.py
def _get_dict(names, ndarrays): """Get the dictionary given name and ndarray pairs.""" nset = set() for nm in names: if nm in nset: raise ValueError('Duplicate names detected, %s' % str(names)) nset.add(nm) return dict(zip(names, ndarrays))
def _get_dict(names, ndarrays): """Get the dictionary given name and ndarray pairs.""" nset = set() for nm in names: if nm in nset: raise ValueError('Duplicate names detected, %s' % str(names)) nset.add(nm) return dict(zip(names, ndarrays))
[ "Get", "the", "dictionary", "given", "name", "and", "ndarray", "pairs", "." ]
apache/incubator-mxnet
python
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/executor.py#L90-L97
[ "def", "_get_dict", "(", "names", ",", "ndarrays", ")", ":", "nset", "=", "set", "(", ")", "for", "nm", "in", "names", ":", "if", "nm", "in", "nset", ":", "raise", "ValueError", "(", "'Duplicate names detected, %s'", "%", "str", "(", "names", ")", ")",...
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
train
Executor._get_outputs
List all the output NDArray. Returns ------- A list of ndarray bound to the heads of executor.
python/mxnet/executor.py
def _get_outputs(self): """List all the output NDArray. Returns ------- A list of ndarray bound to the heads of executor. """ out_size = mx_uint() handles = ctypes.POINTER(NDArrayHandle)() check_call(_LIB.MXExecutorOutputs(self.handle, ...
def _get_outputs(self): """List all the output NDArray. Returns ------- A list of ndarray bound to the heads of executor. """ out_size = mx_uint() handles = ctypes.POINTER(NDArrayHandle)() check_call(_LIB.MXExecutorOutputs(self.handle, ...
[ "List", "all", "the", "output", "NDArray", "." ]
apache/incubator-mxnet
python
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/executor.py#L99-L112
[ "def", "_get_outputs", "(", "self", ")", ":", "out_size", "=", "mx_uint", "(", ")", "handles", "=", "ctypes", ".", "POINTER", "(", "NDArrayHandle", ")", "(", ")", "check_call", "(", "_LIB", ".", "MXExecutorOutputs", "(", "self", ".", "handle", ",", "ctyp...
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
train
Executor.forward
Calculate the outputs specified by the bound symbol. Parameters ---------- is_train: bool, optional Whether this forward is for evaluation purpose. If True, a backward call is expected to follow. **kwargs Additional specification of input arguments. ...
python/mxnet/executor.py
def forward(self, is_train=False, **kwargs): """Calculate the outputs specified by the bound symbol. Parameters ---------- is_train: bool, optional Whether this forward is for evaluation purpose. If True, a backward call is expected to follow. **kwargs ...
def forward(self, is_train=False, **kwargs): """Calculate the outputs specified by the bound symbol. Parameters ---------- is_train: bool, optional Whether this forward is for evaluation purpose. If True, a backward call is expected to follow. **kwargs ...
[ "Calculate", "the", "outputs", "specified", "by", "the", "bound", "symbol", "." ]
apache/incubator-mxnet
python
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/executor.py#L114-L153
[ "def", "forward", "(", "self", ",", "is_train", "=", "False", ",", "*", "*", "kwargs", ")", ":", "if", "len", "(", "kwargs", ")", "!=", "0", ":", "arg_dict", "=", "self", ".", "arg_dict", "for", "name", ",", "array", "in", "kwargs", ".", "items", ...
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
train
Executor.backward
Do backward pass to get the gradient of arguments. Parameters ---------- out_grads : NDArray or list of NDArray or dict of str to NDArray, optional Gradient on the outputs to be propagated back. This parameter is only needed when bind is called on outputs tha...
python/mxnet/executor.py
def backward(self, out_grads=None, is_train=True): """Do backward pass to get the gradient of arguments. Parameters ---------- out_grads : NDArray or list of NDArray or dict of str to NDArray, optional Gradient on the outputs to be propagated back. This parameter...
def backward(self, out_grads=None, is_train=True): """Do backward pass to get the gradient of arguments. Parameters ---------- out_grads : NDArray or list of NDArray or dict of str to NDArray, optional Gradient on the outputs to be propagated back. This parameter...
[ "Do", "backward", "pass", "to", "get", "the", "gradient", "of", "arguments", "." ]
apache/incubator-mxnet
python
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/executor.py#L155-L235
[ "def", "backward", "(", "self", ",", "out_grads", "=", "None", ",", "is_train", "=", "True", ")", ":", "if", "out_grads", "is", "None", ":", "out_grads", "=", "[", "]", "elif", "isinstance", "(", "out_grads", ",", "NDArray", ")", ":", "out_grads", "=",...
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
train
Executor.set_monitor_callback
Install callback for monitor. Parameters ---------- callback : function Takes a string and an NDArrayHandle. monitor_all : bool, default False If true, monitor both input and output, otherwise monitor output only. Examples -------- >>> de...
python/mxnet/executor.py
def set_monitor_callback(self, callback, monitor_all=False): """Install callback for monitor. Parameters ---------- callback : function Takes a string and an NDArrayHandle. monitor_all : bool, default False If true, monitor both input and output, otherwis...
def set_monitor_callback(self, callback, monitor_all=False): """Install callback for monitor. Parameters ---------- callback : function Takes a string and an NDArrayHandle. monitor_all : bool, default False If true, monitor both input and output, otherwis...
[ "Install", "callback", "for", "monitor", "." ]
apache/incubator-mxnet
python
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/executor.py#L237-L260
[ "def", "set_monitor_callback", "(", "self", ",", "callback", ",", "monitor_all", "=", "False", ")", ":", "cb_type", "=", "ctypes", ".", "CFUNCTYPE", "(", "None", ",", "ctypes", ".", "c_char_p", ",", "NDArrayHandle", ",", "ctypes", ".", "c_void_p", ")", "se...
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
train
Executor.arg_dict
Get dictionary representation of argument arrrays. Returns ------- arg_dict : dict of str to NDArray The dictionary that maps the names of arguments to NDArrays. Raises ------ ValueError : if there are duplicated names in the arguments.
python/mxnet/executor.py
def arg_dict(self): """Get dictionary representation of argument arrrays. Returns ------- arg_dict : dict of str to NDArray The dictionary that maps the names of arguments to NDArrays. Raises ------ ValueError : if there are duplicated names in the a...
def arg_dict(self): """Get dictionary representation of argument arrrays. Returns ------- arg_dict : dict of str to NDArray The dictionary that maps the names of arguments to NDArrays. Raises ------ ValueError : if there are duplicated names in the a...
[ "Get", "dictionary", "representation", "of", "argument", "arrrays", "." ]
apache/incubator-mxnet
python
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/executor.py#L263-L278
[ "def", "arg_dict", "(", "self", ")", ":", "if", "self", ".", "_arg_dict", "is", "None", ":", "self", ".", "_arg_dict", "=", "Executor", ".", "_get_dict", "(", "self", ".", "_symbol", ".", "list_arguments", "(", ")", ",", "self", ".", "arg_arrays", ")",...
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
train
Executor.grad_dict
Get dictionary representation of gradient arrays. Returns ------- grad_dict : dict of str to NDArray The dictionary that maps name of arguments to gradient arrays.
python/mxnet/executor.py
def grad_dict(self): """Get dictionary representation of gradient arrays. Returns ------- grad_dict : dict of str to NDArray The dictionary that maps name of arguments to gradient arrays. """ if self._grad_dict is None: self._grad_dict = Executor....
def grad_dict(self): """Get dictionary representation of gradient arrays. Returns ------- grad_dict : dict of str to NDArray The dictionary that maps name of arguments to gradient arrays. """ if self._grad_dict is None: self._grad_dict = Executor....
[ "Get", "dictionary", "representation", "of", "gradient", "arrays", "." ]
apache/incubator-mxnet
python
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/executor.py#L281-L292
[ "def", "grad_dict", "(", "self", ")", ":", "if", "self", ".", "_grad_dict", "is", "None", ":", "self", ".", "_grad_dict", "=", "Executor", ".", "_get_dict", "(", "self", ".", "_symbol", ".", "list_arguments", "(", ")", ",", "self", ".", "grad_arrays", ...
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
train
Executor.aux_dict
Get dictionary representation of auxiliary states arrays. Returns ------- aux_dict : dict of str to NDArray The dictionary that maps name of auxiliary states to NDArrays. Raises ------ ValueError : if there are duplicated names in the auxiliary states.
python/mxnet/executor.py
def aux_dict(self): """Get dictionary representation of auxiliary states arrays. Returns ------- aux_dict : dict of str to NDArray The dictionary that maps name of auxiliary states to NDArrays. Raises ------ ValueError : if there are duplicated names...
def aux_dict(self): """Get dictionary representation of auxiliary states arrays. Returns ------- aux_dict : dict of str to NDArray The dictionary that maps name of auxiliary states to NDArrays. Raises ------ ValueError : if there are duplicated names...
[ "Get", "dictionary", "representation", "of", "auxiliary", "states", "arrays", "." ]
apache/incubator-mxnet
python
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/executor.py#L295-L310
[ "def", "aux_dict", "(", "self", ")", ":", "if", "self", ".", "_aux_dict", "is", "None", ":", "self", ".", "_aux_dict", "=", "Executor", ".", "_get_dict", "(", "self", ".", "_symbol", ".", "list_auxiliary_states", "(", ")", ",", "self", ".", "aux_arrays",...
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
train
Executor.output_dict
Get dictionary representation of output arrays. Returns ------- output_dict : dict of str to NDArray The dictionary that maps name of output names to NDArrays. Raises ------ ValueError : if there are duplicated names in the outputs.
python/mxnet/executor.py
def output_dict(self): """Get dictionary representation of output arrays. Returns ------- output_dict : dict of str to NDArray The dictionary that maps name of output names to NDArrays. Raises ------ ValueError : if there are duplicated names in the ...
def output_dict(self): """Get dictionary representation of output arrays. Returns ------- output_dict : dict of str to NDArray The dictionary that maps name of output names to NDArrays. Raises ------ ValueError : if there are duplicated names in the ...
[ "Get", "dictionary", "representation", "of", "output", "arrays", "." ]
apache/incubator-mxnet
python
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/executor.py#L313-L328
[ "def", "output_dict", "(", "self", ")", ":", "if", "self", ".", "_output_dict", "is", "None", ":", "self", ".", "_output_dict", "=", "Executor", ".", "_get_dict", "(", "self", ".", "_symbol", ".", "list_outputs", "(", ")", ",", "self", ".", "outputs", ...
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
train
Executor.copy_params_from
Copy parameters from arg_params, aux_params into executor's internal array. Parameters ---------- arg_params : dict of str to NDArray Parameters, dict of name to NDArray of arguments. aux_params : dict of str to NDArray, optional Parameters, dict of name to NDAr...
python/mxnet/executor.py
def copy_params_from(self, arg_params, aux_params=None, allow_extra_params=False): """Copy parameters from arg_params, aux_params into executor's internal array. Parameters ---------- arg_params : dict of str to NDArray Parameters, dict of name to NDArray of arguments. ...
def copy_params_from(self, arg_params, aux_params=None, allow_extra_params=False): """Copy parameters from arg_params, aux_params into executor's internal array. Parameters ---------- arg_params : dict of str to NDArray Parameters, dict of name to NDArray of arguments. ...
[ "Copy", "parameters", "from", "arg_params", "aux_params", "into", "executor", "s", "internal", "array", "." ]
apache/incubator-mxnet
python
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/executor.py#L330-L373
[ "def", "copy_params_from", "(", "self", ",", "arg_params", ",", "aux_params", "=", "None", ",", "allow_extra_params", "=", "False", ")", ":", "for", "name", ",", "array", "in", "arg_params", ".", "items", "(", ")", ":", "if", "name", "in", "self", ".", ...
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
train
Executor.reshape
Return a new executor with the same symbol and shared memory, but different input/output shapes. For runtime reshaping, variable length sequences, etc. The returned executor shares state with the current one, and cannot be used in parallel with it. Parameters ---------- ...
python/mxnet/executor.py
def reshape(self, partial_shaping=False, allow_up_sizing=False, **kwargs): """Return a new executor with the same symbol and shared memory, but different input/output shapes. For runtime reshaping, variable length sequences, etc. The returned executor shares state with the current one, ...
def reshape(self, partial_shaping=False, allow_up_sizing=False, **kwargs): """Return a new executor with the same symbol and shared memory, but different input/output shapes. For runtime reshaping, variable length sequences, etc. The returned executor shares state with the current one, ...
[ "Return", "a", "new", "executor", "with", "the", "same", "symbol", "and", "shared", "memory", "but", "different", "input", "/", "output", "shapes", ".", "For", "runtime", "reshaping", "variable", "length", "sequences", "etc", ".", "The", "returned", "executor"...
apache/incubator-mxnet
python
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/executor.py#L375-L472
[ "def", "reshape", "(", "self", ",", "partial_shaping", "=", "False", ",", "allow_up_sizing", "=", "False", ",", "*", "*", "kwargs", ")", ":", "# pylint: disable=too-many-branches", "provided_arg_shape_data", "=", "[", "]", "# shape data", "# argument shape index in sd...
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
train
Executor.debug_str
Get a debug string about internal execution plan. Returns ------- debug_str : string Debug string of the executor. Examples -------- >>> a = mx.sym.Variable('a') >>> b = mx.sym.sin(a) >>> c = 2 * a + b >>> texec = c.bind(mx.cpu(), {'a...
python/mxnet/executor.py
def debug_str(self): """Get a debug string about internal execution plan. Returns ------- debug_str : string Debug string of the executor. Examples -------- >>> a = mx.sym.Variable('a') >>> b = mx.sym.sin(a) >>> c = 2 * a + b ...
def debug_str(self): """Get a debug string about internal execution plan. Returns ------- debug_str : string Debug string of the executor. Examples -------- >>> a = mx.sym.Variable('a') >>> b = mx.sym.sin(a) >>> c = 2 * a + b ...
[ "Get", "a", "debug", "string", "about", "internal", "execution", "plan", "." ]
apache/incubator-mxnet
python
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/executor.py#L474-L513
[ "def", "debug_str", "(", "self", ")", ":", "debug_str", "=", "ctypes", ".", "c_char_p", "(", ")", "check_call", "(", "_LIB", ".", "MXExecutorPrint", "(", "self", ".", "handle", ",", "ctypes", ".", "byref", "(", "debug_str", ")", ")", ")", "return", "py...
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
train
parse_voc_rec
parse pascal voc record into a dictionary :param filename: xml file path :return: list of dict
example/ssd/evaluate/eval_voc.py
def parse_voc_rec(filename): """ parse pascal voc record into a dictionary :param filename: xml file path :return: list of dict """ import xml.etree.ElementTree as ET tree = ET.parse(filename) objects = [] for obj in tree.findall('object'): obj_dict = dict() obj_dict[...
def parse_voc_rec(filename): """ parse pascal voc record into a dictionary :param filename: xml file path :return: list of dict """ import xml.etree.ElementTree as ET tree = ET.parse(filename) objects = [] for obj in tree.findall('object'): obj_dict = dict() obj_dict[...
[ "parse", "pascal", "voc", "record", "into", "a", "dictionary", ":", "param", "filename", ":", "xml", "file", "path", ":", "return", ":", "list", "of", "dict" ]
apache/incubator-mxnet
python
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/ssd/evaluate/eval_voc.py#L30-L49
[ "def", "parse_voc_rec", "(", "filename", ")", ":", "import", "xml", ".", "etree", ".", "ElementTree", "as", "ET", "tree", "=", "ET", ".", "parse", "(", "filename", ")", "objects", "=", "[", "]", "for", "obj", "in", "tree", ".", "findall", "(", "'obje...
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
train
voc_eval
pascal voc evaluation :param detpath: detection results detpath.format(classname) :param annopath: annotations annopath.format(classname) :param imageset_file: text file containing list of images :param classname: category name :param cache_dir: caching annotations :param ovthresh: overlap thres...
example/ssd/evaluate/eval_voc.py
def voc_eval(detpath, annopath, imageset_file, classname, cache_dir, ovthresh=0.5, use_07_metric=False): """ pascal voc evaluation :param detpath: detection results detpath.format(classname) :param annopath: annotations annopath.format(classname) :param imageset_file: text file containing list of im...
def voc_eval(detpath, annopath, imageset_file, classname, cache_dir, ovthresh=0.5, use_07_metric=False): """ pascal voc evaluation :param detpath: detection results detpath.format(classname) :param annopath: annotations annopath.format(classname) :param imageset_file: text file containing list of im...
[ "pascal", "voc", "evaluation", ":", "param", "detpath", ":", "detection", "results", "detpath", ".", "format", "(", "classname", ")", ":", "param", "annopath", ":", "annotations", "annopath", ".", "format", "(", "classname", ")", ":", "param", "imageset_file",...
apache/incubator-mxnet
python
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/ssd/evaluate/eval_voc.py#L86-L196
[ "def", "voc_eval", "(", "detpath", ",", "annopath", ",", "imageset_file", ",", "classname", ",", "cache_dir", ",", "ovthresh", "=", "0.5", ",", "use_07_metric", "=", "False", ")", ":", "if", "not", "os", ".", "path", ".", "isdir", "(", "cache_dir", ")", ...
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
train
MXNetGraph.register
Register operators
python/mxnet/contrib/onnx/mx2onnx/export_onnx.py
def register(op_name): """Register operators""" def wrapper(func): """Helper function to map functions""" try: import onnx as _ MXNetGraph.registry_[op_name] = func except ImportError: pass return func ...
def register(op_name): """Register operators""" def wrapper(func): """Helper function to map functions""" try: import onnx as _ MXNetGraph.registry_[op_name] = func except ImportError: pass return func ...
[ "Register", "operators" ]
apache/incubator-mxnet
python
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/contrib/onnx/mx2onnx/export_onnx.py#L72-L83
[ "def", "register", "(", "op_name", ")", ":", "def", "wrapper", "(", "func", ")", ":", "\"\"\"Helper function to map functions\"\"\"", "try", ":", "import", "onnx", "as", "_", "MXNetGraph", ".", "registry_", "[", "op_name", "]", "=", "func", "except", "ImportEr...
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
train
MXNetGraph.convert_layer
Convert MXNet layer to ONNX
python/mxnet/contrib/onnx/mx2onnx/export_onnx.py
def convert_layer(node, **kwargs): """Convert MXNet layer to ONNX""" op = str(node["op"]) if op not in MXNetGraph.registry_: raise AttributeError("No conversion function registered for op type %s yet." % op) convert_func = MXNetGraph.registry_[op] return convert_func(...
def convert_layer(node, **kwargs): """Convert MXNet layer to ONNX""" op = str(node["op"]) if op not in MXNetGraph.registry_: raise AttributeError("No conversion function registered for op type %s yet." % op) convert_func = MXNetGraph.registry_[op] return convert_func(...
[ "Convert", "MXNet", "layer", "to", "ONNX" ]
apache/incubator-mxnet
python
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/contrib/onnx/mx2onnx/export_onnx.py#L86-L92
[ "def", "convert_layer", "(", "node", ",", "*", "*", "kwargs", ")", ":", "op", "=", "str", "(", "node", "[", "\"op\"", "]", ")", "if", "op", "not", "in", "MXNetGraph", ".", "registry_", ":", "raise", "AttributeError", "(", "\"No conversion function register...
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
train
MXNetGraph.split_params
Helper function to split params dictionary into args and aux params Parameters ---------- sym : :class:`~mxnet.symbol.Symbol` MXNet symbol object params : dict of ``str`` to :class:`~mxnet.ndarray.NDArray` Dict of converted parameters stored in ``mxnet.ndarray.ND...
python/mxnet/contrib/onnx/mx2onnx/export_onnx.py
def split_params(sym, params): """Helper function to split params dictionary into args and aux params Parameters ---------- sym : :class:`~mxnet.symbol.Symbol` MXNet symbol object params : dict of ``str`` to :class:`~mxnet.ndarray.NDArray` Dict of convert...
def split_params(sym, params): """Helper function to split params dictionary into args and aux params Parameters ---------- sym : :class:`~mxnet.symbol.Symbol` MXNet symbol object params : dict of ``str`` to :class:`~mxnet.ndarray.NDArray` Dict of convert...
[ "Helper", "function", "to", "split", "params", "dictionary", "into", "args", "and", "aux", "params" ]
apache/incubator-mxnet
python
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/contrib/onnx/mx2onnx/export_onnx.py#L95-L120
[ "def", "split_params", "(", "sym", ",", "params", ")", ":", "arg_params", "=", "{", "}", "aux_params", "=", "{", "}", "for", "args", "in", "sym", ".", "list_arguments", "(", ")", ":", "if", "args", "in", "params", ":", "arg_params", ".", "update", "(...
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
train
MXNetGraph.get_outputs
Infer output shapes and return dictionary of output name to shape :param :class:`~mxnet.symbol.Symbol` sym: symbol to perform infer shape on :param dic of (str, nd.NDArray) params: :param list of tuple(int, ...) in_shape: list of all input shapes :param in_label: name of label typicall...
python/mxnet/contrib/onnx/mx2onnx/export_onnx.py
def get_outputs(sym, params, in_shape, in_label): """ Infer output shapes and return dictionary of output name to shape :param :class:`~mxnet.symbol.Symbol` sym: symbol to perform infer shape on :param dic of (str, nd.NDArray) params: :param list of tuple(int, ...) in_shape: list of all...
def get_outputs(sym, params, in_shape, in_label): """ Infer output shapes and return dictionary of output name to shape :param :class:`~mxnet.symbol.Symbol` sym: symbol to perform infer shape on :param dic of (str, nd.NDArray) params: :param list of tuple(int, ...) in_shape: list of all...
[ "Infer", "output", "shapes", "and", "return", "dictionary", "of", "output", "name", "to", "shape" ]
apache/incubator-mxnet
python
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/contrib/onnx/mx2onnx/export_onnx.py#L123-L156
[ "def", "get_outputs", "(", "sym", ",", "params", ",", "in_shape", ",", "in_label", ")", ":", "# remove any input listed in params from sym.list_inputs() and bind them to the input shapes provided", "# by user. Also remove in_label, which is the name of the label symbol that may have been u...
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
train
MXNetGraph.convert_weights_to_numpy
Convert weights to numpy
python/mxnet/contrib/onnx/mx2onnx/export_onnx.py
def convert_weights_to_numpy(weights_dict): """Convert weights to numpy""" return dict([(k.replace("arg:", "").replace("aux:", ""), v.asnumpy()) for k, v in weights_dict.items()])
def convert_weights_to_numpy(weights_dict): """Convert weights to numpy""" return dict([(k.replace("arg:", "").replace("aux:", ""), v.asnumpy()) for k, v in weights_dict.items()])
[ "Convert", "weights", "to", "numpy" ]
apache/incubator-mxnet
python
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/contrib/onnx/mx2onnx/export_onnx.py#L159-L162
[ "def", "convert_weights_to_numpy", "(", "weights_dict", ")", ":", "return", "dict", "(", "[", "(", "k", ".", "replace", "(", "\"arg:\"", ",", "\"\"", ")", ".", "replace", "(", "\"aux:\"", ",", "\"\"", ")", ",", "v", ".", "asnumpy", "(", ")", ")", "fo...
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
train
MXNetGraph.create_onnx_graph_proto
Convert MXNet graph to ONNX graph Parameters ---------- sym : :class:`~mxnet.symbol.Symbol` MXNet symbol object params : dict of ``str`` to :class:`~mxnet.ndarray.NDArray` Dict of converted parameters stored in ``mxnet.ndarray.NDArray`` format in_shape : ...
python/mxnet/contrib/onnx/mx2onnx/export_onnx.py
def create_onnx_graph_proto(self, sym, params, in_shape, in_type, verbose=False): """Convert MXNet graph to ONNX graph Parameters ---------- sym : :class:`~mxnet.symbol.Symbol` MXNet symbol object params : dict of ``str`` to :class:`~mxnet.ndarray.NDArray` ...
def create_onnx_graph_proto(self, sym, params, in_shape, in_type, verbose=False): """Convert MXNet graph to ONNX graph Parameters ---------- sym : :class:`~mxnet.symbol.Symbol` MXNet symbol object params : dict of ``str`` to :class:`~mxnet.ndarray.NDArray` ...
[ "Convert", "MXNet", "graph", "to", "ONNX", "graph" ]
apache/incubator-mxnet
python
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/contrib/onnx/mx2onnx/export_onnx.py#L164-L313
[ "def", "create_onnx_graph_proto", "(", "self", ",", "sym", ",", "params", ",", "in_shape", ",", "in_type", ",", "verbose", "=", "False", ")", ":", "try", ":", "from", "onnx", "import", "(", "checker", ",", "helper", ",", "NodeProto", ",", "ValueInfoProto",...
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
train
get_lr_scheduler
Compute learning rate and refactor scheduler Parameters: --------- learning_rate : float original learning rate lr_refactor_step : comma separated str epochs to change learning rate lr_refactor_ratio : float lr *= ratio at certain steps num_example : int number o...
example/ssd/train/train_net.py
def get_lr_scheduler(learning_rate, lr_refactor_step, lr_refactor_ratio, num_example, batch_size, begin_epoch): """ Compute learning rate and refactor scheduler Parameters: --------- learning_rate : float original learning rate lr_refactor_step : comma separated str...
def get_lr_scheduler(learning_rate, lr_refactor_step, lr_refactor_ratio, num_example, batch_size, begin_epoch): """ Compute learning rate and refactor scheduler Parameters: --------- learning_rate : float original learning rate lr_refactor_step : comma separated str...
[ "Compute", "learning", "rate", "and", "refactor", "scheduler" ]
apache/incubator-mxnet
python
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/ssd/train/train_net.py#L48-L88
[ "def", "get_lr_scheduler", "(", "learning_rate", ",", "lr_refactor_step", ",", "lr_refactor_ratio", ",", "num_example", ",", "batch_size", ",", "begin_epoch", ")", ":", "assert", "lr_refactor_ratio", ">", "0", "iter_refactor", "=", "[", "int", "(", "r", ")", "fo...
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
train
train_net
Wrapper for training phase. Parameters: ---------- net : str symbol name for the network structure train_path : str record file path for training num_classes : int number of object classes, not including background batch_size : int training batch-size data_sh...
example/ssd/train/train_net.py
def train_net(net, train_path, num_classes, batch_size, data_shape, mean_pixels, resume, finetune, pretrained, epoch, prefix, ctx, begin_epoch, end_epoch, frequent, learning_rate, momentum, weight_decay, lr_refactor_step, lr_refactor_ratio, freeze_layer_pattern=''...
def train_net(net, train_path, num_classes, batch_size, data_shape, mean_pixels, resume, finetune, pretrained, epoch, prefix, ctx, begin_epoch, end_epoch, frequent, learning_rate, momentum, weight_decay, lr_refactor_step, lr_refactor_ratio, freeze_layer_pattern=''...
[ "Wrapper", "for", "training", "phase", "." ]
apache/incubator-mxnet
python
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/ssd/train/train_net.py#L90-L279
[ "def", "train_net", "(", "net", ",", "train_path", ",", "num_classes", ",", "batch_size", ",", "data_shape", ",", "mean_pixels", ",", "resume", ",", "finetune", ",", "pretrained", ",", "epoch", ",", "prefix", ",", "ctx", ",", "begin_epoch", ",", "end_epoch",...
1af29e9c060a4c7d60eeaacba32afdb9a7775ba7
train
imagenet50
This is a set of 50 images representative of ImageNet images. This dataset was collected by randomly finding a working ImageNet link and then pasting the original ImageNet image into Google image search restricted to images licensed for reuse. A similar image (now with rights to reuse) was downloaded as a ...
shap/datasets.py
def imagenet50(display=False, resolution=224): """ This is a set of 50 images representative of ImageNet images. This dataset was collected by randomly finding a working ImageNet link and then pasting the original ImageNet image into Google image search restricted to images licensed for reuse. A simila...
def imagenet50(display=False, resolution=224): """ This is a set of 50 images representative of ImageNet images. This dataset was collected by randomly finding a working ImageNet link and then pasting the original ImageNet image into Google image search restricted to images licensed for reuse. A simila...
[ "This", "is", "a", "set", "of", "50", "images", "representative", "of", "ImageNet", "images", "." ]
slundberg/shap
python
https://github.com/slundberg/shap/blob/b280cb81d498b9d98565cad8dd16fc88ae52649f/shap/datasets.py#L13-L28
[ "def", "imagenet50", "(", "display", "=", "False", ",", "resolution", "=", "224", ")", ":", "prefix", "=", "github_data_url", "+", "\"imagenet50_\"", "X", "=", "np", ".", "load", "(", "cache", "(", "prefix", "+", "\"%sx%s.npy\"", "%", "(", "resolution", ...
b280cb81d498b9d98565cad8dd16fc88ae52649f
train
boston
Return the boston housing data in a nice package.
shap/datasets.py
def boston(display=False): """ Return the boston housing data in a nice package. """ d = sklearn.datasets.load_boston() df = pd.DataFrame(data=d.data, columns=d.feature_names) # pylint: disable=E1101 return df, d.target
def boston(display=False): """ Return the boston housing data in a nice package. """ d = sklearn.datasets.load_boston() df = pd.DataFrame(data=d.data, columns=d.feature_names) # pylint: disable=E1101 return df, d.target
[ "Return", "the", "boston", "housing", "data", "in", "a", "nice", "package", "." ]
slundberg/shap
python
https://github.com/slundberg/shap/blob/b280cb81d498b9d98565cad8dd16fc88ae52649f/shap/datasets.py#L30-L35
[ "def", "boston", "(", "display", "=", "False", ")", ":", "d", "=", "sklearn", ".", "datasets", ".", "load_boston", "(", ")", "df", "=", "pd", ".", "DataFrame", "(", "data", "=", "d", ".", "data", ",", "columns", "=", "d", ".", "feature_names", ")",...
b280cb81d498b9d98565cad8dd16fc88ae52649f
train
imdb
Return the clssic IMDB sentiment analysis training data in a nice package. Full data is at: http://ai.stanford.edu/~amaas/data/sentiment/aclImdb_v1.tar.gz Paper to cite when using the data is: http://www.aclweb.org/anthology/P11-1015
shap/datasets.py
def imdb(display=False): """ Return the clssic IMDB sentiment analysis training data in a nice package. Full data is at: http://ai.stanford.edu/~amaas/data/sentiment/aclImdb_v1.tar.gz Paper to cite when using the data is: http://www.aclweb.org/anthology/P11-1015 """ with open(cache(github_data_url...
def imdb(display=False): """ Return the clssic IMDB sentiment analysis training data in a nice package. Full data is at: http://ai.stanford.edu/~amaas/data/sentiment/aclImdb_v1.tar.gz Paper to cite when using the data is: http://www.aclweb.org/anthology/P11-1015 """ with open(cache(github_data_url...
[ "Return", "the", "clssic", "IMDB", "sentiment", "analysis", "training", "data", "in", "a", "nice", "package", "." ]
slundberg/shap
python
https://github.com/slundberg/shap/blob/b280cb81d498b9d98565cad8dd16fc88ae52649f/shap/datasets.py#L37-L48
[ "def", "imdb", "(", "display", "=", "False", ")", ":", "with", "open", "(", "cache", "(", "github_data_url", "+", "\"imdb_train.txt\"", ")", ")", "as", "f", ":", "data", "=", "f", ".", "readlines", "(", ")", "y", "=", "np", ".", "ones", "(", "25000...
b280cb81d498b9d98565cad8dd16fc88ae52649f
train
communitiesandcrime
Predict total number of non-violent crimes per 100K popuation. This dataset is from the classic UCI Machine Learning repository: https://archive.ics.uci.edu/ml/datasets/Communities+and+Crime+Unnormalized
shap/datasets.py
def communitiesandcrime(display=False): """ Predict total number of non-violent crimes per 100K popuation. This dataset is from the classic UCI Machine Learning repository: https://archive.ics.uci.edu/ml/datasets/Communities+and+Crime+Unnormalized """ raw_data = pd.read_csv( cache(github_d...
def communitiesandcrime(display=False): """ Predict total number of non-violent crimes per 100K popuation. This dataset is from the classic UCI Machine Learning repository: https://archive.ics.uci.edu/ml/datasets/Communities+and+Crime+Unnormalized """ raw_data = pd.read_csv( cache(github_d...
[ "Predict", "total", "number", "of", "non", "-", "violent", "crimes", "per", "100K", "popuation", "." ]
slundberg/shap
python
https://github.com/slundberg/shap/blob/b280cb81d498b9d98565cad8dd16fc88ae52649f/shap/datasets.py#L50-L71
[ "def", "communitiesandcrime", "(", "display", "=", "False", ")", ":", "raw_data", "=", "pd", ".", "read_csv", "(", "cache", "(", "github_data_url", "+", "\"CommViolPredUnnormalizedData.txt\"", ")", ",", "na_values", "=", "\"?\"", ")", "# find the indices where the t...
b280cb81d498b9d98565cad8dd16fc88ae52649f
train
diabetes
Return the diabetes data in a nice package.
shap/datasets.py
def diabetes(display=False): """ Return the diabetes data in a nice package. """ d = sklearn.datasets.load_diabetes() df = pd.DataFrame(data=d.data, columns=d.feature_names) # pylint: disable=E1101 return df, d.target
def diabetes(display=False): """ Return the diabetes data in a nice package. """ d = sklearn.datasets.load_diabetes() df = pd.DataFrame(data=d.data, columns=d.feature_names) # pylint: disable=E1101 return df, d.target
[ "Return", "the", "diabetes", "data", "in", "a", "nice", "package", "." ]
slundberg/shap
python
https://github.com/slundberg/shap/blob/b280cb81d498b9d98565cad8dd16fc88ae52649f/shap/datasets.py#L73-L78
[ "def", "diabetes", "(", "display", "=", "False", ")", ":", "d", "=", "sklearn", ".", "datasets", ".", "load_diabetes", "(", ")", "df", "=", "pd", ".", "DataFrame", "(", "data", "=", "d", ".", "data", ",", "columns", "=", "d", ".", "feature_names", ...
b280cb81d498b9d98565cad8dd16fc88ae52649f
train
iris
Return the classic iris data in a nice package.
shap/datasets.py
def iris(display=False): """ Return the classic iris data in a nice package. """ d = sklearn.datasets.load_iris() df = pd.DataFrame(data=d.data, columns=d.feature_names) # pylint: disable=E1101 if display: return df, [d.target_names[v] for v in d.target] # pylint: disable=E1101 else: ...
def iris(display=False): """ Return the classic iris data in a nice package. """ d = sklearn.datasets.load_iris() df = pd.DataFrame(data=d.data, columns=d.feature_names) # pylint: disable=E1101 if display: return df, [d.target_names[v] for v in d.target] # pylint: disable=E1101 else: ...
[ "Return", "the", "classic", "iris", "data", "in", "a", "nice", "package", "." ]
slundberg/shap
python
https://github.com/slundberg/shap/blob/b280cb81d498b9d98565cad8dd16fc88ae52649f/shap/datasets.py#L81-L89
[ "def", "iris", "(", "display", "=", "False", ")", ":", "d", "=", "sklearn", ".", "datasets", ".", "load_iris", "(", ")", "df", "=", "pd", ".", "DataFrame", "(", "data", "=", "d", ".", "data", ",", "columns", "=", "d", ".", "feature_names", ")", "...
b280cb81d498b9d98565cad8dd16fc88ae52649f
train
adult
Return the Adult census data in a nice package.
shap/datasets.py
def adult(display=False): """ Return the Adult census data in a nice package. """ dtypes = [ ("Age", "float32"), ("Workclass", "category"), ("fnlwgt", "float32"), ("Education", "category"), ("Education-Num", "float32"), ("Marital Status", "category"), ("Occupation", "category"), ("Relati...
def adult(display=False): """ Return the Adult census data in a nice package. """ dtypes = [ ("Age", "float32"), ("Workclass", "category"), ("fnlwgt", "float32"), ("Education", "category"), ("Education-Num", "float32"), ("Marital Status", "category"), ("Occupation", "category"), ("Relati...
[ "Return", "the", "Adult", "census", "data", "in", "a", "nice", "package", "." ]
slundberg/shap
python
https://github.com/slundberg/shap/blob/b280cb81d498b9d98565cad8dd16fc88ae52649f/shap/datasets.py#L92-L128
[ "def", "adult", "(", "display", "=", "False", ")", ":", "dtypes", "=", "[", "(", "\"Age\"", ",", "\"float32\"", ")", ",", "(", "\"Workclass\"", ",", "\"category\"", ")", ",", "(", "\"fnlwgt\"", ",", "\"float32\"", ")", ",", "(", "\"Education\"", ",", "...
b280cb81d498b9d98565cad8dd16fc88ae52649f
train
nhanesi
A nicely packaged version of NHANES I data with surivival times as labels.
shap/datasets.py
def nhanesi(display=False): """ A nicely packaged version of NHANES I data with surivival times as labels. """ X = pd.read_csv(cache(github_data_url + "NHANESI_subset_X.csv")) y = pd.read_csv(cache(github_data_url + "NHANESI_subset_y.csv"))["y"] if display: X_display = X.copy() X_dis...
def nhanesi(display=False): """ A nicely packaged version of NHANES I data with surivival times as labels. """ X = pd.read_csv(cache(github_data_url + "NHANESI_subset_X.csv")) y = pd.read_csv(cache(github_data_url + "NHANESI_subset_y.csv"))["y"] if display: X_display = X.copy() X_dis...
[ "A", "nicely", "packaged", "version", "of", "NHANES", "I", "data", "with", "surivival", "times", "as", "labels", "." ]
slundberg/shap
python
https://github.com/slundberg/shap/blob/b280cb81d498b9d98565cad8dd16fc88ae52649f/shap/datasets.py#L131-L141
[ "def", "nhanesi", "(", "display", "=", "False", ")", ":", "X", "=", "pd", ".", "read_csv", "(", "cache", "(", "github_data_url", "+", "\"NHANESI_subset_X.csv\"", ")", ")", "y", "=", "pd", ".", "read_csv", "(", "cache", "(", "github_data_url", "+", "\"NHA...
b280cb81d498b9d98565cad8dd16fc88ae52649f
train
cric
A nicely packaged version of CRIC data with progression to ESRD within 4 years as the label.
shap/datasets.py
def cric(display=False): """ A nicely packaged version of CRIC data with progression to ESRD within 4 years as the label. """ X = pd.read_csv(cache(github_data_url + "CRIC_time_4yearESRD_X.csv")) y = np.loadtxt(cache(github_data_url + "CRIC_time_4yearESRD_y.csv")) if display: X_display = X.c...
def cric(display=False): """ A nicely packaged version of CRIC data with progression to ESRD within 4 years as the label. """ X = pd.read_csv(cache(github_data_url + "CRIC_time_4yearESRD_X.csv")) y = np.loadtxt(cache(github_data_url + "CRIC_time_4yearESRD_y.csv")) if display: X_display = X.c...
[ "A", "nicely", "packaged", "version", "of", "CRIC", "data", "with", "progression", "to", "ESRD", "within", "4", "years", "as", "the", "label", "." ]
slundberg/shap
python
https://github.com/slundberg/shap/blob/b280cb81d498b9d98565cad8dd16fc88ae52649f/shap/datasets.py#L143-L152
[ "def", "cric", "(", "display", "=", "False", ")", ":", "X", "=", "pd", ".", "read_csv", "(", "cache", "(", "github_data_url", "+", "\"CRIC_time_4yearESRD_X.csv\"", ")", ")", "y", "=", "np", ".", "loadtxt", "(", "cache", "(", "github_data_url", "+", "\"CR...
b280cb81d498b9d98565cad8dd16fc88ae52649f
train
corrgroups60
Correlated Groups 60 A simulated dataset with tight correlations among distinct groups of features.
shap/datasets.py
def corrgroups60(display=False): """ Correlated Groups 60 A simulated dataset with tight correlations among distinct groups of features. """ # set a constant seed old_seed = np.random.seed() np.random.seed(0) # generate dataset with known correlation N = 1000 M = 60 # set...
def corrgroups60(display=False): """ Correlated Groups 60 A simulated dataset with tight correlations among distinct groups of features. """ # set a constant seed old_seed = np.random.seed() np.random.seed(0) # generate dataset with known correlation N = 1000 M = 60 # set...
[ "Correlated", "Groups", "60", "A", "simulated", "dataset", "with", "tight", "correlations", "among", "distinct", "groups", "of", "features", "." ]
slundberg/shap
python
https://github.com/slundberg/shap/blob/b280cb81d498b9d98565cad8dd16fc88ae52649f/shap/datasets.py#L155-L197
[ "def", "corrgroups60", "(", "display", "=", "False", ")", ":", "# set a constant seed", "old_seed", "=", "np", ".", "random", ".", "seed", "(", ")", "np", ".", "random", ".", "seed", "(", "0", ")", "# generate dataset with known correlation", "N", "=", "1000...
b280cb81d498b9d98565cad8dd16fc88ae52649f
train
independentlinear60
A simulated dataset with tight correlations among distinct groups of features.
shap/datasets.py
def independentlinear60(display=False): """ A simulated dataset with tight correlations among distinct groups of features. """ # set a constant seed old_seed = np.random.seed() np.random.seed(0) # generate dataset with known correlation N = 1000 M = 60 # set one coefficent from ea...
def independentlinear60(display=False): """ A simulated dataset with tight correlations among distinct groups of features. """ # set a constant seed old_seed = np.random.seed() np.random.seed(0) # generate dataset with known correlation N = 1000 M = 60 # set one coefficent from ea...
[ "A", "simulated", "dataset", "with", "tight", "correlations", "among", "distinct", "groups", "of", "features", "." ]
slundberg/shap
python
https://github.com/slundberg/shap/blob/b280cb81d498b9d98565cad8dd16fc88ae52649f/shap/datasets.py#L200-L225
[ "def", "independentlinear60", "(", "display", "=", "False", ")", ":", "# set a constant seed", "old_seed", "=", "np", ".", "random", ".", "seed", "(", ")", "np", ".", "random", ".", "seed", "(", "0", ")", "# generate dataset with known correlation", "N", "=", ...
b280cb81d498b9d98565cad8dd16fc88ae52649f
train
rank
Ranking datasets from lightgbm repository.
shap/datasets.py
def rank(): """ Ranking datasets from lightgbm repository. """ rank_data_url = 'https://raw.githubusercontent.com/Microsoft/LightGBM/master/examples/lambdarank/' x_train, y_train = sklearn.datasets.load_svmlight_file(cache(rank_data_url + 'rank.train')) x_test, y_test = sklearn.datasets.load_svmligh...
def rank(): """ Ranking datasets from lightgbm repository. """ rank_data_url = 'https://raw.githubusercontent.com/Microsoft/LightGBM/master/examples/lambdarank/' x_train, y_train = sklearn.datasets.load_svmlight_file(cache(rank_data_url + 'rank.train')) x_test, y_test = sklearn.datasets.load_svmligh...
[ "Ranking", "datasets", "from", "lightgbm", "repository", "." ]
slundberg/shap
python
https://github.com/slundberg/shap/blob/b280cb81d498b9d98565cad8dd16fc88ae52649f/shap/datasets.py#L234-L242
[ "def", "rank", "(", ")", ":", "rank_data_url", "=", "'https://raw.githubusercontent.com/Microsoft/LightGBM/master/examples/lambdarank/'", "x_train", ",", "y_train", "=", "sklearn", ".", "datasets", ".", "load_svmlight_file", "(", "cache", "(", "rank_data_url", "+", "'rank...
b280cb81d498b9d98565cad8dd16fc88ae52649f
train
batch_remove_retrain
An approximation of holdout that only retraines the model once. This is alse called ROAR (RemOve And Retrain) in work by Google. It is much more computationally efficient that the holdout method because it masks the most important features in every sample and then retrains the model once, instead of retrai...
shap/benchmark/measures.py
def batch_remove_retrain(nmask_train, nmask_test, X_train, y_train, X_test, y_test, attr_train, attr_test, model_generator, metric): """ An approximation of holdout that only retraines the model once. This is alse called ROAR (RemOve And Retrain) in work by Google. It is much more computationally efficient...
def batch_remove_retrain(nmask_train, nmask_test, X_train, y_train, X_test, y_test, attr_train, attr_test, model_generator, metric): """ An approximation of holdout that only retraines the model once. This is alse called ROAR (RemOve And Retrain) in work by Google. It is much more computationally efficient...
[ "An", "approximation", "of", "holdout", "that", "only", "retraines", "the", "model", "once", "." ]
slundberg/shap
python
https://github.com/slundberg/shap/blob/b280cb81d498b9d98565cad8dd16fc88ae52649f/shap/benchmark/measures.py#L158-L193
[ "def", "batch_remove_retrain", "(", "nmask_train", ",", "nmask_test", ",", "X_train", ",", "y_train", ",", "X_test", ",", "y_test", ",", "attr_train", ",", "attr_test", ",", "model_generator", ",", "metric", ")", ":", "warnings", ".", "warn", "(", "\"The retra...
b280cb81d498b9d98565cad8dd16fc88ae52649f
train
keep_retrain
The model is retrained for each test sample with the non-important features set to a constant. If you want to know how important a set of features is you can ask how the model would be different if only those features had existed. To determine this we can mask the other features across the entire training ...
shap/benchmark/measures.py
def keep_retrain(nkeep, X_train, y_train, X_test, y_test, attr_test, model_generator, metric, trained_model, random_state): """ The model is retrained for each test sample with the non-important features set to a constant. If you want to know how important a set of features is you can ask how the model would b...
def keep_retrain(nkeep, X_train, y_train, X_test, y_test, attr_test, model_generator, metric, trained_model, random_state): """ The model is retrained for each test sample with the non-important features set to a constant. If you want to know how important a set of features is you can ask how the model would b...
[ "The", "model", "is", "retrained", "for", "each", "test", "sample", "with", "the", "non", "-", "important", "features", "set", "to", "a", "constant", "." ]
slundberg/shap
python
https://github.com/slundberg/shap/blob/b280cb81d498b9d98565cad8dd16fc88ae52649f/shap/benchmark/measures.py#L196-L258
[ "def", "keep_retrain", "(", "nkeep", ",", "X_train", ",", "y_train", ",", "X_test", ",", "y_test", ",", "attr_test", ",", "model_generator", ",", "metric", ",", "trained_model", ",", "random_state", ")", ":", "warnings", ".", "warn", "(", "\"The retrain based ...
b280cb81d498b9d98565cad8dd16fc88ae52649f
train
keep_mask
The model is revaluated for each test sample with the non-important features set to their mean.
shap/benchmark/measures.py
def keep_mask(nkeep, X_train, y_train, X_test, y_test, attr_test, model_generator, metric, trained_model, random_state): """ The model is revaluated for each test sample with the non-important features set to their mean. """ X_train, X_test = to_array(X_train, X_test) # how many features to mask a...
def keep_mask(nkeep, X_train, y_train, X_test, y_test, attr_test, model_generator, metric, trained_model, random_state): """ The model is revaluated for each test sample with the non-important features set to their mean. """ X_train, X_test = to_array(X_train, X_test) # how many features to mask a...
[ "The", "model", "is", "revaluated", "for", "each", "test", "sample", "with", "the", "non", "-", "important", "features", "set", "to", "their", "mean", "." ]
slundberg/shap
python
https://github.com/slundberg/shap/blob/b280cb81d498b9d98565cad8dd16fc88ae52649f/shap/benchmark/measures.py#L260-L281
[ "def", "keep_mask", "(", "nkeep", ",", "X_train", ",", "y_train", ",", "X_test", ",", "y_test", ",", "attr_test", ",", "model_generator", ",", "metric", ",", "trained_model", ",", "random_state", ")", ":", "X_train", ",", "X_test", "=", "to_array", "(", "X...
b280cb81d498b9d98565cad8dd16fc88ae52649f
train
keep_impute
The model is revaluated for each test sample with the non-important features set to an imputed value. Note that the imputation is done using a multivariate normality assumption on the dataset. This depends on being able to estimate the full data covariance matrix (and inverse) accuractly. So X_train.shape[0] s...
shap/benchmark/measures.py
def keep_impute(nkeep, X_train, y_train, X_test, y_test, attr_test, model_generator, metric, trained_model, random_state): """ The model is revaluated for each test sample with the non-important features set to an imputed value. Note that the imputation is done using a multivariate normality assumption on the ...
def keep_impute(nkeep, X_train, y_train, X_test, y_test, attr_test, model_generator, metric, trained_model, random_state): """ The model is revaluated for each test sample with the non-important features set to an imputed value. Note that the imputation is done using a multivariate normality assumption on the ...
[ "The", "model", "is", "revaluated", "for", "each", "test", "sample", "with", "the", "non", "-", "important", "features", "set", "to", "an", "imputed", "value", "." ]
slundberg/shap
python
https://github.com/slundberg/shap/blob/b280cb81d498b9d98565cad8dd16fc88ae52649f/shap/benchmark/measures.py#L283-L318
[ "def", "keep_impute", "(", "nkeep", ",", "X_train", ",", "y_train", ",", "X_test", ",", "y_test", ",", "attr_test", ",", "model_generator", ",", "metric", ",", "trained_model", ",", "random_state", ")", ":", "X_train", ",", "X_test", "=", "to_array", "(", ...
b280cb81d498b9d98565cad8dd16fc88ae52649f
train
keep_resample
The model is revaluated for each test sample with the non-important features set to resample background values.
shap/benchmark/measures.py
def keep_resample(nkeep, X_train, y_train, X_test, y_test, attr_test, model_generator, metric, trained_model, random_state): """ The model is revaluated for each test sample with the non-important features set to resample background values. """ # why broken? overwriting? X_train, X_test = to_array(X_train,...
def keep_resample(nkeep, X_train, y_train, X_test, y_test, attr_test, model_generator, metric, trained_model, random_state): """ The model is revaluated for each test sample with the non-important features set to resample background values. """ # why broken? overwriting? X_train, X_test = to_array(X_train,...
[ "The", "model", "is", "revaluated", "for", "each", "test", "sample", "with", "the", "non", "-", "important", "features", "set", "to", "resample", "background", "values", "." ]
slundberg/shap
python
https://github.com/slundberg/shap/blob/b280cb81d498b9d98565cad8dd16fc88ae52649f/shap/benchmark/measures.py#L320-L345
[ "def", "keep_resample", "(", "nkeep", ",", "X_train", ",", "y_train", ",", "X_test", ",", "y_test", ",", "attr_test", ",", "model_generator", ",", "metric", ",", "trained_model", ",", "random_state", ")", ":", "# why broken? overwriting?", "X_train", ",", "X_tes...
b280cb81d498b9d98565cad8dd16fc88ae52649f
train
local_accuracy
The how well do the features plus a constant base rate sum up to the model output.
shap/benchmark/measures.py
def local_accuracy(X_train, y_train, X_test, y_test, attr_test, model_generator, metric, trained_model): """ The how well do the features plus a constant base rate sum up to the model output. """ X_train, X_test = to_array(X_train, X_test) # how many features to mask assert X_train.shape[1] == X_t...
def local_accuracy(X_train, y_train, X_test, y_test, attr_test, model_generator, metric, trained_model): """ The how well do the features plus a constant base rate sum up to the model output. """ X_train, X_test = to_array(X_train, X_test) # how many features to mask assert X_train.shape[1] == X_t...
[ "The", "how", "well", "do", "the", "features", "plus", "a", "constant", "base", "rate", "sum", "up", "to", "the", "model", "output", "." ]
slundberg/shap
python
https://github.com/slundberg/shap/blob/b280cb81d498b9d98565cad8dd16fc88ae52649f/shap/benchmark/measures.py#L384-L396
[ "def", "local_accuracy", "(", "X_train", ",", "y_train", ",", "X_test", ",", "y_test", ",", "attr_test", ",", "model_generator", ",", "metric", ",", "trained_model", ")", ":", "X_train", ",", "X_test", "=", "to_array", "(", "X_train", ",", "X_test", ")", "...
b280cb81d498b9d98565cad8dd16fc88ae52649f
train
const_rand
Generate a random array with a fixed seed.
shap/benchmark/measures.py
def const_rand(size, seed=23980): """ Generate a random array with a fixed seed. """ old_seed = np.random.seed() np.random.seed(seed) out = np.random.rand(size) np.random.seed(old_seed) return out
def const_rand(size, seed=23980): """ Generate a random array with a fixed seed. """ old_seed = np.random.seed() np.random.seed(seed) out = np.random.rand(size) np.random.seed(old_seed) return out
[ "Generate", "a", "random", "array", "with", "a", "fixed", "seed", "." ]
slundberg/shap
python
https://github.com/slundberg/shap/blob/b280cb81d498b9d98565cad8dd16fc88ae52649f/shap/benchmark/measures.py#L401-L408
[ "def", "const_rand", "(", "size", ",", "seed", "=", "23980", ")", ":", "old_seed", "=", "np", ".", "random", ".", "seed", "(", ")", "np", ".", "random", ".", "seed", "(", "seed", ")", "out", "=", "np", ".", "random", ".", "rand", "(", "size", "...
b280cb81d498b9d98565cad8dd16fc88ae52649f