Code stringlengths 103 85.9k | Summary listlengths 0 94 |
|---|---|
Please provide a description of the function:def calc_grad(exe, exe_grads, params, X, Y, label_name=None, outgrad_f=None):
exe.copy_params_from(params)
exe.arg_dict['data'][:] = X
if outgrad_f is None:
exe.arg_dict[label_name][:] = Y
exe.forward(is_train=True)
exe.backward()
... | [
"Calculate gradient"
] |
Please provide a description of the function:def step_HMC(exe, exe_params, exe_grads, label_key, noise_precision, prior_precision, L=10, eps=1E-6):
init_params = {k: v.copyto(v.context) for k, v in exe_params.items()}
end_params = {k: v.copyto(v.context) for k, v in exe_params.items()}
init_momentums =... | [
"Generate the implementation of step HMC"
] |
Please provide a description of the function:def HMC(sym, data_inputs, X, Y, X_test, Y_test, sample_num,
initializer=None, noise_precision=1 / 9.0, prior_precision=0.1,
learning_rate=1E-6, L=10, dev=mx.gpu()):
label_key = list(set(data_inputs.keys()) - set(['data']))[0]
exe, exe_params, exe... | [
"Generate the implementation of HMC"
] |
Please provide a description of the function:def SGD(sym, data_inputs, X, Y, X_test, Y_test, total_iter_num,
lr=None,
lr_scheduler=None, prior_precision=1,
out_grad_f=None,
initializer=None,
minibatch_size=100, dev=mx.gpu()):
if out_grad_f is None:
label_key = li... | [
"Generate the implementation of SGD"
] |
Please provide a description of the function:def SGLD(sym, X, Y, X_test, Y_test, total_iter_num,
data_inputs=None,
learning_rate=None,
lr_scheduler=None, prior_precision=1,
out_grad_f=None,
initializer=None,
minibatch_size=100, thin_interval=100, burn_in_iter_num=10... | [
"Generate the implementation of SGLD"
] |
Please provide a description of the function:def DistilledSGLD(teacher_sym, student_sym,
teacher_data_inputs, student_data_inputs,
X, Y, X_test, Y_test, total_iter_num,
teacher_learning_rate, student_learning_rate,
teacher_lr_scheduler=None, studen... | [
"Generate the implementation of DistilledSGLD"
] |
Please provide a description of the function:def get_platforms(path: str = get_dockerfiles_path()) -> List[str]:
dockerfiles = glob.glob(os.path.join(path, "Dockerfile.*"))
dockerfiles = list(filter(lambda x: x[-1] != '~', dockerfiles))
files = list(map(lambda x: re.sub(r"Dockerfile.(.*)", r"\1", x), d... | [
"Get a list of architectures given our dockerfiles"
] |
Please provide a description of the function:def get_docker_tag(platform: str, registry: str) -> str:
platform = platform if any(x in platform for x in ['build.', 'publish.']) else 'build.{}'.format(platform)
if not registry:
registry = "mxnet_local"
return "{0}/{1}".format(registry, platform) | [
":return: docker tag to be used for the container"
] |
Please provide a description of the function:def build_docker(platform: str, docker_binary: str, registry: str, num_retries: int, no_cache: bool) -> str:
tag = get_docker_tag(platform=platform, registry=registry)
logging.info("Building docker container tagged '%s' with %s", tag, docker_binary)
#
# ... | [
"\n Build a container for the given platform\n :param platform: Platform\n :param docker_binary: docker binary to use (docker/nvidia-docker)\n :param registry: Dockerhub registry name\n :param num_retries: Number of retries to build the docker image\n :param no_cache: pass no-cache to docker to re... |
Please provide a description of the function:def _get_local_image_id(docker_binary, docker_tag):
cmd = [docker_binary, "images", "-q", docker_tag]
image_id_b = check_output(cmd)
image_id = image_id_b.decode('utf-8').strip()
if not image_id:
raise RuntimeError('Unable to find docker image id... | [
"\n Get the image id of the local docker layer with the passed tag\n :param docker_tag: docker tag\n :return: Image id as string or None if tag does not exist\n "
] |
Please provide a description of the function:def default_ccache_dir() -> str:
# Share ccache across containers
if 'CCACHE_DIR' in os.environ:
ccache_dir = os.path.realpath(os.environ['CCACHE_DIR'])
try:
os.makedirs(ccache_dir, exist_ok=True)
return ccache_dir
... | [
":return: ccache directory for the current platform"
] |
Please provide a description of the function:def container_run(platform: str,
nvidia_runtime: bool,
docker_registry: str,
shared_memory_size: str,
local_ccache_dir: str,
command: List[str],
cleanup: Cleanup,
... | [
"Run command in a container"
] |
Please provide a description of the function:def load_docker_cache(tag, docker_registry) -> None:
if docker_registry:
# noinspection PyBroadException
try:
import docker_cache
logging.info('Docker cache download is enabled from registry %s', docker_registry)
d... | [
"Imports tagged container from the given docker registry"
] |
Please provide a description of the function:def _load_general(data, targets, major_axis):
for d_src, d_targets, axis in zip(data, targets, major_axis): # pylint: disable=too-many-nested-blocks
if isinstance(d_targets, nd.NDArray):
d_src.copyto(d_targets)
elif isinstance(d_src, (lis... | [
"Load a list of arrays into a list of arrays specified by slices."
] |
Please provide a description of the function:def _load_data(batch, targets, major_axis):
if isinstance(batch, list):
new_batch = []
for i in range(len(targets)):
new_batch.append([b.data[i] for b in batch])
new_targets = [[dst for _, dst in d_target] for d_target in targets]... | [
"Load data into sliced arrays."
] |
Please provide a description of the function:def _merge_multi_context(outputs, major_axis):
rets = []
for tensors, axis in zip(outputs, major_axis):
if axis >= 0:
# pylint: disable=no-member,protected-access
if len(tensors) == 1:
rets.append(tensors[0])
... | [
"Merge outputs that lives on multiple context into one, so that they look\n like living on one context.\n "
] |
Please provide a description of the function:def _prepare_group2ctxs(group2ctxs, ctx_len):
if group2ctxs is None:
return [None] * ctx_len
elif isinstance(group2ctxs, list):
assert(len(group2ctxs) == ctx_len), "length of group2ctxs\
should be %d" % ctx_len
return group2ct... | [
"Prepare the group2contexts, will duplicate the context\n if some ctx_group map to only one context.\n "
] |
Please provide a description of the function:def decide_slices(self, data_shapes):
assert len(data_shapes) > 0
major_axis = [DataDesc.get_batch_axis(x.layout) for x in data_shapes]
for (name, shape), axis in zip(data_shapes, major_axis):
if axis == -1:
conti... | [
"Decide the slices for each context according to the workload.\n\n Parameters\n ----------\n data_shapes : list\n list of (name, shape) specifying the shapes for the input data or label.\n "
] |
Please provide a description of the function:def _collect_arrays(self):
# convenient data structures
self.data_arrays = [[(self.slices[i], e.arg_dict[name]) for i, e in enumerate(self.execs)]
for name, _ in self.data_shapes]
self.state_arrays = [[e.arg_dict[... | [
"Collect internal arrays from executors."
] |
Please provide a description of the function:def bind_exec(self, data_shapes, label_shapes, shared_group=None, reshape=False):
assert reshape or not self.execs
self.batch_size = None
# calculate workload and bind executors
self.data_layouts = self.decide_slices(data_shapes)
... | [
"Bind executors on their respective devices.\n\n Parameters\n ----------\n data_shapes : list\n label_shapes : list\n shared_group : DataParallelExecutorGroup\n reshape : bool\n "
] |
Please provide a description of the function:def reshape(self, data_shapes, label_shapes):
if data_shapes == self.data_shapes and label_shapes == self.label_shapes:
return
if self._default_execs is None:
self._default_execs = [i for i in self.execs]
self.bind_exe... | [
"Reshape executors.\n\n Parameters\n ----------\n data_shapes : list\n label_shapes : list\n "
] |
Please provide a description of the function:def set_params(self, arg_params, aux_params, allow_extra=False):
for exec_ in self.execs:
exec_.copy_params_from(arg_params, aux_params, allow_extra_params=allow_extra) | [
"Assign, i.e. copy parameters to all the executors.\n\n Parameters\n ----------\n arg_params : dict\n A dictionary of name to `NDArray` parameter mapping.\n aux_params : dict\n A dictionary of name to `NDArray` auxiliary variable mapping.\n allow_extra : bool... |
Please provide a description of the function:def get_params(self, arg_params, aux_params):
for name, block in zip(self.param_names, self.param_arrays):
weight = sum(w.copyto(ctx.cpu()) for w in block) / len(block)
weight.astype(arg_params[name].dtype).copyto(arg_params[name])
... | [
" Copy data from each executor to `arg_params` and `aux_params`.\n\n Parameters\n ----------\n arg_params : list of NDArray\n Target parameter arrays.\n aux_params : list of NDArray\n Target aux arrays.\n\n Notes\n -----\n - This function will i... |
Please provide a description of the function:def forward(self, data_batch, is_train=None):
_load_data(data_batch, self.data_arrays, self.data_layouts)
if is_train is None:
is_train = self.for_training
if isinstance(data_batch, list):
if self.label_arrays is not ... | [
"Split `data_batch` according to workload and run forward on each devices.\n\n Parameters\n ----------\n data_batch : DataBatch\n Or could be any object implementing similar interface.\n is_train : bool\n The hint for the backend, indicating whether we are during tr... |
Please provide a description of the function:def get_output_shapes(self):
outputs = self.execs[0].outputs
shapes = [out.shape for out in outputs]
concat_shapes = []
for key, the_shape, axis in zip(self.symbol.list_outputs(), shapes, self.output_layouts):
the_shape =... | [
"Get the shapes of the outputs."
] |
Please provide a description of the function:def get_outputs(self, merge_multi_context=True, begin=0, end=None):
if end is None:
end = self.num_outputs
outputs = [[exec_.outputs[i] for exec_ in self.execs]
for i in range(begin, end)]
if merge_multi_context... | [
"Get outputs of the previous forward computation.\n If begin or end is specified, return [begin, end)-th outputs,\n otherwise return all outputs.\n\n Parameters\n ----------\n merge_multi_context : bool\n Default is `True`. In the case when data-parallelism is used, the... |
Please provide a description of the function:def set_states(self, states=None, value=None):
if states is not None:
assert value is None, "Only one of states & value can be specified."
_load_general(states, self.state_arrays, (0,)*len(states))
else:
assert val... | [
"Set value for states. Only one of states & value can be specified.\n\n Parameters\n ----------\n states : list of list of NDArrays\n source states arrays formatted like [[state1_dev1, state1_dev2],\n [state2_dev1, state2_dev2]].\n value : number\n a sing... |
Please provide a description of the function:def get_input_grads(self, merge_multi_context=True):
assert self.inputs_need_grad
if merge_multi_context:
return _merge_multi_context(self.input_grad_arrays, self.data_layouts)
return self.input_grad_arrays | [
"Get the gradients with respect to the inputs of the module.\n\n Parameters\n ----------\n merge_multi_context : bool\n Defaults to ``True``. In the case when data-parallelism is used, the outputs\n will be collected from multiple devices. A `True` value indicate that we\n... |
Please provide a description of the function:def backward(self, out_grads=None):
assert self.for_training, 're-bind with for_training=True to run backward'
if out_grads is None:
out_grads = []
for i, (exec_, islice) in enumerate(zip(self.execs, self.slices)):
ou... | [
"Run backward on all devices. A backward should be called after\n a call to the forward function. Backward cannot be called unless\n ``self.for_training`` is ``True``.\n\n Parameters\n ----------\n out_grads : NDArray or list of NDArray, optional\n Gradient on the outpu... |
Please provide a description of the function:def update_metric(self, eval_metric, labels, pre_sliced):
for current_exec, (texec, islice) in enumerate(zip(self.execs, self.slices)):
if not pre_sliced:
labels_slice = []
for label, axis in zip(labels, self.label... | [
"Accumulate the performance according to `eval_metric` on all devices\n by comparing outputs from [begin, end) to labels. By default use all\n outputs.\n\n Parameters\n ----------\n eval_metric : EvalMetric\n The metric used for evaluation.\n labels : list of NDA... |
Please provide a description of the function:def _bind_ith_exec(self, i, data_shapes, label_shapes, shared_group):
shared_exec = None if shared_group is None else shared_group.execs[i]
context = self.contexts[i]
shared_data_arrays = self.shared_data_arrays[i]
input_shapes = dic... | [
"Internal utility function to bind the i-th executor.\n This function utilizes simple_bind python interface.\n "
] |
Please provide a description of the function:def _sliced_shape(self, shapes, i, major_axis):
sliced_shapes = []
for desc, axis in zip(shapes, major_axis):
shape = list(desc.shape)
if axis >= 0:
shape[axis] = self.slices[i].stop - self.slices[i].start
... | [
"Get the sliced shapes for the i-th executor.\n\n Parameters\n ----------\n shapes : list of (str, tuple)\n The original (name, shape) pairs.\n i : int\n Which executor we are dealing with.\n "
] |
Please provide a description of the function:def parse_class_names(args):
num_class = args.num_class
if len(args.class_names) > 0:
if os.path.isfile(args.class_names):
# try to open it to read class names
with open(args.class_names, 'r') as f:
class_names = [... | [
" parse # classes and class_names if applicable "
] |
Please provide a description of the function:def _has_instance(data, dtype):
for item in data:
_, arr = item
if isinstance(arr, dtype):
return True
return False | [
"Return True if ``data`` has instance of ``dtype``.\n This function is called after _init_data.\n ``data`` is a list of (str, NDArray)"
] |
Please provide a description of the function:def _getdata_by_idx(data, idx):
shuffle_data = []
for k, v in data:
if (isinstance(v, h5py.Dataset) if h5py else False):
shuffle_data.append((k, v))
elif isinstance(v, CSRNDArray):
shuffle_data.append((k, sparse_array(v.a... | [
"Shuffle the data."
] |
Please provide a description of the function:def get_mobilenet(multiplier, pretrained=False, ctx=cpu(),
root=os.path.join(base.data_dir(), 'models'), **kwargs):
r
net = MobileNet(multiplier, **kwargs)
if pretrained:
from ..model_store import get_model_file
version_suffix =... | [
"MobileNet model from the\n `\"MobileNets: Efficient Convolutional Neural Networks for Mobile Vision Applications\"\n <https://arxiv.org/abs/1704.04861>`_ paper.\n\n Parameters\n ----------\n multiplier : float\n The width multiplier for controling the model size. Only multipliers that are no\... |
Please provide a description of the function:def get(self, name, hint):
if name:
return name
if hint not in self._counter:
self._counter[hint] = 0
name = '%s%d' % (hint, self._counter[hint])
self._counter[hint] += 1
return name | [
"Get the canonical name for a symbol.\n\n This is the default implementation.\n If the user specifies a name,\n the user-specified name will be used.\n\n When user does not specify a name, we automatically generate a\n name based on the hint string.\n\n Parameters\n ... |
Please provide a description of the function:def draw(self, true_classes):
range_max = self.range_max
num_sampled = self.num_sampled
ctx = true_classes.context
log_range = math.log(range_max + 1)
num_tries = 0
true_classes = true_classes.reshape((-1,))
sa... | [
"Draw samples from log uniform distribution and returns sampled candidates,\n expected count for true classes and sampled classes."
] |
Please provide a description of the function:def get_inception_score(images, splits=10):
assert (images.shape[1] == 3)
# load inception model
if inception_model is None:
_init_inception()
# resize images to adapt inception model(inceptionV3)
if images.shape[2] != 299:
images =... | [
"\n Inception_score function.\n The images will be divided into 'splits' parts, and calculate each inception_score separately,\n then return the mean and std of inception_scores of these parts.\n :param images: Images(num x c x w x h) that needs to calculate inception_score.\n :param splits:\... |
Please provide a description of the function:def load_param(params, ctx=None):
if ctx is None:
ctx = mx.cpu()
save_dict = mx.nd.load(params)
arg_params = {}
aux_params = {}
for k, v in save_dict.items():
tp, name = k.split(':', 1)
if tp == 'arg':
arg_params[n... | [
"same as mx.model.load_checkpoint, but do not load symnet and will convert context"
] |
Please provide a description of the function:def rnn_unroll(cell, length, inputs=None, begin_state=None, input_prefix='', layout='NTC'):
warnings.warn('rnn_unroll is deprecated. Please call cell.unroll directly.')
return cell.unroll(length=length, inputs=inputs, begin_state=begin_state,
... | [
"Deprecated. Please use cell.unroll instead"
] |
Please provide a description of the function:def save_rnn_checkpoint(cells, prefix, epoch, symbol, arg_params, aux_params):
if isinstance(cells, BaseRNNCell):
cells = [cells]
for cell in cells:
arg_params = cell.unpack_weights(arg_params)
save_checkpoint(prefix, epoch, symbol, arg_param... | [
"Save checkpoint for model using RNN cells.\n Unpacks weight before saving.\n\n Parameters\n ----------\n cells : mxnet.rnn.RNNCell or list of RNNCells\n The RNN cells used by this symbol.\n prefix : str\n Prefix of model name.\n epoch : int\n The epoch number of the model.\n ... |
Please provide a description of the function:def load_rnn_checkpoint(cells, prefix, epoch):
sym, arg, aux = load_checkpoint(prefix, epoch)
if isinstance(cells, BaseRNNCell):
cells = [cells]
for cell in cells:
arg = cell.pack_weights(arg)
return sym, arg, aux | [
"Load model checkpoint from file.\n Pack weights after loading.\n\n Parameters\n ----------\n cells : mxnet.rnn.RNNCell or list of RNNCells\n The RNN cells used by this symbol.\n prefix : str\n Prefix of model name.\n epoch : int\n Epoch number of model we would like to load.\... |
Please provide a description of the function:def do_rnn_checkpoint(cells, prefix, period=1):
period = int(max(1, period))
# pylint: disable=unused-argument
def _callback(iter_no, sym=None, arg=None, aux=None):
if (iter_no + 1) % period == 0:
save_rnn_checkpoint(cells, prefi... | [
"Make a callback to checkpoint Module to prefix every epoch.\n unpacks weights used by cells before saving.\n\n Parameters\n ----------\n cells : mxnet.rnn.RNNCell or list of RNNCells\n The RNN cells used by this symbol.\n prefix : str\n The file prefix to checkpoint to\n period : in... |
Please provide a description of the function:def hybridize(self, active=True, **kwargs):
if self._children and all(isinstance(c, HybridBlock) for c in self._children.values()):
warnings.warn(
"All children of this Sequential layer '%s' are HybridBlocks. Consider "
... | [
"Activates or deactivates `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 **kwargs : string\n Additional flags for hybridized operator.\n ... |
Please provide a description of the function:def read_img(path):
img = cv2.resize(cv2.imread(path, 0), (80, 30)).astype(np.float32) / 255
img = np.expand_dims(img.transpose(1, 0), 0)
return img | [
" Reads image specified by path into numpy.ndarray"
] |
Please provide a description of the function:def lstm_init_states(batch_size):
hp = Hyperparams()
init_shapes = lstm.init_states(batch_size=batch_size, num_lstm_layer=hp.num_lstm_layer, num_hidden=hp.num_hidden)
init_names = [s[0] for s in init_shapes]
init_arrays = [mx.nd.zeros(x[1]) for x in init... | [
" Returns a tuple of names and zero arrays for LSTM init states"
] |
Please provide a description of the function:def load_module(prefix, epoch, data_names, data_shapes):
sym, arg_params, aux_params = mx.model.load_checkpoint(prefix, epoch)
# We don't need CTC loss for prediction, just a simple softmax will suffice.
# We get the output of the layer just before the loss... | [
"Loads the model from checkpoint specified by prefix and epoch, binds it\n to an executor, and sets its parameters and returns a mx.mod.Module\n "
] |
Please provide a description of the function:def main():
parser = argparse.ArgumentParser()
parser.add_argument("path", help="Path to the CAPTCHA image file")
parser.add_argument("--prefix", help="Checkpoint prefix [Default 'ocr']", default='ocr')
parser.add_argument("--epoch", help="Checkpoint epo... | [
"Program entry point"
] |
Please provide a description of the function:def bbox_flip(bbox, width, flip_x=False):
if flip_x:
xmax = width - bbox[:, 0]
xmin = width - bbox[:, 2]
bbox[:, 0] = xmin
bbox[:, 2] = xmax
return bbox | [
"\n invalid value in bbox_transform if this wrong (no overlap), note index 0 and 2\n also note need to save before assignment\n :param bbox: [n][x1, y1, x2, y2]\n :param width: cv2 (height, width, channel)\n :param flip_x: will flip x1 and x2\n :return: flipped box\n "
] |
Please provide a description of the function:def bbox_overlaps(boxes, query_boxes):
n_ = boxes.shape[0]
k_ = query_boxes.shape[0]
overlaps = np.zeros((n_, k_), dtype=np.float)
for k in range(k_):
query_box_area = (query_boxes[k, 2] - query_boxes[k, 0] + 1) * (query_boxes[k, 3] - query_boxes... | [
"\n determine overlaps between boxes and query_boxes\n :param boxes: n * 4 bounding boxes\n :param query_boxes: k * 4 bounding boxes\n :return: overlaps: n * k overlaps\n "
] |
Please provide a description of the function:def clip_boxes(boxes, im_shape):
# x1 >= 0
boxes[:, 0::4] = np.maximum(np.minimum(boxes[:, 0::4], im_shape[1] - 1), 0)
# y1 >= 0
boxes[:, 1::4] = np.maximum(np.minimum(boxes[:, 1::4], im_shape[0] - 1), 0)
# x2 < im_shape[1]
boxes[:, 2::4] = np.ma... | [
"\n Clip boxes to image boundaries.\n :param boxes: [N, 4* num_classes]\n :param im_shape: tuple of 2\n :return: [N, 4* num_classes]\n "
] |
Please provide a description of the function:def bbox_transform(ex_rois, gt_rois, box_stds):
assert ex_rois.shape[0] == gt_rois.shape[0], 'inconsistent rois number'
ex_widths = ex_rois[:, 2] - ex_rois[:, 0] + 1.0
ex_heights = ex_rois[:, 3] - ex_rois[:, 1] + 1.0
ex_ctr_x = ex_rois[:, 0] + 0.5 * (ex... | [
"\n compute bounding box regression targets from ex_rois to gt_rois\n :param ex_rois: [N, 4]\n :param gt_rois: [N, 4]\n :return: [N, 4]\n "
] |
Please provide a description of the function:def bbox_pred(boxes, box_deltas, box_stds):
if boxes.shape[0] == 0:
return np.zeros((0, box_deltas.shape[1]))
widths = boxes[:, 2] - boxes[:, 0] + 1.0
heights = boxes[:, 3] - boxes[:, 1] + 1.0
ctr_x = boxes[:, 0] + 0.5 * (widths - 1.0)
ctr_y... | [
"\n Transform the set of class-agnostic boxes into class-specific boxes\n by applying the predicted offsets (box_deltas)\n :param boxes: !important [N 4]\n :param box_deltas: [N, 4 * num_classes]\n :return: [N 4 * num_classes]\n "
] |
Please provide a description of the function:def nms(dets, thresh):
x1 = dets[:, 0]
y1 = dets[:, 1]
x2 = dets[:, 2]
y2 = dets[:, 3]
scores = dets[:, 4]
areas = (x2 - x1 + 1) * (y2 - y1 + 1)
order = scores.argsort()[::-1]
keep = []
while order.size > 0:
i = order[0]
... | [
"\n greedily select boxes with high confidence and overlap with current maximum <= thresh\n rule out overlap >= thresh\n :param dets: [[x1, y1, x2, y2 score]]\n :param thresh: retain overlap < thresh\n :return: indexes to keep\n "
] |
Please provide a description of the function:def im_detect(rois, scores, bbox_deltas, im_info,
bbox_stds, nms_thresh, conf_thresh):
rois = rois.asnumpy()
scores = scores.asnumpy()
bbox_deltas = bbox_deltas.asnumpy()
im_info = im_info.asnumpy()
height, width, scale = im_info
... | [
"rois (nroi, 4), scores (nrois, nclasses), bbox_deltas (nrois, 4 * nclasses), im_info (3)"
] |
Please provide a description of the function:def c_str(string):
if not isinstance(string, str):
string = string.decode('ascii')
return ctypes.c_char_p(string.encode('utf-8')) | [
"\"Convert a python string to C string."
] |
Please provide a description of the function:def _find_lib_path():
curr_path = os.path.dirname(os.path.abspath(os.path.expanduser(__file__)))
amalgamation_lib_path = os.path.join(curr_path, '../../lib/libmxnet_predict.so')
if os.path.exists(amalgamation_lib_path) and os.path.isfile(amalgamation_lib_pat... | [
"Find mxnet library."
] |
Please provide a description of the function:def _load_lib():
lib_path = _find_lib_path()
lib = ctypes.cdll.LoadLibrary(lib_path[0])
# DMatrix functions
lib.MXGetLastError.restype = ctypes.c_char_p
return lib | [
"Load libary by searching possible path."
] |
Please provide a description of the function:def load_ndarray_file(nd_bytes):
handle = NDListHandle()
olen = mx_uint()
nd_bytes = bytearray(nd_bytes)
ptr = (ctypes.c_char * len(nd_bytes)).from_buffer(nd_bytes)
_check_call(_LIB.MXNDListCreate(
ptr, len(nd_bytes),
ctypes.byref(han... | [
"Load ndarray file and return as list of numpy array.\n\n Parameters\n ----------\n nd_bytes : str or bytes\n The internal ndarray bytes\n\n Returns\n -------\n out : dict of str to numpy array or list of numpy array\n The output list or dict, depending on whether the saved type is l... |
Please provide a description of the function:def forward(self, **kwargs):
for k, v in kwargs.items():
if not isinstance(v, np.ndarray):
raise ValueError("Expect numpy ndarray as input")
v = np.asarray(v, dtype=np.float32, order='C')
_check_call(_LIB.M... | [
"Perform forward to get the output.\n\n Parameters\n ----------\n **kwargs\n Keyword arguments of input variable name to data.\n\n Examples\n --------\n >>> predictor.forward(data=mydata)\n >>> out = predictor.get_output(0)\n "
] |
Please provide a description of the function:def reshape(self, input_shapes):
indptr = [0]
sdata = []
keys = []
for k, v in input_shapes.items():
if not isinstance(v, tuple):
raise ValueError("Expect input_shapes to be dict str->tuple")
k... | [
"Change the input shape of the predictor.\n\n Parameters\n ----------\n input_shapes : dict of str to tuple\n The new shape of input data.\n\n Examples\n --------\n >>> predictor.reshape({'data':data_shape_tuple})\n "
] |
Please provide a description of the function:def get_output(self, index):
pdata = ctypes.POINTER(mx_uint)()
ndim = mx_uint()
_check_call(_LIB.MXPredGetOutputShape(
self.handle, index,
ctypes.byref(pdata),
ctypes.byref(ndim)))
shape = tuple(pda... | [
"Get the index-th output.\n\n Parameters\n ----------\n index : int\n The index of output.\n\n Returns\n -------\n out : numpy array.\n The output array.\n "
] |
Please provide a description of the function:def begin_episode(self, max_episode_step=DEFAULT_MAX_EPISODE_STEP):
if self.episode_step > self.max_episode_step or self.ale.game_over():
self.start()
else:
for i in range(self.screen_buffer_length):
self.ale.a... | [
"\n Begin an episode of a game instance. We can play the game for a maximum of\n `max_episode_step` and after that, we are forced to restart\n "
] |
Please provide a description of the function:def reset(self):
self._init_counter = -1
self._counter = -1
for cell in self._children.values():
cell.reset() | [
"Reset before re-using the cell for another graph."
] |
Please provide a description of the function:def begin_state(self, batch_size=0, func=ndarray.zeros, **kwargs):
assert not self._modified, \
"After applying modifier cells (e.g. ZoneoutCell) the base " \
"cell cannot be called directly. Call the modifier cell instead."
s... | [
"Initial state for this cell.\n\n Parameters\n ----------\n func : callable, default symbol.zeros\n Function for creating initial state.\n\n For Symbol API, func can be `symbol.zeros`, `symbol.uniform`,\n `symbol.var etc`. Use `symbol.var` if you want to directl... |
Please provide a description of the function:def unroll(self, length, inputs, begin_state=None, layout='NTC', merge_outputs=None,
valid_length=None):
# pylint: disable=too-many-locals
self.reset()
inputs, axis, F, batch_size = _format_sequence(length, inputs, layout, Fal... | [
"Unrolls an RNN cell across time steps.\n\n Parameters\n ----------\n length : int\n Number of steps to unroll.\n inputs : Symbol, list of Symbol, or None\n If `inputs` is a single Symbol (usually the output\n of Embedding symbol), it should have shape\n ... |
Please provide a description of the function:def _get_activation(self, F, inputs, activation, **kwargs):
func = {'tanh': F.tanh,
'relu': F.relu,
'sigmoid': F.sigmoid,
'softsign': F.softsign}.get(activation)
if func:
return func(inputs,... | [
"Get activation function. Convert if is string"
] |
Please provide a description of the function:def forward(self, inputs, states):
# pylint: disable= arguments-differ
self._counter += 1
return super(RecurrentCell, self).forward(inputs, states) | [
"Unrolls the recurrent cell for one time step.\n\n Parameters\n ----------\n inputs : sym.Variable\n Input symbol, 2D, of shape (batch_size * num_units).\n states : list of sym.Variable\n RNN state from previous step or the output of begin_state().\n\n Return... |
Please provide a description of the function:def _check_input_names(symbol, names, typename, throw):
args = symbol.list_arguments()
for name in names:
if name in args:
continue
candidates = [arg for arg in args if
not arg.endswith('_weight') and
... | [
"Check that all input names are in symbol's arguments."
] |
Please provide a description of the function:def _check_names_match(data_names, data_shapes, name, throw):
actual = [x[0] for x in data_shapes]
if sorted(data_names) != sorted(actual):
msg = "Data provided by %s_shapes don't match names specified by %s_names (%s vs. %s)"%(
name, name, s... | [
"Check that input names matches input data descriptors."
] |
Please provide a description of the function:def _parse_data_desc(data_names, label_names, data_shapes, label_shapes):
data_shapes = [x if isinstance(x, DataDesc) else DataDesc(*x) for x in data_shapes]
_check_names_match(data_names, data_shapes, 'data', True)
if label_shapes is not None:
label... | [
"parse data_attrs into DataDesc format and check that names match"
] |
Please provide a description of the function:def forward_backward(self, data_batch):
self.forward(data_batch, is_train=True)
self.backward() | [
"A convenient function that calls both ``forward`` and ``backward``."
] |
Please provide a description of the function:def score(self, eval_data, eval_metric, num_batch=None, batch_end_callback=None,
score_end_callback=None,
reset=True, epoch=0, sparse_row_id_fn=None):
assert self.binded and self.params_initialized
if reset:
e... | [
"Runs prediction on ``eval_data`` and evaluates the performance according to\n the given ``eval_metric``.\n\n Checkout `Module Tutorial <http://mxnet.io/tutorials/basic/module.html>`_ to see\n a end-to-end use-case.\n\n Parameters\n ----------\n eval_data : DataIter\n ... |
Please provide a description of the function:def iter_predict(self, eval_data, num_batch=None, reset=True, sparse_row_id_fn=None):
assert self.binded and self.params_initialized
if reset:
eval_data.reset()
for nbatch, eval_batch in enumerate(eval_data):
if num_... | [
"Iterates over predictions.\n\n Examples\n --------\n >>> for pred, i_batch, batch in module.iter_predict(eval_data):\n ... # pred is a list of outputs from the module\n ... # i_batch is a integer\n ... # batch is the data batch from the data iterator\n\n ... |
Please provide a description of the function:def predict(self, eval_data, num_batch=None, merge_batches=True, reset=True,
always_output_list=False, sparse_row_id_fn=None):
assert self.binded and self.params_initialized
if isinstance(eval_data, (ndarray.NDArray, np.ndarray)):
... | [
"Runs prediction and collects the outputs.\n\n When `merge_batches` is ``True`` (by default), the return value will be a list\n ``[out1, out2, out3]``, where each element is formed by concatenating the outputs for\n all the mini-batches. When `always_output_list` is ``False`` (as by default),\n... |
Please provide a description of the function:def set_params(self, arg_params, aux_params, allow_missing=False, force_init=True,
allow_extra=False):
self.init_params(initializer=None, arg_params=arg_params, aux_params=aux_params,
allow_missing=allow_missing, f... | [
"Assigns parameter and aux state values.\n\n Parameters\n ----------\n arg_params : dict\n Dictionary of name to value (`NDArray`) mapping.\n aux_params : dict\n Dictionary of name to value (`NDArray`) mapping.\n allow_missing : bool\n If ``True``,... |
Please provide a description of the function:def save_params(self, fname):
arg_params, aux_params = self.get_params()
save_dict = {('arg:%s' % k) : v.as_in_context(cpu()) for k, v in arg_params.items()}
save_dict.update({('aux:%s' % k) : v.as_in_context(cpu()) for k, v in aux_params.ite... | [
"Saves model parameters to file.\n\n Parameters\n ----------\n fname : str\n Path to output param file.\n\n Examples\n --------\n >>> # An example of saving module parameters.\n >>> mod.save_params('myfile')\n "
] |
Please provide a description of the function:def load_params(self, fname):
save_dict = ndarray.load(fname)
arg_params = {}
aux_params = {}
for k, value in save_dict.items():
arg_type, name = k.split(':', 1)
if arg_type == 'arg':
arg_params... | [
"Loads model parameters from file.\n\n Parameters\n ----------\n fname : str\n Path to input param file.\n\n Examples\n --------\n >>> # An example of loading module parameters.\n >>> mod.load_params('myfile')\n "
] |
Please provide a description of the function:def bind(self, data_shapes, label_shapes=None, for_training=True,
inputs_need_grad=False, force_rebind=False, shared_module=None,
grad_req='write'):
raise NotImplementedError() | [
"Binds the symbols to construct executors. This is necessary before one\n can perform computation with the module.\n\n Parameters\n ----------\n data_shapes : list of (str, tuple) or DataDesc objects\n Typically is ``data_iter.provide_data``. Can also be a list of\n ... |
Please provide a description of the function:def find_lib_path():
lib_from_env = os.environ.get('MXNET_LIBRARY_PATH')
if lib_from_env:
if os.path.isfile(lib_from_env):
if not os.path.isabs(lib_from_env):
logging.warning("MXNET_LIBRARY_PATH should be an absolute path, ins... | [
"Find MXNet dynamic library files.\n\n Returns\n -------\n lib_path : list(string)\n List of all found path to the libraries.\n "
] |
Please provide a description of the function:def find_include_path():
incl_from_env = os.environ.get('MXNET_INCLUDE_PATH')
if incl_from_env:
if os.path.isdir(incl_from_env):
if not os.path.isabs(incl_from_env):
logging.warning("MXNET_INCLUDE_PATH should be an absolute pa... | [
"Find MXNet included header files.\n\n Returns\n -------\n incl_path : string\n Path to the header files.\n "
] |
Please provide a description of the function:def image(self, captcha_str):
img = self.captcha.generate(captcha_str)
img = np.fromstring(img.getvalue(), dtype='uint8')
img = cv2.imdecode(img, cv2.IMREAD_GRAYSCALE)
img = cv2.resize(img, (self.h, self.w))
img = img.transpos... | [
"Generate a greyscale captcha image representing number string\n\n Parameters\n ----------\n captcha_str: str\n string a characters for captcha image\n\n Returns\n -------\n numpy.ndarray\n Generated greyscale image in np.ndarray float type with values... |
Please provide a description of the function:def get_rand(num_digit_min, num_digit_max):
buf = ""
max_len = random.randint(num_digit_min, num_digit_max)
for i in range(max_len):
buf += str(random.randint(0, 9))
return buf | [
"Generates a character string of digits. Number of digits are\n between self.num_digit_min and self.num_digit_max\n Returns\n -------\n str\n "
] |
Please provide a description of the function:def _gen_sample(self):
num_str = self.get_rand(self.num_digit_min, self.num_digit_max)
return self.captcha.image(num_str), num_str | [
"Generate a random captcha image sample\n Returns\n -------\n (numpy.ndarray, str)\n Tuple of image (numpy ndarray) and character string of digits used to generate the image\n "
] |
Please provide a description of the function:def register(klass):
assert(isinstance(klass, type))
name = klass.__name__.lower()
if name in Optimizer.opt_registry:
warnings.warn('WARNING: New optimizer %s.%s is overriding '
'existing optimizer %s.%s'... | [
"Registers a new optimizer.\n\n Once an optimizer is registered, we can create an instance of this\n optimizer with `create_optimizer` later.\n\n Examples\n --------\n\n >>> @mx.optimizer.Optimizer.register\n ... class MyOptimizer(mx.optimizer.Optimizer):\n ... p... |
Please provide a description of the function:def create_optimizer(name, **kwargs):
if name.lower() in Optimizer.opt_registry:
return Optimizer.opt_registry[name.lower()](**kwargs)
else:
raise ValueError('Cannot find optimizer %s' % name) | [
"Instantiates an optimizer with a given name and kwargs.\n\n .. note:: We can use the alias `create` for ``Optimizer.create_optimizer``.\n\n Parameters\n ----------\n name: str\n Name of the optimizer. Should be the name\n of a subclass of Optimizer. Case insensitiv... |
Please provide a description of the function:def create_state_multi_precision(self, index, weight):
weight_master_copy = None
if self.multi_precision and weight.dtype == numpy.float16:
weight_master_copy = weight.astype(numpy.float32)
return (weight_master_copy,) + (self... | [
"Creates auxiliary state for a given weight, including FP32 high\n precision copy if original weight is FP16.\n\n This method is provided to perform automatic mixed precision training\n for optimizers that do not support it themselves.\n\n Parameters\n ----------\n index : ... |
Please provide a description of the function:def update_multi_precision(self, index, weight, grad, state):
if self.multi_precision and weight.dtype == numpy.float16:
# Wrapper for mixed precision
weight_master_copy = state[0]
original_state = state[1]
gra... | [
"Updates the given parameter using the corresponding gradient and state.\n Mixed precision version.\n\n Parameters\n ----------\n index : int\n The unique index of the parameter into the individual learning\n rates and weight decays. Learning rates and weight decay\... |
Please provide a description of the function:def set_lr_mult(self, args_lr_mult):
self.lr_mult = {}
if self.sym_info:
attr, arg_names = self.sym_info
for name in arg_names:
if name in attr and '__lr_mult__' in attr[name]:
self.lr_mult[... | [
"Sets an individual learning rate multiplier for each parameter.\n\n If you specify a learning rate multiplier for a parameter, then\n the learning rate for the parameter will be set as the product of\n the global learning rate `self.lr` and its multiplier.\n\n .. note:: The default lear... |
Please provide a description of the function:def set_wd_mult(self, args_wd_mult):
self.wd_mult = {}
for n in self.idx2name.values():
if not (n.endswith('_weight') or n.endswith('_gamma')):
self.wd_mult[n] = 0.0
if self.sym_info:
attr, arg_names = ... | [
"Sets an individual weight decay multiplier for each parameter.\n\n By default, if `param_idx2name` was provided in the\n constructor, the weight decay multipler is set as 0 for all\n parameters whose name don't end with ``_weight`` or\n ``_gamma``.\n\n .. note:: The default weigh... |
Please provide a description of the function:def _set_current_context(self, device_id):
if device_id not in self._all_index_update_counts:
self._all_index_update_counts[device_id] = {}
self._index_update_count = self._all_index_update_counts[device_id] | [
"Sets the number of the currently handled device.\n\n Parameters\n ----------\n device_id : int\n The number of current device.\n "
] |
Please provide a description of the function:def _update_count(self, index):
if not isinstance(index, (list, tuple)):
index = [index]
for idx in index:
if idx not in self._index_update_count:
self._index_update_count[idx] = self.begin_num_update
... | [
"Updates num_update.\n\n Parameters\n ----------\n index : int or list of int\n The index to be updated.\n "
] |
Please provide a description of the function:def _get_lrs(self, indices):
if self.lr_scheduler is not None:
lr = self.lr_scheduler(self.num_update)
else:
lr = self.lr
lrs = [lr for _ in indices]
for i, index in enumerate(indices):
if index in... | [
"Gets the learning rates given the indices of the weights.\n\n Parameters\n ----------\n indices : list of int\n Indices corresponding to weights.\n\n Returns\n -------\n lrs : list of float\n Learning rates for those indices.\n "
] |
Please provide a description of the function:def _get_wds(self, indices):
wds = [self.wd for _ in indices]
for i, index in enumerate(indices):
if index in self.param_dict:
wds[i] *= self.param_dict[index].wd_mult
elif index in self.wd_mult:
... | [
"Gets weight decays for indices.\n Returns 0 for non-weights if the name of weights are provided for `__init__`.\n\n Parameters\n ----------\n indices : list of int\n Indices of weights.\n\n Returns\n -------\n wds : list of float\n Weight decay... |
Please provide a description of the function:def sync_state_context(self, state, context):
if isinstance(state, NDArray):
return state.as_in_context(context)
elif isinstance(state, (tuple, list)):
synced_state = (self.sync_state_context(i, context) for i in state)
... | [
"sync state context."
] |
Please provide a description of the function:def set_states(self, states):
states = pickle.loads(states)
if isinstance(states, tuple) and len(states) == 2:
self.states, self.optimizer = states
else:
self.states = states
self.states_synced = dict.fromkeys(... | [
"Sets updater states."
] |
Please provide a description of the function:def get_states(self, dump_optimizer=False):
return pickle.dumps((self.states, self.optimizer) if dump_optimizer else self.states) | [
"Gets updater states.\n\n Parameters\n ----------\n dump_optimizer : bool, default False\n Whether to also save the optimizer itself. This would also save optimizer\n information such as learning rate and weight decay schedules.\n "
] |
Please provide a description of the function:def preprocess(from_idx, to_idx, _params):
source_exts = '*.mpg'
src_path = _params['src_path']
tgt_path = _params['tgt_path']
face_predictor_path = './shape_predictor_68_face_landmarks.dat'
succ = set()
fail = set()
for idx in range(from_id... | [
"\n Preprocess: Convert a video into the mouth images\n "
] |
Please provide a description of the function:def from_frames(self, path):
frames_path = sorted([os.path.join(path, x) for x in os.listdir(path)])
frames = [ndimage.imread(frame_path) for frame_path in frames_path]
self.handle_type(frames)
return self | [
"\n Read from frames\n "
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.