Code stringlengths 103 85.9k | Summary listlengths 0 94 |
|---|---|
Please provide a description of the function:def infer_storage_type(self, in_stype):
for i, stype in enumerate(in_stype):
assert stype == _STORAGE_TYPE_ID_TO_STR[_STORAGE_TYPE_DEFAULT], \
"Default infer_storage_type implementation doesnt allow non default stypes: " \
... | [
"infer_storage_type interface. Used to infer storage type of\n inputs and outputs in the forward pass. When this interface is not implemented,\n all stypes will be inferred as default.\n\n Parameters\n ----------\n in_stype : list of stypes, valid stypes are default, row_sparse an... |
Please provide a description of the function:def infer_storage_type_backward(self, ograd_stype, in_stype, out_stype, igrad_stype, aux_stype):
for i, stype in enumerate(ograd_stype):
assert stype == _STORAGE_TYPE_ID_TO_STR[_STORAGE_TYPE_DEFAULT], \
"Default infer_storage_type_bac... | [
"infer_storage_type_backward interface. Used to infer storage\n type of inputs and outputs in the backward pass.\n\n Will raise an error if undefined storage type is returned.\n Returned lists have to be the same size as the input lists to infer_storage_type_backward,\n otherwise an exce... |
Please provide a description of the function:def declare_backward_dependency(self, out_grad, in_data, out_data):
deps = []
if self.need_top_grad_:
deps.extend(out_grad)
deps.extend(in_data)
deps.extend(out_data)
return deps | [
"Declare dependencies of this operator for backward pass.\n\n Parameters\n ----------\n out_grad : list of int\n ids of out_grad blobs.\n in_data : list of int\n ids of in_data blobs.\n out_data: list of int\n ids of out_data blobs.\n\n Retu... |
Please provide a description of the function:def inc(self):
self.lock.acquire()
cur = self.counter
self.counter += 1
self.lock.release()
return cur | [
"Get index for new entry."
] |
Please provide a description of the function:def close(self):
if not self.is_open:
return
super(IndexCreator, self).close()
self.fidx.close() | [
"Closes the record and index files."
] |
Please provide a description of the function:def tell(self):
pos = ctypes.c_size_t()
check_call(_LIB.MXRecordIOReaderTell(self.handle, ctypes.byref(pos)))
return pos.value | [
"Returns the current position of read head.\n "
] |
Please provide a description of the function:def create_index(self):
self.reset()
counter = 0
pre_time = time.time()
while True:
if counter % 1000 == 0:
cur_time = time.time()
print('time:', cur_time - pre_time, ' count:', counter)
... | [
"Creates the index file from open record file\n "
] |
Please provide a description of the function:def _run_cmd(cmds):
if not isinstance(cmds, str):
cmds = "".join(cmds)
print("Execute \"%s\"" % cmds)
try:
subprocess.check_call(cmds, shell=True)
except subprocess.CalledProcessError as err:
print(err)
raise err | [
"Run commands, raise exception if failed"
] |
Please provide a description of the function:def generate_doxygen(app):
_run_cmd("cd %s/.. && make doxygen" % app.builder.srcdir)
_run_cmd("cp -rf doxygen/html %s/doxygen" % app.builder.outdir) | [
"Run the doxygen make commands"
] |
Please provide a description of the function:def build_mxnet(app):
if not os.path.exists(os.path.join(app.builder.srcdir, '..', 'config.mk')):
_run_cmd("cd %s/.. && cp make/config.mk config.mk && make -j$(nproc) USE_MKLDNN=0 USE_CPP_PACKAGE=1 " %
app.builder.srcdir)
else:
_r... | [
"Build mxnet .so lib"
] |
Please provide a description of the function:def build_r_docs(app):
r_root = app.builder.srcdir + '/../R-package'
pdf_path = app.builder.srcdir + '/api/r/mxnet-r-reference-manual.pdf'
_run_cmd('cd ' + r_root +
'; R -e "roxygen2::roxygenize()"; R CMD Rd2pdf . --no-preview -o ' + pdf_path)
... | [
"build r pdf"
] |
Please provide a description of the function:def build_scala(app):
if any(v in _BUILD_VER for v in ['1.2.', '1.3.', '1.4.']):
_run_cmd("cd %s/.. && make scalapkg" % app.builder.srcdir)
_run_cmd("cd %s/.. && make scalainstall" % app.builder.srcdir)
else:
_run_cmd("cd %s/../scala-pack... | [
"build scala for scala docs, java docs, and clojure docs to use"
] |
Please provide a description of the function:def build_scala_docs(app):
scala_path = app.builder.srcdir + '/../scala-package'
scala_doc_sources = 'find . -type f -name "*.scala" | egrep \"\.\/core|\.\/infer\" | egrep -v \"\/javaapi\" | egrep -v \"Suite\"'
scala_doc_classpath = ':'.join([
'`fin... | [
"build scala doc and then move the outdir"
] |
Please provide a description of the function:def build_java_docs(app):
java_path = app.builder.srcdir + '/../scala-package'
java_doc_sources = 'find . -type f -name "*.scala" | egrep \"\.\/core|\.\/infer\" | egrep \"\/javaapi\" | egrep -v \"Suite\"'
java_doc_classpath = ':'.join([
'`find native... | [
"build java docs and then move the outdir"
] |
Please provide a description of the function:def build_clojure_docs(app):
clojure_path = app.builder.srcdir + '/../contrib/clojure-package'
_run_cmd('cd ' + clojure_path + '; lein codox')
dest_path = app.builder.outdir + '/api/clojure/docs'
_run_cmd('rm -rf ' + dest_path)
_run_cmd('mkdir -p ' +... | [
"build clojure doc and then move the outdir"
] |
Please provide a description of the function:def _convert_md_table_to_rst(table):
if len(table) < 3:
return ''
out = '```eval_rst\n.. list-table::\n :header-rows: 1\n\n'
for i,l in enumerate(table):
cols = l.split('|')[1:-1]
if i == 0:
ncol = len(cols)
else... | [
"Convert a markdown table to rst format"
] |
Please provide a description of the function:def convert_table(app, docname, source):
num_tables = 0
for i,j in enumerate(source):
table = []
output = ''
in_table = False
for l in j.split('\n'):
r = l.strip()
if r.startswith('|'):
tabl... | [
"Find tables in a markdown and then convert them into the rst format"
] |
Please provide a description of the function:def _parse_code_lines(lines):
in_code = False
lang = None
indent = None
for l in lines:
m = _CODE_MARK.match(l)
if m is not None:
if not in_code:
if m.groups()[1].lower() in _LANGS:
lang = m... | [
"A iterator that returns if a line is within a code block\n\n Returns\n -------\n iterator of (str, bool, str, int)\n - line: the line\n - in_code: if this line is in a code block\n - lang: the code block langunage\n - indent: the code indent\n "
] |
Please provide a description of the function:def _get_blocks(lines):
cur_block = []
pre_lang = None
pre_in_code = None
for (l, in_code, cur_lang, _) in _parse_code_lines(lines):
if in_code != pre_in_code:
if pre_in_code and len(cur_block) >= 2:
cur_block = cur_bl... | [
"split lines into code and non-code blocks\n\n Returns\n -------\n iterator of (bool, str, list of str)\n - if it is a code block\n - source language\n - lines of source\n "
] |
Please provide a description of the function:def _get_python_block_output(src, global_dict, local_dict):
src = '\n'.join([l for l in src.split('\n')
if not l.startswith('%') and not 'plt.show()' in l])
ret_status = True
err = ''
with _string_io() as s:
try:
... | [
"Evaluate python source codes\n\n Returns\n (bool, str):\n - True if success\n - output\n "
] |
Please provide a description of the function:def copy_artifacts(app):
dest_path = app.builder.outdir + '/error'
source_path = app.builder.srcdir + '/build_version_doc/artifacts'
_run_cmd('cd ' + app.builder.srcdir)
_run_cmd('rm -rf ' + dest_path)
_run_cmd('mkdir -p ' + dest_path)
_run_cmd('... | [
"Copies artifacts needed for website presentation"
] |
Please provide a description of the function:def download_caffe_model(model_name, meta_info, dst_dir='./model'):
if not os.path.isdir(dst_dir):
os.mkdir(dst_dir)
model_name = os.path.join(dst_dir, model_name)
assert 'prototxt' in meta_info, "missing prototxt url"
proto_url, proto_sha1 = me... | [
"Download caffe model into disk by the given meta info "
] |
Please provide a description of the function:def convert_caffe_model(model_name, meta_info, dst_dir='./model'):
(prototxt, caffemodel, mean) = download_caffe_model(model_name, meta_info, dst_dir)
model_name = os.path.join(dst_dir, model_name)
convert_model(prototxt, caffemodel, model_name)
if isin... | [
"Download, convert and save a caffe model"
] |
Please provide a description of the function:def multi_p_run(tot_num, _func, worker, params, n_process):
from multiprocessing import Process, Queue
out_q = Queue()
procs = []
split_num = split_seq(list(range(0, tot_num)), n_process)
print(tot_num, ">>", split_num)
split_len = len(split_n... | [
"\n Run _func with multi-process using params.\n "
] |
Please provide a description of the function:def split_seq(sam_num, n_tile):
import math
print(sam_num)
print(n_tile)
start_num = sam_num[0::int(math.ceil(len(sam_num) / (n_tile)))]
end_num = start_num[1::]
end_num.append(len(sam_num))
return [[i, j] for i, j in zip(start_num, end_num)] | [
"\n Split the number(sam_num) into numbers by n_tile\n "
] |
Please provide a description of the function:def put_worker(func, from_idx, to_idx, params, out_q):
succ, fail = func(from_idx, to_idx, params)
return out_q.put({'succ': succ, 'fail': fail}) | [
"\n put worker\n "
] |
Please provide a description of the function:def namedtuple_with_defaults(typename, field_names, default_values=()):
T = collections.namedtuple(typename, field_names)
T.__new__.__defaults__ = (None, ) * len(T._fields)
if isinstance(default_values, collections.Mapping):
prototype = T(**default_v... | [
" create a namedtuple with default values "
] |
Please provide a description of the function:def merge_dict(a, b):
c = a.copy()
c.update(b)
return c | [
" merge dict a, b, with b overriding keys in a "
] |
Please provide a description of the function:def zip_namedtuple(nt_list):
if not nt_list:
return dict()
if not isinstance(nt_list, list):
nt_list = [nt_list]
for nt in nt_list:
assert type(nt) == type(nt_list[0])
ret = {k : [v] for k, v in nt_list[0]._asdict().items()}
f... | [
" accept list of namedtuple, return a dict of zipped fields "
] |
Please provide a description of the function:def config_as_dict(cfg):
ret = cfg.__dict__.copy()
# random cropping params
del ret['rand_crop_samplers']
assert isinstance(cfg.rand_crop_samplers, list)
ret = merge_dict(ret, zip_namedtuple(cfg.rand_crop_samplers))
num_crop_sampler = len(cfg.ran... | [
" convert raw configuration to unified dictionary "
] |
Please provide a description of the function:def import_model(model_file):
graph = GraphProto()
try:
import onnx
except ImportError:
raise ImportError("Onnx and protobuf need to be installed. "
+ "Instructions to install - https://github.com/onnx/onnx")
# ... | [
"Imports the ONNX model file, passed as a parameter, into MXNet symbol and parameters.\n Operator support and coverage -\n https://cwiki.apache.org/confluence/display/MXNET/MXNet-ONNX+Integration\n\n Parameters\n ----------\n model_file : str\n ONNX model file name\n\n Returns\n -------\... |
Please provide a description of the function:def get_model_metadata(model_file):
graph = GraphProto()
try:
import onnx
except ImportError:
raise ImportError("Onnx and protobuf need to be installed. "
+ "Instructions to install - https://github.com/onnx/onnx")
... | [
"\n Returns the name and shape information of input and output tensors of the given ONNX model file.\n\n Notes\n -----\n This method is available when you ``import mxnet.contrib.onnx``\n\n Parameters\n ----------\n model_file : str\n ONNX model file name\n\n Returns\n -------\n ... |
Please provide a description of the function:def conv_act_layer(from_layer, name, num_filter, kernel=(1,1), pad=(0,0), \
stride=(1,1), act_type="relu", use_batchnorm=False):
conv = mx.symbol.Convolution(data=from_layer, kernel=kernel, pad=pad, \
stride=stride, num_filter=num_filter, name="{}_conv".... | [
"\n wrapper for a small Convolution group\n\n Parameters:\n ----------\n from_layer : mx.symbol\n continue on which layer\n name : str\n base name of the new layers\n num_filter : int\n how many filters to use in Convolution layer\n kernel : tuple (int, int)\n kernel... |
Please provide a description of the function:def legacy_conv_act_layer(from_layer, name, num_filter, kernel=(1,1), pad=(0,0), \
stride=(1,1), act_type="relu", use_batchnorm=False):
assert not use_batchnorm, "batchnorm not yet supported"
bias = mx.symbol.Variable(name="conv{}_bias".format(name),
... | [
"\n wrapper for a small Convolution group\n\n Parameters:\n ----------\n from_layer : mx.symbol\n continue on which layer\n name : str\n base name of the new layers\n num_filter : int\n how many filters to use in Convolution layer\n kernel : tuple (int, int)\n kernel... |
Please provide a description of the function:def multi_layer_feature(body, from_layers, num_filters, strides, pads, min_filter=128):
# arguments check
assert len(from_layers) > 0
assert isinstance(from_layers[0], str) and len(from_layers[0].strip()) > 0
assert len(from_layers) == len(num_filters) =... | [
"Wrapper function to extract features from base network, attaching extra\n layers and SSD specific layers\n\n Parameters\n ----------\n from_layers : list of str\n feature extraction layers, use '' for add extra layers\n For example:\n from_layers = ['relu4_3', 'fc7', '', '', '', ''... |
Please provide a description of the function:def multibox_layer(from_layers, num_classes, sizes=[.2, .95],
ratios=[1], normalization=-1, num_channels=[],
clip=False, interm_layer=0, steps=[]):
assert len(from_layers) > 0, "from_layers must not be empty list"
assert n... | [
"\n the basic aggregation module for SSD detection. Takes in multiple layers,\n generate multiple object detection targets by customized layers\n\n Parameters:\n ----------\n from_layers : list of mx.symbol\n generate multibox detection from layers\n num_classes : int\n number of cla... |
Please provide a description of the function:def _apply_weighting(F, loss, weight=None, sample_weight=None):
if sample_weight is not None:
loss = F.broadcast_mul(loss, sample_weight)
if weight is not None:
assert isinstance(weight, numeric_types), "weight must be a number"
loss = l... | [
"Apply weighting to loss.\n\n Parameters\n ----------\n loss : Symbol\n The loss to be weighted.\n weight : float or None\n Global scalar weight for loss.\n sample_weight : Symbol or None\n Per sample weighting. Must be broadcastable to\n the same shape as loss. For exampl... |
Please provide a description of the function:def _reshape_like(F, x, y):
return x.reshape(y.shape) if F is ndarray else F.reshape_like(x, y) | [
"Reshapes x to the same shape as y."
] |
Please provide a description of the function:def get_tv_grad_executor(img, ctx, tv_weight):
if tv_weight <= 0.0:
return None
nchannel = img.shape[1]
simg = mx.sym.Variable("img")
skernel = mx.sym.Variable("kernel")
channels = mx.sym.SliceChannel(simg, num_outputs=nchannel)
out = mx.... | [
"create TV gradient executor with input binded on img\n "
] |
Please provide a description of the function:def train_nstyle(args, callback=None):
# input
dev = mx.gpu(args.gpu) if args.gpu >= 0 else mx.cpu()
content_np = PreprocessContentImage(args.content_image, args.max_long_edge)
style_np = PreprocessStyleImage(args.style_image, shape=content_np.shape)
... | [
"Train a neural style network.\n Args are from argparse and control input, output, hyper-parameters.\n callback allows for display of training progress.\n "
] |
Please provide a description of the function:def _get_batch(self):
batch_data = mx.nd.zeros((self.batch_size, 3, self._data_shape[0], self._data_shape[1]))
batch_label = []
for i in range(self.batch_size):
if (self._current + i) >= self._size:
if not self.is_... | [
"\n Load data/label from dataset\n "
] |
Please provide a description of the function:def _data_augmentation(self, data, label):
if self.is_train and self._rand_samplers:
rand_crops = []
for rs in self._rand_samplers:
rand_crops += rs.sample(label)
num_rand_crops = len(rand_crops)
... | [
"\n perform data augmentations: crop, mirror, resize, sub mean, swap channels...\n "
] |
Please provide a description of the function:def get_mnist():
np.random.seed(1234) # set seed for deterministic ordering
mnist_data = mx.test_utils.get_mnist()
X = np.concatenate([mnist_data['train_data'], mnist_data['test_data']])
Y = np.concatenate([mnist_data['train_label'], mnist_data['test_la... | [
" Gets MNIST dataset "
] |
Please provide a description of the function:def _split_input_slice(batch_size, work_load_list):
total_work_load = sum(work_load_list)
batch_num_list = [round(work_load * batch_size / total_work_load)
for work_load in work_load_list]
batch_num_sum = sum(batch_num_list)
if batc... | [
"Get input slice from the input shape.\n\n Parameters\n ----------\n batch_size : int\n The number of samples in a mini-batch.\n work_load_list : list of float or int, optional\n The list of work load for different devices,\n in the same order as `ctx`.\n\n Returns\n -------\n... |
Please provide a description of the function:def _check_arguments(symbol):
arg_set = set()
arg_names = symbol.list_arguments()
for name in arg_names:
if name in arg_set:
raise ValueError(('Find duplicated argument name \"%s\", ' +
'please make the weigh... | [
"Check the argument names of symbol.\n This function checks the duplication of arguments in Symbol.\n The check is done for feedforward net for now.\n\n Parameters\n ----------\n symbol : Symbol\n The network configuration.\n "
] |
Please provide a description of the function:def _load_general(data, targets):
for d_src, d_targets in zip(data, targets):
if isinstance(d_targets, nd.NDArray):
d_src.copyto(d_targets)
else:
assert d_targets[-1][0].stop == d_src.shape[0], \
"Batch size mi... | [
"Load a list of arrays into a list of arrays specified by slices."
] |
Please provide a description of the function:def _bind_exec(sym, ctx, input_shapes, param_names, need_grad=False,
base_exec=None, shared_data_arrays=None, input_types=None, logger=logging):
arg_shape, _, aux_shape = sym.infer_shape(**input_shapes)
assert(arg_shape is not None)
if input_t... | [
"bind executor for bucketing, potentially sharing data with an existing executor."
] |
Please provide a description of the function:def load_data_batch(self, data_batch):
_load_data(data_batch, self.data_arrays)
_load_label(data_batch, self.label_arrays) | [
"Load data and labels into arrays."
] |
Please provide a description of the function:def forward(self, is_train=False):
for texec in self.train_execs:
texec.forward(is_train=is_train) | [
"Perform a forward pass on each executor."
] |
Please provide a description of the function:def update_metric(self, metric, labels, pre_sliced=False):
for current_exec, (texec, islice) in enumerate(zip(self.train_execs, self.slices)):
if not pre_sliced:
labels_slice = [label[islice] for label in labels]
else:... | [
"Update evaluation metric with label and current outputs."
] |
Please provide a description of the function:def install_monitor(self, monitor):
if self.sym_gen is not None:
raise NotImplementedError("Monitoring is not implemented for bucketing")
for train_exec in self.execgrp.train_execs:
monitor.install(train_exec) | [
"Install monitor on all executors."
] |
Please provide a description of the function:def set_params(self, arg_params, aux_params):
for texec in self.execgrp.train_execs:
texec.copy_params_from(arg_params, aux_params) | [
"Set parameter and aux values.\n\n Parameters\n ----------\n arg_params : list of NDArray\n Source parameter arrays\n aux_params : list of NDArray\n Source aux arrays.\n "
] |
Please provide a description of the function:def load_data_batch(self, data_batch):
if self.sym_gen is not None:
key = data_batch.bucket_key
if key not in self.execgrp_bucket:
# create new bucket entry
symbol = self.sym_gen(key)
ex... | [
"Load data and labels into arrays."
] |
Please provide a description of the function:def update_metric(self, metric, labels, pre_sliced=False):
self.curr_execgrp.update_metric(metric, labels, pre_sliced) | [
"Update metric with the current executor."
] |
Please provide a description of the function:def clear(self):
self.states[:] = 0
self.actions[:] = 0
self.rewards[:] = 0
self.terminate_flags[:] = 0
self.top = 0
self.size = 0 | [
"\n Clear all contents in the relay memory\n "
] |
Please provide a description of the function:def get_header_guard_dmlc(filename):
fileinfo = cpplint.FileInfo(filename)
file_path_from_root = fileinfo.RepositoryName()
inc_list = ['include', 'api', 'wrapper']
if file_path_from_root.find('src/') != -1 and _HELPER.project_name is not None:
i... | [
"Get Header Guard Convention for DMLC Projects.\n For headers in include, directly use the path\n For headers in src, use project name plus path\n Examples: with project-name = dmlc\n include/dmlc/timer.h -> DMLC_TIMTER_H_\n src/io/libsvm_parser.h -> DMLC_IO_LIBSVM_PARSER_H_\n "
] |
Please provide a description of the function:def process(fname, allow_type):
fname = str(fname)
# HACK: ignore op.h which is automatically generated
if fname.endswith('op.h'):
return
arr = fname.rsplit('.', 1)
if fname.find('#') != -1 or arr[-1] not in allow_type:
return
if ar... | [
"Process a file."
] |
Please provide a description of the function:def main():
if len(sys.argv) < 3:
print('Usage: <project-name> <filetype> <list-of-path to traverse>')
print('\tfiletype can be python/cpp/all')
exit(-1)
_HELPER.project_name = sys.argv[1]
file_type = sys.argv[2]
allow_type = []
... | [
"Main entry function."
] |
Please provide a description of the function:def _print_summary_map(strm, result_map, ftype):
if len(result_map) == 0:
return 0
npass = len([x for k, x in result_map.iteritems() if len(x) == 0])
strm.write('=====%d/%d %s files passed check=====\n' % (npass, len(result_map), ... | [
"Print summary of certain result map."
] |
Please provide a description of the function:def process_cpp(self, path, suffix):
_cpplint_state.ResetErrorCounts()
cpplint.ProcessFile(str(path), _cpplint_state.verbose_level)
_cpplint_state.PrintErrorCounts()
errors = _cpplint_state.errors_by_category.copy()
if suffix... | [
"Process a cpp file."
] |
Please provide a description of the function:def process_python(self, path):
(pylint_stdout, pylint_stderr) = epylint.py_run(
' '.join([str(path)] + self.pylint_opts), return_std=True)
emap = {}
print(pylint_stderr.read())
for line in pylint_stdout:
sys.s... | [
"Process a python file."
] |
Please provide a description of the function:def print_summary(self, strm):
nerr = 0
nerr += LintHelper._print_summary_map(strm, self.cpp_header_map, 'cpp-header')
nerr += LintHelper._print_summary_map(strm, self.cpp_src_map, 'cpp-soruce')
nerr += LintHelper._print_summary_map(s... | [
"Print summary of lint."
] |
Please provide a description of the function:def _init_kvstore_server_module():
is_worker = ctypes.c_int()
check_call(_LIB.MXKVStoreIsWorkerNode(ctypes.byref(is_worker)))
if is_worker.value == 0:
kvstore = create('dist')
server = KVStoreServer(kvstore)
server.run()
sys.e... | [
"Start server/scheduler."
] |
Please provide a description of the function:def _controller(self):
def server_controller(cmd_id, cmd_body, _):
if not self.init_logginig:
# the reason put the codes here is because we cannot get
# kvstore.rank earlier
head = '%(a... | [
"Return the server controller.",
"Server controler."
] |
Please provide a description of the function:def run(self):
_ctrl_proto = ctypes.CFUNCTYPE(None, ctypes.c_int, ctypes.c_char_p, ctypes.c_void_p)
check_call(_LIB.MXKVStoreRunServer(self.handle, _ctrl_proto(self._controller()), None)) | [
"Run the server, whose behavior is like.\n\n\n >>> while receive(x):\n ... if is_command x: controller(x)\n ... else if is_key_value x: updater(x)\n "
] |
Please provide a description of the function:def _generate_ndarray_function_code(handle, name, func_name, signature_only=False):
real_name = ctypes.c_char_p()
desc = ctypes.c_char_p()
num_args = mx_uint()
arg_names = ctypes.POINTER(ctypes.c_char_p)()
arg_types = ctypes.POINTER(ctypes.c_char_p)(... | [
"Generate function for ndarray op by handle and function name.",
"\ndef %s(*%s, **kwargs):",
"\n ndargs = []\n for i in {}:\n assert isinstance(i, NDArrayBase), \\\\\n \"Positional arguments must have NDArray type, \" \\\\\n \"but got %s\"%str(i)\n ndargs.append(i)",
... |
Please provide a description of the function:def _make_ndarray_function(handle, name, func_name):
code, doc_str = _generate_ndarray_function_code(handle, name, func_name)
local = {}
exec(code, None, local) # pylint: disable=exec-used
ndarray_function = local[func_name]
ndarray_function.__name... | [
"Create a NDArray function from the FunctionHandle."
] |
Please provide a description of the function:def count_tokens_from_str(source_str, token_delim=' ', seq_delim='\n',
to_lower=False, counter_to_update=None):
source_str = filter(None,
re.split(token_delim + '|' + seq_delim, source_str))
if to_lower:
... | [
"Counts tokens in the specified string.\n\n For token_delim=\\'<td>\\' and seq_delim=\\'<sd>\\', a specified string of two sequences of\n tokens may look like::\n\n <td>token1<td>token2<td>token3<td><sd><td>token4<td>token5<td><sd>\n\n <td> and <sd> are regular expressions. Make use of \\\\\\\\ to allow... |
Please provide a description of the function:def zeros(shape, ctx=None, dtype=None, stype=None, **kwargs):
if stype is None or stype == 'default':
return _zeros_ndarray(shape, ctx, dtype, **kwargs)
else:
return _zeros_sparse_ndarray(stype, shape, ctx, dtype, **kwargs) | [
"Return a new array of given shape and type, filled with zeros.\n\n Parameters\n ----------\n shape : int or tuple of int\n The shape of the empty array\n ctx : Context, optional\n An optional device context (default is the current default context)\n dtype : str or numpy.dtype, optional... |
Please provide a description of the function:def empty(shape, ctx=None, dtype=None, stype=None):
if stype is None or stype == 'default':
return _empty_ndarray(shape, ctx, dtype)
else:
return _empty_sparse_ndarray(stype, shape, ctx, dtype) | [
"Returns a new array of given shape and type, without initializing entries.\n\n Parameters\n ----------\n shape : int or tuple of int\n The shape of the empty array.\n ctx : Context, optional\n An optional device context (default is the current default context).\n dtype : str or numpy.d... |
Please provide a description of the function:def array(source_array, ctx=None, dtype=None):
if spsp is not None and isinstance(source_array, spsp.csr.csr_matrix):
return _sparse_array(source_array, ctx=ctx, dtype=dtype)
elif isinstance(source_array, NDArray) and source_array.stype != 'default':
... | [
"Creates an array from any object exposing the array interface.\n\n Parameters\n ----------\n source_array : array_like\n An object exposing the array interface, an object whose `__array__`\n method returns an array, or any (nested) sequence.\n ctx : Context, optional\n Device conte... |
Please provide a description of the function:def load(fname):
if not isinstance(fname, string_types):
raise TypeError('fname required to be a string')
out_size = mx_uint()
out_name_size = mx_uint()
handles = ctypes.POINTER(NDArrayHandle)()
names = ctypes.POINTER(ctypes.c_char_p)()
c... | [
"Loads an array from file.\n\n See more details in ``save``.\n\n Parameters\n ----------\n fname : str\n The filename.\n\n Returns\n -------\n list of NDArray, RowSparseNDArray or CSRNDArray, or \\\n dict of str to NDArray, RowSparseNDArray or CSRNDArray\n Loaded data.\n "
] |
Please provide a description of the function:def load_frombuffer(buf):
if not isinstance(buf, string_types + tuple([bytes])):
raise TypeError('buf required to be a string or bytes')
out_size = mx_uint()
out_name_size = mx_uint()
handles = ctypes.POINTER(NDArrayHandle)()
names = ctypes.P... | [
"Loads an array dictionary or list from a buffer\n\n See more details in ``save``.\n\n Parameters\n ----------\n buf : str\n Buffer containing contents of a file as a string or bytes.\n\n Returns\n -------\n list of NDArray, RowSparseNDArray or CSRNDArray, or \\\n dict of str to NDArr... |
Please provide a description of the function:def save(fname, data):
if isinstance(data, NDArray):
data = [data]
handles = c_array(NDArrayHandle, [])
if isinstance(data, dict):
str_keys = data.keys()
nd_vals = data.values()
if any(not isinstance(k, string_types) for k... | [
"Saves a list of arrays or a dict of str->array to file.\n\n Examples of filenames:\n\n - ``/path/to/file``\n - ``s3://my-bucket/path/to/file`` (if compiled with AWS S3 supports)\n - ``hdfs://path/to/file`` (if compiled with HDFS supports)\n\n Parameters\n ----------\n fname : str\n The ... |
Please provide a description of the function:def _common_prefix(names):
if not names:
return ''
prefix = names[0]
for name in names:
i = 0
while i < len(prefix) and i < len(name) and prefix[i] == name[i]:
i += 1
prefix = prefix[:i]
return prefix | [
"Get the common prefix for all names"
] |
Please provide a description of the function:def _infer_param_types(in_params, out_params, arg_params, aux_params, default_dtype=mx_real_t):
arg_types = None
aux_types = None
# Get Input symbol details. This will be used to infer types of
# other parameters.
input_sym_names = [in_param.name fo... | [
"Utility function that helps in inferring DType of args and auxs params\n from given input param.\n\n Parameters\n ----------\n in_params: List of Symbol\n List of input symbol variables.\n out_params: Symbol\n Output symbol variable.\n arg_params: List of Str\n List of names ... |
Please provide a description of the function:def create(prefix, params, hint):
current = getattr(_BlockScope._current, "value", None)
if current is None:
if prefix is None:
if not hasattr(_name.NameManager._current, "value"):
_name.NameManager._cu... | [
"Creates prefix and params for new `Block`."
] |
Please provide a description of the function:def collect_params(self, select=None):
# We need to check here because blocks inside containers are not supported.
self._check_container_with_block()
ret = ParameterDict(self._params.prefix)
if not select:
ret.update(self.... | [
"Returns a :py:class:`ParameterDict` containing this :py:class:`Block` and all of its\n children's Parameters(default), also can returns the select :py:class:`ParameterDict`\n which match some given regular expressions.\n\n For example, collect the specified parameters in ['conv1_weight', 'conv... |
Please provide a description of the function:def save_params(self, filename):
warnings.warn("save_params is deprecated. Please use save_parameters. "
"Note that if you want load from SymbolBlock later, please "
"use export instead. For details, see "
... | [
"[Deprecated] Please use save_parameters. Note that if you want load\n from SymbolBlock later, please use export instead.\n\n Save parameters to file.\n\n filename : str\n Path to file.\n "
] |
Please provide a description of the function:def load_parameters(self, filename, ctx=None, allow_missing=False,
ignore_extra=False):
loaded = ndarray.load(filename)
params = self._collect_params_with_prefix()
if not loaded and not params:
return
... | [
"Load parameters from file previously saved by `save_parameters`.\n\n Parameters\n ----------\n filename : str\n Path to parameter file.\n ctx : Context or list of Context, default cpu()\n Context(s) to initialize loaded parameters on.\n allow_missing : bool,... |
Please provide a description of the function:def load_params(self, filename, ctx=None, allow_missing=False,
ignore_extra=False):
warnings.warn("load_params is deprecated. Please use load_parameters.")
self.load_parameters(filename, ctx, allow_missing, ignore_extra) | [
"[Deprecated] Please use load_parameters.\n\n Load parameters from file.\n\n filename : str\n Path to parameter file.\n ctx : Context or list of Context, default cpu()\n Context(s) to initialize loaded parameters on.\n allow_missing : bool, default False\n ... |
Please provide a description of the function:def register_child(self, block, name=None):
if name is None:
name = str(len(self._children))
self._children[name] = block | [
"Registers block as a child of self. :py:class:`Block` s assigned to self as\n attributes will be registered automatically."
] |
Please provide a description of the function:def register_forward_pre_hook(self, hook):
r
handle = HookHandle()
handle.attach(self._forward_pre_hooks, hook)
return handle | [
"Registers a forward pre-hook on the block.\n\n The hook function is called immediately before :func:`forward`.\n It should not modify the input or output.\n\n Parameters\n ----------\n hook : callable\n The forward hook function of form `hook(block, input) -> None`.\n\... |
Please provide a description of the function:def register_forward_hook(self, hook):
r
handle = HookHandle()
handle.attach(self._forward_hooks, hook)
return handle | [
"Registers a forward hook on the block.\n\n The hook function is called immediately after :func:`forward`.\n It should not modify the input or output.\n\n Parameters\n ----------\n hook : callable\n The forward hook function of form `hook(block, input, output) -> None`.... |
Please provide a description of the function:def apply(self, fn):
r
for cld in self._children.values():
cld.apply(fn)
fn(self)
return self | [
"Applies ``fn`` recursively to every child block as well as self.\n\n Parameters\n ----------\n fn : callable\n Function to be applied to each submodule, of form `fn(block)`.\n\n Returns\n -------\n this block\n "
] |
Please provide a description of the function:def initialize(self, init=initializer.Uniform(), ctx=None, verbose=False,
force_reinit=False):
self.collect_params().initialize(init, ctx, verbose, force_reinit) | [
"Initializes :py:class:`Parameter` s of this :py:class:`Block` and its children.\n Equivalent to ``block.collect_params().initialize(...)``\n\n Parameters\n ----------\n init : Initializer\n Global default Initializer to be used when :py:meth:`Parameter.init` is ``None``.\n ... |
Please provide a description of the function:def hybridize(self, active=True, **kwargs):
for cld in self._children.values():
cld.hybridize(active, **kwargs) | [
"Activates or deactivates :py:class:`HybridBlock` s recursively. Has no effect on\n non-hybrid children.\n\n Parameters\n ----------\n active : bool, default True\n Whether to turn hybrid on or off.\n static_alloc : bool, default False\n Statically allocate m... |
Please provide a description of the function:def cast(self, dtype):
for child in self._children.values():
child.cast(dtype)
for _, param in self.params.items():
param.cast(dtype) | [
"Cast this Block to use another data type.\n\n Parameters\n ----------\n dtype : str or numpy.dtype\n The new data type.\n "
] |
Please provide a description of the function:def summary(self, *inputs):
summary = OrderedDict()
seen = set()
hooks = []
def _get_shape_str(args):
def flatten(args):
if not isinstance(args, (list, tuple)):
return [args], int(0)
... | [
"Print the summary of the model's output and parameters.\n\n The network must have been initialized, and must not have been hybridized.\n\n Parameters\n ----------\n inputs : object\n Any input that the model supports. For any tensor in the input, only\n :class:`mxn... |
Please provide a description of the function:def _infer_attrs(self, infer_fn, attr, *args):
inputs, out = self._get_graph(*args)
args, _ = _flatten(args, "input")
with warnings.catch_warnings(record=True) as w:
arg_attrs, _, aux_attrs = getattr(out, infer_fn)(
... | [
"Generic infer attributes."
] |
Please provide a description of the function:def export(self, path, epoch=0):
if not self._cached_graph:
raise RuntimeError(
"Please first call block.hybridize() and then run forward with "
"this block at least once before calling export.")
sym = self... | [
"Export HybridBlock to json format that can be loaded by\n `SymbolBlock.imports`, `mxnet.mod.Module` or the C++ interface.\n\n .. note:: When there are only one input, it will have name `data`. When there\n Are more than one inputs, they will be named as `data0`, `data1`, etc.\n\n ... |
Please provide a description of the function:def forward(self, x, *args):
if isinstance(x, NDArray):
with x.context as ctx:
if self._active:
return self._call_cached_op(x, *args)
try:
params = {i: j.data(ctx) for i, j ... | [
"Defines the forward computation. Arguments can be either\n :py:class:`NDArray` or :py:class:`Symbol`."
] |
Please provide a description of the function:def imports(symbol_file, input_names, param_file=None, ctx=None):
sym = symbol.load(symbol_file)
if isinstance(input_names, str):
input_names = [input_names]
inputs = [symbol.var(i) for i in input_names]
ret = SymbolBlock(... | [
"Import model previously saved by `HybridBlock.export` or\n `Module.save_checkpoint` as a SymbolBlock for use in Gluon.\n\n Parameters\n ----------\n symbol_file : str\n Path to symbol file.\n input_names : list of str\n List of input variable names\n ... |
Please provide a description of the function:def calc_expectation(grad_dict, num_batches):
for key in grad_dict.keys():
grad_dict[str.format(key+"_expectation")] = mx.ndarray.sum(grad_dict[key], axis=0) / num_batches
return grad_dict | [
"Calculates the expectation of the gradients per epoch for each parameter w.r.t number of batches\n\n Parameters\n ----------\n grad_dict: dict\n dictionary that maps parameter name to gradients in the mod executor group\n num_batches: int\n number of batches\n\n Returns\n ----------... |
Please provide a description of the function:def calc_variance(grad_dict, num_batches, param_names):
for i in range(len(param_names)):
diff_sqr = mx.ndarray.square(mx.nd.subtract(grad_dict[param_names[i]],
grad_dict[str.format(param_names[i]+"_expecta... | [
"Calculates the variance of the gradients per epoch for each parameter w.r.t number of batches\n\n Parameters\n ----------\n grad_dict: dict\n dictionary that maps parameter name to gradients in the mod executor group\n num_batches: int\n number of batches\n param_names: str\n pa... |
Please provide a description of the function:def makedirs(d):
if sys.version_info[0] < 3:
from distutils.dir_util import mkpath
mkpath(d)
else:
os.makedirs(d, exist_ok=True) | [
"Create directories recursively if they don't exist. os.makedirs(exist_ok=True) is not\n available in Python2"
] |
Please provide a description of the function:def alexnet(pretrained=False, ctx=cpu(),
root=os.path.join(base.data_dir(), 'models'), **kwargs):
r
net = AlexNet(**kwargs)
if pretrained:
from ..model_store import get_model_file
net.load_parameters(get_model_file('alexnet', root=root... | [
"AlexNet model from the `\"One weird trick...\" <https://arxiv.org/abs/1404.5997>`_ paper.\n\n Parameters\n ----------\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n ctx : Context, default CPU\n The context in which to load the pretrained weights.\... |
Please provide a description of the function:def classifer_metrics(label, pred):
prediction = np.argmax(pred, axis=1)
label = label.astype(int)
pred_is_entity = prediction != not_entity_index
label_is_entity = label != not_entity_index
corr_pred = (prediction == label) == (pred_is_entity == T... | [
"\n computes f1, precision and recall on the entity class\n "
] |
Please provide a description of the function:def data_iter(batch_size, num_embed, pre_trained_word2vec=False):
print('Loading data...')
if pre_trained_word2vec:
word2vec = data_helpers.load_pretrained_word2vec('data/rt.vec')
x, y = data_helpers.load_data_with_word2vec(word2vec)
# re... | [
"Construct data iter\n\n Parameters\n ----------\n batch_size: int\n num_embed: int\n pre_trained_word2vec: boolean\n identify the pre-trained layers or not\n Returns\n ----------\n train_set: DataIter\n Train DataIter\n valid: DataIter\n ... |
Please provide a description of the function:def sym_gen(batch_size, sentences_size, num_embed, vocabulary_size,
num_label=2, filter_list=None, num_filter=100,
dropout=0.0, pre_trained_word2vec=False):
input_x = mx.sym.Variable('data')
input_y = mx.sym.Variable('softmax_label')
... | [
"Generate network symbol\n\n Parameters\n ----------\n batch_size: int\n sentences_size: int\n num_embed: int\n vocabulary_size: int\n num_label: int\n filter_list: list\n num_filter: int\n dropout: int\n pre_trained_word2vec: boolean\n identify the pre-traine... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.