Code stringlengths 103 85.9k | Summary listlengths 0 94 |
|---|---|
Please provide a description of the function:def empty(stype, shape, ctx=None, dtype=None):
if isinstance(shape, int):
shape = (shape, )
if ctx is None:
ctx = current_context()
if dtype is None:
dtype = mx_real_t
assert(stype is not None)
if stype in ('csr', 'row_sparse'... | [
"Returns a new array of given shape and type, without initializing entries.\n\n Parameters\n ----------\n stype: string\n The storage type of the empty array, such as 'row_sparse', 'csr', etc\n shape : int or tuple of int\n The shape of the empty array.\n ctx : Context, optional\n ... |
Please provide a description of the function:def array(source_array, ctx=None, dtype=None):
ctx = current_context() if ctx is None else ctx
if isinstance(source_array, NDArray):
assert(source_array.stype != 'default'), \
"Please use `tostype` to create RowSparseNDArray or CSRNDArray ... | [
"Creates a sparse array from any object exposing the array interface.\n\n Parameters\n ----------\n source_array : RowSparseNDArray, CSRNDArray or scipy.sparse.csr.csr_matrix\n The source sparse array\n ctx : Context, optional\n The default context is ``source_array.context`` if ``source_a... |
Please provide a description of the function:def _aux_type(self, i):
aux_type = ctypes.c_int()
check_call(_LIB.MXNDArrayGetAuxType(self.handle, i, ctypes.byref(aux_type)))
return _DTYPE_MX_TO_NP[aux_type.value] | [
"Data-type of the array's ith aux data.\n\n Returns\n -------\n numpy.dtype\n This BaseSparseNDArray's aux data type.\n "
] |
Please provide a description of the function:def _aux_types(self):
aux_types = []
num_aux = self._num_aux
for i in range(num_aux):
aux_types.append(self._aux_type(i))
return aux_types | [
"The data types of the aux data for the BaseSparseNDArray.\n "
] |
Please provide a description of the function:def astype(self, dtype, copy=True):
if not copy and np.dtype(dtype) == self.dtype:
return self
res = zeros(shape=self.shape, ctx=self.context,
dtype=dtype, stype=self.stype)
self.copyto(res)
return res | [
"Return a copy of the array after casting to a specified type.\n\n Parameters\n ----------\n dtype : numpy.dtype or str\n The type of the returned array.\n copy : bool\n Default `True`. By default, astype always returns a newly\n allocated ndarray on the ... |
Please provide a description of the function:def check_format(self, full_check=True):
check_call(_LIB.MXNDArraySyncCheckFormat(self.handle, ctypes.c_bool(full_check))) | [
"Check whether the NDArray format is valid.\n\n Parameters\n ----------\n full_check : bool, optional\n If `True`, rigorous check, O(N) operations. Otherwise\n basic check, O(1) operations (default True).\n "
] |
Please provide a description of the function:def _data(self):
self.wait_to_read()
hdl = NDArrayHandle()
check_call(_LIB.MXNDArrayGetDataNDArray(self.handle, ctypes.byref(hdl)))
return NDArray(hdl) | [
"A deep copy NDArray of the data array associated with the BaseSparseNDArray.\n\n This function blocks. Do not use it in performance critical code.\n "
] |
Please provide a description of the function:def _aux_data(self, i):
self.wait_to_read()
hdl = NDArrayHandle()
check_call(_LIB.MXNDArrayGetAuxNDArray(self.handle, i, ctypes.byref(hdl)))
return NDArray(hdl) | [
" Get a deep copy NDArray of the i-th aux data array associated with the\n BaseSparseNDArray.\n\n This function blocks. Do not use it in performance critical code.\n "
] |
Please provide a description of the function:def asscipy(self):
data = self.data.asnumpy()
indices = self.indices.asnumpy()
indptr = self.indptr.asnumpy()
if not spsp:
raise ImportError("scipy is not available. \
Please check if the sci... | [
"Returns a ``scipy.sparse.csr.csr_matrix`` object with value copied from this array\n\n Examples\n --------\n >>> x = mx.nd.sparse.zeros('csr', (2,3))\n >>> y = x.asscipy()\n >>> type(y)\n <type 'scipy.sparse.csr.csr_matrix'>\n >>> y\n <2x3 sparse matrix of ty... |
Please provide a description of the function:def tostype(self, stype):
# pylint: disable= no-member, protected-access
if stype == 'csr':
raise ValueError("cast_storage from row_sparse to csr is not supported")
return op.cast_storage(self, stype=stype) | [
"Return a copy of the array with chosen storage type.\n\n Returns\n -------\n NDArray or RowSparseNDArray\n A copy of the array with the chosen storage stype\n "
] |
Please provide a description of the function:def copyto(self, other):
if isinstance(other, Context):
return super(RowSparseNDArray, self).copyto(other)
elif isinstance(other, NDArray):
stype = other.stype
if stype in ('default', 'row_sparse'):
... | [
"Copies the value of this array to another array.\n\n If ``other`` is a ``NDArray`` or ``RowSparseNDArray`` object, then ``other.shape``\n and ``self.shape`` should be the same. This function copies the value from\n ``self`` to ``other``.\n\n If ``other`` is a context, a new ``RowSparseN... |
Please provide a description of the function:def export_model(sym, params, input_shape, input_type=np.float32,
onnx_file_path='model.onnx', verbose=False):
try:
from onnx import helper, mapping
except ImportError:
raise ImportError("Onnx and protobuf need to be installed. ... | [
"Exports the MXNet model file, passed as a parameter, into ONNX model.\n Accepts both symbol,parameter objects as well as json and params filepaths as input.\n Operator support and coverage -\n https://cwiki.apache.org/confluence/display/MXNET/MXNet-ONNX+Integration\n\n Parameters\n ----------\n s... |
Please provide a description of the function:def bench_dot(lhs_row_dim, lhs_col_dim, rhs_col_dim, density,
rhs_density, dot_func, trans_lhs, lhs_stype,
rhs_stype, only_storage, distribution="uniform"):
lhs_nd = rand_ndarray((lhs_row_dim, lhs_col_dim), lhs_stype, density, distributio... | [
" Benchmarking both storage and dot\n "
] |
Please provide a description of the function:def convert_mean(binaryproto_fname, output=None):
mean_blob = caffe_parser.caffe_pb2.BlobProto()
with open(binaryproto_fname, 'rb') as f:
mean_blob.ParseFromString(f.read())
img_mean_np = np.array(mean_blob.data)
img_mean_np = img_mean_np.reshap... | [
"Convert caffe mean\n\n Parameters\n ----------\n binaryproto_fname : str\n Filename of the mean\n output : str, optional\n Save the mean into mxnet's format\n\n Returns\n -------\n NDArray\n Mean in ndarray\n "
] |
Please provide a description of the function:def get_densenet(num_layers, pretrained=False, ctx=cpu(),
root=os.path.join(base.data_dir(), 'models'), **kwargs):
r
num_init_features, growth_rate, block_config = densenet_spec[num_layers]
net = DenseNet(num_init_features, growth_rate, block_con... | [
"Densenet-BC model from the\n `\"Densely Connected Convolutional Networks\" <https://arxiv.org/pdf/1608.06993.pdf>`_ paper.\n\n Parameters\n ----------\n num_layers : int\n Number of layers for the variant of densenet. Options are 121, 161, 169, 201.\n pretrained : bool, default False\n ... |
Please provide a description of the function:def load_module(sym_filepath, params_filepath):
if not (os.path.isfile(sym_filepath) and os.path.isfile(params_filepath)):
raise ValueError("Symbol and params files provided are invalid")
else:
try:
# reads symbol.json file from given... | [
"Loads the MXNet model file and\n returns MXNet symbol and params (weights).\n\n Parameters\n ----------\n json_path : str\n Path to the json file\n params_path : str\n Path to the params file\n\n Returns\n -------\n sym : MXNet symbol\n Model symbol object\n\n params... |
Please provide a description of the function:def import_module(module_name):
import sys, os
import importlib
sys.path.append(os.path.dirname(__file__))
return importlib.import_module(module_name) | [
"Helper function to import module"
] |
Please provide a description of the function:def get_symbol_train(network, num_classes, from_layers, num_filters, strides, pads,
sizes, ratios, normalizations=-1, steps=[], min_filter=128,
nms_thresh=0.5, force_suppress=False, nms_topk=400, **kwargs):
label = mx.sym.Va... | [
"Build network symbol for training SSD\n\n Parameters\n ----------\n network : str\n base network symbol name\n num_classes : int\n number of object classes not including background\n from_layers : list of str\n feature extraction layers, use '' for add extra layers\n For ... |
Please provide a description of the function:def get_symbol(network, num_classes, from_layers, num_filters, sizes, ratios,
strides, pads, normalizations=-1, steps=[], min_filter=128,
nms_thresh=0.5, force_suppress=False, nms_topk=400, **kwargs):
body = import_module(network).get_s... | [
"Build network for testing SSD\n\n Parameters\n ----------\n network : str\n base network symbol name\n num_classes : int\n number of object classes not including background\n from_layers : list of str\n feature extraction layers, use '' for add extra layers\n For example:... |
Please provide a description of the function:def _get_grad(net, image, class_id=None, conv_layer_name=None, image_grad=False):
if image_grad:
image.attach_grad()
Conv2D.capture_layer_name = None
Activation.set_guided_backprop(True)
else:
# Tell convviz.Conv2D which layer's ... | [
"This is an internal helper function that can be used for either of these\n but not both at the same time:\n 1. Record the output and gradient of output of an intermediate convolutional layer.\n 2. Record the gradients of the image.\n\n Parameters\n ----------\n image : NDArray\n Image to v... |
Please provide a description of the function:def get_conv_out_grad(net, image, class_id=None, conv_layer_name=None):
return _get_grad(net, image, class_id, conv_layer_name, image_grad=False) | [
"Get the output and gradients of output of a convolutional layer.\n\n Parameters:\n ----------\n net: Block\n Network to use for visualization.\n image: NDArray\n Preprocessed image to use for visualization.\n class_id: int\n Category ID this image belongs to. If not provided,\n ... |
Please provide a description of the function:def get_image_grad(net, image, class_id=None):
return _get_grad(net, image, class_id, image_grad=True) | [
"Get the gradients of the image.\n\n Parameters:\n ----------\n net: Block\n Network to use for visualization.\n image: NDArray\n Preprocessed image to use for visualization.\n class_id: int\n Category ID this image belongs to. If not provided,\n network's prediction will ... |
Please provide a description of the function:def grad_to_image(gradient):
gradient = gradient - gradient.min()
gradient /= gradient.max()
gradient = np.uint8(gradient * 255).transpose(1, 2, 0)
gradient = gradient[..., ::-1]
return gradient | [
"Convert gradients of image obtained using `get_image_grad`\n into image. This shows parts of the image that is most strongly activating\n the output neurons."
] |
Please provide a description of the function:def get_cam(imggrad, conv_out):
weights = np.mean(imggrad, axis=(1, 2))
cam = np.ones(conv_out.shape[1:], dtype=np.float32)
for i, w in enumerate(weights):
cam += w * conv_out[i, :, :]
cam = cv2.resize(cam, (imggrad.shape[1], imggrad.shape[2]))
... | [
"Compute CAM. Refer section 3 of https://arxiv.org/abs/1610.02391 for details"
] |
Please provide a description of the function:def get_img_heatmap(orig_img, activation_map):
heatmap = cv2.applyColorMap(activation_map, cv2.COLORMAP_COOL)
heatmap = cv2.cvtColor(heatmap, cv2.COLOR_BGR2RGB)
img_heatmap = np.float32(heatmap) + np.float32(orig_img)
img_heatmap = img_heatmap / np.max(i... | [
"Draw a heatmap on top of the original image using intensities from activation_map"
] |
Please provide a description of the function:def to_grayscale(cv2im):
# How strongly does each position activate the output
grayscale_im = np.sum(np.abs(cv2im), axis=0)
# Normalize between min and 99th percentile
im_max = np.percentile(grayscale_im, 99)
im_min = np.min(grayscale_im)
graysc... | [
"Convert gradients to grayscale. This gives a saliency map."
] |
Please provide a description of the function:def check_label_shapes(labels, preds, wrap=False, shape=False):
if not shape:
label_shape, pred_shape = len(labels), len(preds)
else:
label_shape, pred_shape = labels.shape, preds.shape
if label_shape != pred_shape:
raise ValueError(... | [
"Helper function for checking shape of label and prediction\n\n Parameters\n ----------\n labels : list of `NDArray`\n The labels of the data.\n\n preds : list of `NDArray`\n Predicted values.\n\n wrap : boolean\n If True, wrap labels/preds in a list if they are single NDArray\n\... |
Please provide a description of the function:def create(metric, *args, **kwargs):
if callable(metric):
return CustomMetric(metric, *args, **kwargs)
elif isinstance(metric, list):
composite_metric = CompositeEvalMetric()
for child_metric in metric:
composite_metric.add(cr... | [
"Creates evaluation metric from metric names or instances of EvalMetric\n or a custom metric function.\n\n Parameters\n ----------\n metric : str or callable\n Specifies the metric to create.\n This argument must be one of the below:\n\n - Name of a metric.\n - An instance of... |
Please provide a description of the function:def np(numpy_feval, name=None, allow_extra_outputs=False):
def feval(label, pred):
return numpy_feval(label, pred)
feval.__name__ = numpy_feval.__name__
return CustomMetric(feval, name, allow_extra_outputs) | [
"Creates a custom evaluation metric that receives its inputs as numpy arrays.\n\n Parameters\n ----------\n numpy_feval : callable(label, pred)\n Custom evaluation function that receives labels and predictions for a minibatch\n as numpy arrays and returns the corresponding custom metric as a ... |
Please provide a description of the function:def get_config(self):
config = self._kwargs.copy()
config.update({
'metric': self.__class__.__name__,
'name': self.name,
'output_names': self.output_names,
'label_names': self.label_names})
retu... | [
"Save configurations of metric. Can be recreated\n from configs with metric.create(``**config``)\n "
] |
Please provide a description of the function:def update_dict(self, label, pred):
if self.output_names is not None:
pred = [pred[name] for name in self.output_names]
else:
pred = list(pred.values())
if self.label_names is not None:
label = [label[name... | [
"Update the internal evaluation with named label and pred\n\n Parameters\n ----------\n labels : OrderedDict of str -> NDArray\n name to array mapping for labels.\n\n preds : OrderedDict of str -> NDArray\n name to array mapping of predicted outputs.\n "
] |
Please provide a description of the function:def reset(self):
self.num_inst = 0
self.sum_metric = 0.0
self.global_num_inst = 0
self.global_sum_metric = 0.0 | [
"Resets the internal evaluation result to initial state."
] |
Please provide a description of the function:def get(self):
if self.num_inst == 0:
return (self.name, float('nan'))
else:
return (self.name, self.sum_metric / self.num_inst) | [
"Gets the current evaluation result.\n\n Returns\n -------\n names : list of str\n Name of the metrics.\n values : list of float\n Value of the evaluations.\n "
] |
Please provide a description of the function:def get_global(self):
if self._has_global_stats:
if self.global_num_inst == 0:
return (self.name, float('nan'))
else:
return (self.name, self.global_sum_metric / self.global_num_inst)
else:
... | [
"Gets the current global evaluation result.\n\n Returns\n -------\n names : list of str\n Name of the metrics.\n values : list of float\n Value of the evaluations.\n "
] |
Please provide a description of the function:def get_name_value(self):
name, value = self.get()
if not isinstance(name, list):
name = [name]
if not isinstance(value, list):
value = [value]
return list(zip(name, value)) | [
"Returns zipped name and value pairs.\n\n Returns\n -------\n list of tuples\n A (name, value) tuple list.\n "
] |
Please provide a description of the function:def get_global_name_value(self):
if self._has_global_stats:
name, value = self.get_global()
if not isinstance(name, list):
name = [name]
if not isinstance(value, list):
value = [value]
... | [
"Returns zipped name and value pairs for global results.\n\n Returns\n -------\n list of tuples\n A (name, value) tuple list.\n "
] |
Please provide a description of the function:def update_binary_stats(self, label, pred):
pred = pred.asnumpy()
label = label.asnumpy().astype('int32')
pred_label = numpy.argmax(pred, axis=1)
check_label_shapes(label, pred)
if len(numpy.unique(label)) > 2:
ra... | [
"\n Update various binary classification counts for a single (label, pred)\n pair.\n\n Parameters\n ----------\n label : `NDArray`\n The labels of the data.\n\n pred : `NDArray`\n Predicted values.\n "
] |
Please provide a description of the function:def matthewscc(self, use_global=False):
if use_global:
if not self.global_total_examples:
return 0.
true_pos = float(self.global_true_positives)
false_pos = float(self.global_false_positives)
f... | [
"\n Calculate the Matthew's Correlation Coefficent\n "
] |
Please provide a description of the function:def transform(self, fn, lazy=True):
trans = _LazyTransformDataset(self, fn)
if lazy:
return trans
return SimpleDataset([i for i in trans]) | [
"Returns a new dataset with each sample transformed by the\n transformer function `fn`.\n\n Parameters\n ----------\n fn : callable\n A transformer function that takes a sample as input and\n returns the transformed sample.\n lazy : bool, default True\n ... |
Please provide a description of the function:def transform_first(self, fn, lazy=True):
return self.transform(_TransformFirstClosure(fn), lazy) | [
"Returns a new dataset with the first element of each sample\n transformed by the transformer function `fn`.\n\n This is useful, for example, when you only want to transform data\n while keeping label as is.\n\n Parameters\n ----------\n fn : callable\n A transfo... |
Please provide a description of the function:def forward_ocr(self, img_):
img_ = cv2.resize(img_, (80, 30))
img_ = img_.transpose(1, 0)
print(img_.shape)
img_ = img_.reshape((1, 80, 30))
print(img_.shape)
# img_ = img_.reshape((80 * 30))
img_ = np.multipl... | [
"Forward the image through the LSTM network model\n\n Parameters\n ----------\n img_: int of array\n\n Returns\n ----------\n label_list: string of list\n "
] |
Please provide a description of the function:def read_prototxt(fname):
proto = caffe_pb2.NetParameter()
with open(fname, 'r') as f:
text_format.Merge(str(f.read()), proto)
return proto | [
"Return a caffe_pb2.NetParameter object that defined in a prototxt file\n "
] |
Please provide a description of the function:def get_layers(proto):
if len(proto.layer):
return proto.layer
elif len(proto.layers):
return proto.layers
else:
raise ValueError('Invalid proto file.') | [
"Returns layers in a caffe_pb2.NetParameter object\n "
] |
Please provide a description of the function:def read_caffemodel(prototxt_fname, caffemodel_fname):
if use_caffe:
caffe.set_mode_cpu()
net = caffe.Net(prototxt_fname, caffemodel_fname, caffe.TEST)
layer_names = net._layer_names
layers = net.layers
return (layers, layer_n... | [
"Return a caffe_pb2.NetParameter object that defined in a binary\n caffemodel file\n "
] |
Please provide a description of the function:def layer_iter(layers, layer_names):
if use_caffe:
for layer_idx, layer in enumerate(layers):
layer_name = re.sub('[-/]', '_', layer_names[layer_idx])
layer_type = layer.type
layer_blobs = layer.blobs
yield (la... | [
"Iterate over all layers"
] |
Please provide a description of the function:def set_config(**kwargs):
kk = kwargs.keys()
vv = kwargs.values()
check_call(_LIB.MXSetProcessProfilerConfig(len(kwargs),
c_str_array([key for key in kk]),
c_str_ar... | [
"Set up the configure of profiler (only accepts keyword arguments).\n\n Parameters\n ----------\n filename : string,\n output file for profile data\n profile_all : boolean,\n all profile types enabled\n profile_symbolic : boolean,\n whether to profile symbolic operators\n prof... |
Please provide a description of the function:def profiler_set_config(mode='symbolic', filename='profile.json'):
warnings.warn('profiler.profiler_set_config() is deprecated. '
'Please use profiler.set_config() instead')
keys = c_str_array([key for key in ["profile_" + mode, "filename"]])
... | [
"Set up the configure of profiler (Deprecated).\n\n Parameters\n ----------\n mode : string, optional\n Indicates whether to enable the profiler, can\n be 'symbolic', or 'all'. Defaults to `symbolic`.\n filename : string, optional\n The name of output trace file. Defaults to 'profil... |
Please provide a description of the function:def set_state(state='stop', profile_process='worker'):
state2int = {'stop': 0, 'run': 1}
profile_process2int = {'worker': 0, 'server': 1}
check_call(_LIB.MXSetProcessProfilerState(ctypes.c_int(state2int[state]),
... | [
"Set up the profiler state to 'run' or 'stop'.\n\n Parameters\n ----------\n state : string, optional\n Indicates whether to run the profiler, can\n be 'stop' or 'run'. Default is `stop`.\n profile_process : string\n whether to profile kvstore `server` or `worker`.\n server c... |
Please provide a description of the function:def dump(finished=True, profile_process='worker'):
fin = 1 if finished is True else 0
profile_process2int = {'worker': 0, 'server': 1}
check_call(_LIB.MXDumpProcessProfile(fin,
profile_process2int[profile_process],
... | [
"Dump profile and stop profiler. Use this to save profile\n in advance in case your program cannot exit normally.\n\n Parameters\n ----------\n finished : boolean\n Indicates whether to stop statistic output (dumping) after this dump.\n Default is True\n profile_process : string\n ... |
Please provide a description of the function:def dumps(reset=False):
debug_str = ctypes.c_char_p()
do_reset = 1 if reset is True else 0
check_call(_LIB.MXAggregateProfileStatsPrint(ctypes.byref(debug_str), int(do_reset)))
return py_str(debug_str.value) | [
"Return a printable string of aggregate profile stats.\n\n Parameters\n ----------\n reset: boolean\n Indicates whether to clean aggeregate statistical data collected up to this point\n "
] |
Please provide a description of the function:def pause(profile_process='worker'):
profile_process2int = {'worker': 0, 'server': 1}
check_call(_LIB.MXProcessProfilePause(int(1),
profile_process2int[profile_process],
profiler... | [
"Pause profiling.\n\n Parameters\n ----------\n profile_process : string\n whether to profile kvstore `server` or `worker`.\n server can only be profiled when kvstore is of type dist.\n if this is not passed, defaults to `worker`\n "
] |
Please provide a description of the function:def resume(profile_process='worker'):
profile_process2int = {'worker': 0, 'server': 1}
check_call(_LIB.MXProcessProfilePause(int(0),
profile_process2int[profile_process],
profile... | [
"\n Resume paused profiling.\n\n Parameters\n ----------\n profile_process : string\n whether to profile kvstore `server` or `worker`.\n server can only be profiled when kvstore is of type dist.\n if this is not passed, defaults to `worker`\n "
] |
Please provide a description of the function:def set_value(self, value):
check_call(_LIB.MXProfileSetCounter(self.handle, int(value))) | [
"Set counter value.\n\n Parameters\n ----------\n value : int\n Value for the counter\n "
] |
Please provide a description of the function:def increment(self, delta=1):
check_call(_LIB.MXProfileAdjustCounter(self.handle, int(delta))) | [
"Increment counter value.\n\n Parameters\n ----------\n value_change : int\n Amount by which to add to the counter\n "
] |
Please provide a description of the function:def decrement(self, delta=1):
check_call(_LIB.MXProfileAdjustCounter(self.handle, -int(delta))) | [
"Decrement counter value.\n\n Parameters\n ----------\n value_change : int\n Amount by which to subtract from the counter\n "
] |
Please provide a description of the function:def mark(self, scope='process'):
check_call(_LIB.MXProfileSetMarker(self.domain.handle, c_str(self.name), c_str(scope))) | [
"Set up the profiler state to record operator.\n\n Parameters\n ----------\n scope : string, optional\n Indicates what scope the marker should refer to.\n Can be 'global', 'process', thread', task', and 'marker'\n Default is `process`.\n "
] |
Please provide a description of the function:def get_kernel(self, name, signature):
r
hdl = CudaKernelHandle()
is_ndarray = []
is_const = []
dtypes = []
pattern = re.compile(r)
args = re.sub(r"\s+", " ", signature).split(",")
for arg in args:
m... | [
"Get CUDA kernel from compiled module.\n\n Parameters\n ----------\n name : str\n String name of the kernel.\n signature : str\n Function signature for the kernel. For example, if a kernel is\n declared as::\n\n extern \"C\" __global__ void... |
Please provide a description of the function:def launch(self, args, ctx, grid_dims, block_dims, shared_mem=0):
assert ctx.device_type == 'gpu', "Cuda kernel can only be launched on GPU"
assert len(grid_dims) == 3, "grid_dims must be a tuple of 3 integers"
assert len(block_dims) == 3, "g... | [
"Launch cuda kernel.\n\n Parameters\n ----------\n args : tuple of NDArray or numbers\n List of arguments for kernel. NDArrays are expected for pointer\n types (e.g. `float*`, `double*`) while numbers are expected for\n non-pointer types (e.g. `int`, `float`).\n... |
Please provide a description of the function:def reset(self):
if getattr(self, 'num', None) is None:
self.num_inst = 0
self.sum_metric = 0.0
else:
self.num_inst = [0] * self.num
self.sum_metric = [0.0] * self.num
self.records = dict()
... | [
"Clear the internal statistics to initial state."
] |
Please provide a description of the function:def update(self, labels, preds):
def iou(x, ys):
ixmin = np.maximum(ys[:, 0], x[0])
iymin = np.maximum(ys[:, 1], x[1])
ixmax = np.minimum(ys[:, 2], x[2])
iymax = np.minimum(ys[:, 3], x[3])
... | [
"\n Update internal records. This function now only update internal buffer,\n sum_metric and num_inst are updated in _update() function instead when\n get() is called to return results.\n\n Params:\n ----------\n labels: mx.nd.array (n * 6) or (n * 5), difficult column is o... |
Please provide a description of the function:def _update(self):
aps = []
for k, v in self.records.items():
recall, prec = self._recall_prec(v, self.counts[k])
ap = self._average_precision(recall, prec)
aps.append(ap)
if self.num is not None and k ... | [
" update num_inst and sum_metric "
] |
Please provide a description of the function:def _recall_prec(self, record, count):
record = np.delete(record, np.where(record[:, 1].astype(int) == 0)[0], axis=0)
sorted_records = record[record[:,0].argsort()[::-1]]
tp = np.cumsum(sorted_records[:, 1].astype(int) == 1)
fp = np.c... | [
" get recall and precision from internal records "
] |
Please provide a description of the function:def _average_precision(self, rec, prec):
# append sentinel values at both ends
mrec = np.concatenate(([0.], rec, [1.]))
mpre = np.concatenate(([0.], prec, [0.]))
# compute precision integration ladder
for i in range(mpre.size... | [
"\n calculate average precision\n\n Params:\n ----------\n rec : numpy.array\n cumulated recall\n prec : numpy.array\n cumulated precision\n Returns:\n ----------\n ap as float\n "
] |
Please provide a description of the function:def _insert(self, key, records, count):
if key not in self.records:
assert key not in self.counts
self.records[key] = records
self.counts[key] = count
else:
self.records[key] = np.vstack((self.records[k... | [
" Insert records according to key "
] |
Please provide a description of the function:def _average_precision(self, rec, prec):
ap = 0.
for t in np.arange(0., 1.1, 0.1):
if np.sum(rec >= t) == 0:
p = 0
else:
p = np.max(prec[rec >= t])
ap += p / 11.
return ap | [
"\n calculate average precision, override the default one,\n special 11-point metric\n\n Params:\n ----------\n rec : numpy.array\n cumulated recall\n prec : numpy.array\n cumulated precision\n Returns:\n ----------\n ap as float\n... |
Please provide a description of the function:def get_fine_tune_model(symbol, arg_params, num_classes, layer_name, dtype='float32'):
all_layers = symbol.get_internals()
net = all_layers[layer_name+'_output']
net = mx.symbol.FullyConnected(data=net, num_hidden=num_classes, name='fc')
if dtype == 'flo... | [
"\n symbol: the pre-trained network symbol\n arg_params: the argument parameters of the pre-trained model\n num_classes: the number of classes for the fine-tune datasets\n layer_name: the layer name before the last fully-connected layer\n "
] |
Please provide a description of the function:def _list_images(self, root):
self.labels = []
self.items = []
valid_unseen_sub_idx = [1, 2, 20, 22]
skip_sub_idx = [21]
if self._mode == 'train':
sub_idx = ['s' + str(i) for i in range(1, 35) \
... | [
"\n Description : generate list for lip images\n "
] |
Please provide a description of the function:def align_generation(self, file_nm, padding=75):
align = Align(self._align_root + '/' + file_nm + '.align')
return nd.array(align.sentence(padding)) | [
"\n Description : Align to lip position\n "
] |
Please provide a description of the function:def set_verbosity(self, verbose=False, print_func=None):
self._verbose = verbose
if print_func is None:
def asum_stat(x):
return str((ndarray.norm(x)/sqrt(x.size)).asscalar())
print_func = asum... | [
"Switch on/off verbose mode\n\n Parameters\n ----------\n verbose : bool\n switch on/off verbose mode\n print_func : function\n A function that computes statistics of initialized arrays.\n Takes an `NDArray` and returns an `str`. Defaults to mean\n ... |
Please provide a description of the function:def _verbose_print(self, desc, init, arr):
if self._verbose and self._print_func:
logging.info('Initialized %s as %s: %s', desc, init, self._print_func(arr)) | [
"Internal verbose print function\n\n Parameters\n ----------\n desc : InitDesc or str\n name of the array\n init : str\n initializer pattern\n arr : NDArray\n initialized array\n "
] |
Please provide a description of the function:def _legacy_init(self, name, arr):
warnings.warn(
"\033[91mCalling initializer with init(str, NDArray) has been deprecated." \
"please use init(mx.init.InitDesc(...), NDArray) instead.\033[0m",
DeprecationWarning, stacklev... | [
"Legacy initialization method.\n\n Parameters\n ----------\n name : str\n Name of corresponding NDArray.\n\n arr : NDArray\n NDArray to be initialized.\n "
] |
Please provide a description of the function:def save_imglist(self, fname=None, root=None, shuffle=False):
def progress_bar(count, total, suffix=''):
import sys
bar_len = 24
filled_len = int(round(bar_len * count / float(total)))
percents = round(100.0 *... | [
"\n save imglist to disk\n\n Parameters:\n ----------\n fname : str\n saved filename\n "
] |
Please provide a description of the function:def _load_class_names(self, filename, dirname):
full_path = osp.join(dirname, filename)
classes = []
with open(full_path, 'r') as f:
classes = [l.strip() for l in f.readlines()]
return classes | [
"\n load class names from text file\n\n Parameters:\n ----------\n filename: str\n file stores class names\n dirname: str\n file directory\n "
] |
Please provide a description of the function:def read_data(label, image):
base_url = 'http://yann.lecun.com/exdb/mnist/'
with gzip.open(download_file(base_url+label, os.path.join('data',label))) as flbl:
magic, num = struct.unpack(">II", flbl.read(8))
label = np.fromstring(flbl.read(), dtyp... | [
"\n download and read data into numpy\n "
] |
Please provide a description of the function:def get_mnist_iter(args, kv):
(train_lbl, train_img) = read_data(
'train-labels-idx1-ubyte.gz', 'train-images-idx3-ubyte.gz')
(val_lbl, val_img) = read_data(
't10k-labels-idx1-ubyte.gz', 't10k-images-idx3-ubyte.gz')
train = mx.io.NDAr... | [
"\n create data iterator with NDArrayIter\n "
] |
Please provide a description of the function:def make_file_extension_assertion(extension):
def file_extension_assertion(file_path):
base, ext = os.path.splitext(file_path)
if ext.lower() != extension:
raise argparse.ArgumentTypeError('File must have ' + extension + ' extension')
... | [
"Function factory for file extension argparse assertion\n Args:\n extension (string): the file extension to assert\n\n Returns:\n string: the supplied extension, if assertion is successful.\n\n "
] |
Please provide a description of the function:def get_palette(num_colors=256):
pallete = [0]*(num_colors*3)
for j in range(0, num_colors):
lab = j
pallete[j*3+0] = 0
pallete[j*3+1] = 0
pallete[j*3+2] = 0
i = 0
while (lab > 0):
pallete[j*3+0] |= (((... | [
"generates the colormap for visualizing the segmentation mask\n Args:\n num_colors (int): the number of colors to generate in the output palette\n\n Returns:\n string: the supplied extension, if assertion is successful.\n\n "
] |
Please provide a description of the function:def get_data(img_path):
mean = np.array([123.68, 116.779, 103.939]) # (R,G,B)
img = Image.open(img_path)
img = np.array(img, dtype=np.float32)
reshaped_mean = mean.reshape(1, 1, 3)
img = img - reshaped_mean
img = np.swapaxes(img, 0, 2)
img =... | [
"get the (1, 3, h, w) np.array data for the supplied image\n Args:\n img_path (string): the input image path\n\n Returns:\n np.array: image data in a (1, 3, h, w) shape\n\n "
] |
Please provide a description of the function:def main():
# Initialization variables - update to change your model and execution context
model_prefix = "FCN8s_VGG16"
epoch = 19
# By default, MXNet will run on the CPU. Change to ctx = mx.gpu() to run on GPU.
ctx = mx.cpu()
fcnxs, fcnxs_args... | [
"Module main execution"
] |
Please provide a description of the function:def _check_classes(self):
try:
self.classes = self.imdbs[0].classes
self.num_classes = len(self.classes)
except AttributeError:
# fine, if no classes is provided
pass
if self.num_classes > 0:
... | [
"\n check input imdbs, make sure they have same classes\n "
] |
Please provide a description of the function:def _load_image_set_index(self, shuffle):
self.num_images = 0
for db in self.imdbs:
self.num_images += db.num_images
indices = list(range(self.num_images))
if shuffle:
random.shuffle(indices)
return ind... | [
"\n get total number of images, init indices\n\n Parameters\n ----------\n shuffle : bool\n whether to shuffle the initial indices\n "
] |
Please provide a description of the function:def _locate_index(self, index):
assert index >= 0 and index < self.num_images, "index out of range"
pos = self.image_set_index[index]
for k, v in enumerate(self.imdbs):
if pos >= v.num_images:
pos -= v.num_images
... | [
"\n given index, find out sub-db and sub-index\n\n Parameters\n ----------\n index : int\n index of a specific image\n\n Returns\n ----------\n a tuple (sub-db, sub-index)\n "
] |
Please provide a description of the function:def image_path_from_index(self, index):
assert self.image_set_index is not None, "Dataset not initialized"
pos = self.image_set_index[index]
n_db, n_index = self._locate_index(index)
return self.imdbs[n_db].image_path_from_index(n_ind... | [
"\n given image index, find out full path\n\n Parameters\n ----------\n index: int\n index of a specific image\n\n Returns\n ----------\n full path of this image\n "
] |
Please provide a description of the function:def module_checkpoint(mod, prefix, period=1, save_optimizer_states=False):
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:
mod.s... | [
"Callback to checkpoint Module to prefix every epoch.\n\n Parameters\n ----------\n mod : subclass of BaseModule\n The module to checkpoint.\n prefix : str\n The file prefix for this checkpoint.\n period : int\n How many epochs to wait before checkpointing. Defaults to 1.\n sa... |
Please provide a description of the function:def do_checkpoint(prefix, period=1):
period = int(max(1, period))
def _callback(iter_no, sym, arg, aux):
if (iter_no + 1) % period == 0:
save_checkpoint(prefix, iter_no + 1, sym, arg, aux)
return _callback | [
"A callback that saves a model checkpoint every few epochs.\n Each checkpoint is made up of a couple of binary files: a model description file and a\n parameters (weights and biases) file. The model description file is named\n `prefix`--symbol.json and the parameters file is named `prefix`-`epoch_number`.p... |
Please provide a description of the function:def log_train_metric(period, auto_reset=False):
def _callback(param):
if param.nbatch % period == 0 and param.eval_metric is not None:
name_value = param.eval_metric.get_name_value()
for name, value in name_value:
... | [
"Callback to log the training evaluation result every period.\n\n Parameters\n ----------\n period : int\n The number of batch to log the training evaluation metric.\n auto_reset : bool\n Reset the metric after each log.\n\n Returns\n -------\n callback : function\n The cal... |
Please provide a description of the function:def install(self, exe):
exe.set_monitor_callback(self.stat_helper, self.monitor_all)
self.exes.append(exe) | [
"install callback to executor.\n Supports installing to multiple exes.\n\n Parameters\n ----------\n exe : mx.executor.Executor\n The Executor (returned by symbol.bind) to install to.\n "
] |
Please provide a description of the function:def tic(self):
if self.step % self.interval == 0:
for exe in self.exes:
for array in exe.arg_arrays:
array.wait_to_read()
for array in exe.aux_arrays:
array.wait_to_read()
... | [
"Start collecting stats for current batch.\n Call before calling forward."
] |
Please provide a description of the function:def toc(self):
if not self.activated:
return []
for exe in self.exes:
for array in exe.arg_arrays:
array.wait_to_read()
for array in exe.aux_arrays:
array.wait_to_read()
for ... | [
"End collecting for current batch and return results.\n Call after computation of current batch.\n\n Returns\n -------\n res : list of "
] |
Please provide a description of the function:def toc_print(self):
res = self.toc()
for n, k, v in res:
logging.info('Batch: {:7d} {:30s} {:s}'.format(n, k, v)) | [
"End collecting and print results."
] |
Please provide a description of the function:def make_data_iter_plan(self):
"make a random data iteration plan"
# truncate each bucket into multiple of batch-size
bucket_n_batches = []
for i in range(len(self.data)):
bucket_n_batches.append(np.floor((self.data[i]) / self.batc... | [] |
Please provide a description of the function:def expand(x, pending, stage):
if x in history and x not in ['mshadow/mshadow/expr_scalar-inl.h']: # MULTIPLE includes
return
if x in pending:
#print('loop found: {} in {}'.format(x, pending))
return
whtspace = ' ' * expand.treeDep... | [
"\n Expand the pending files in the current stage.\n\n Parameters\n ----------\n x: str\n The file to expand.\n pending : str\n The list of pending files to expand.\n stage: str\n The current stage for file expansion, used for matching the prefix of files.\n "
] |
Please provide a description of the function:def get_imagenet_iterator(root, batch_size, num_workers, data_shape=224, dtype='float32'):
train_dir = os.path.join(root, 'train')
train_transform, val_transform = get_imagenet_transforms(data_shape, dtype)
logging.info("Loading image folder %s, this may tak... | [
"Dataset loader with preprocessing."
] |
Please provide a description of the function:def create(embedding_name, **kwargs):
create_text_embedding = registry.get_create_func(_TokenEmbedding, 'token embedding')
return create_text_embedding(embedding_name, **kwargs) | [
"Creates an instance of token embedding.\n\n\n Creates a token embedding instance by loading embedding vectors from an externally hosted\n pre-trained token embedding file, such as those of GloVe and FastText. To get all the valid\n `embedding_name` and `pretrained_file_name`, use\n `mxnet.contrib.text.... |
Please provide a description of the function:def get_pretrained_file_names(embedding_name=None):
text_embedding_reg = registry.get_registry(_TokenEmbedding)
if embedding_name is not None:
if embedding_name not in text_embedding_reg:
raise KeyError('Cannot find `embedding_name` %s. Use... | [
"Get valid token embedding names and their pre-trained file names.\n\n\n To load token embedding vectors from an externally hosted pre-trained token embedding file,\n such as those of GloVe and FastText, one should use\n `mxnet.contrib.text.embedding.create(embedding_name, pretrained_file_name)`.\n This... |
Please provide a description of the function:def _load_embedding(self, pretrained_file_path, elem_delim, init_unknown_vec, encoding='utf8'):
pretrained_file_path = os.path.expanduser(pretrained_file_path)
if not os.path.isfile(pretrained_file_path):
raise ValueError('`pretrained_f... | [
"Load embedding vectors from the pre-trained token embedding file.\n\n\n For every unknown token, if its representation `self.unknown_token` is encountered in the\n pre-trained token embedding file, index 0 of `self.idx_to_vec` maps to the pre-trained token\n embedding vector loaded from the fi... |
Please provide a description of the function:def _set_idx_to_vec_by_embeddings(self, token_embeddings, vocab_len, vocab_idx_to_token):
new_vec_len = sum(embed.vec_len for embed in token_embeddings)
new_idx_to_vec = nd.zeros(shape=(vocab_len, new_vec_len))
col_start = 0
# Conca... | [
"Sets the mapping between token indices and token embedding vectors.\n\n\n Parameters\n ----------\n token_embeddings : instance or list `mxnet.contrib.text.embedding._TokenEmbedding`\n One or multiple pre-trained token embeddings to load. If it is a list of multiple\n emb... |
Please provide a description of the function:def get_vecs_by_tokens(self, tokens, lower_case_backup=False):
to_reduce = False
if not isinstance(tokens, list):
tokens = [tokens]
to_reduce = True
if not lower_case_backup:
indices = [self.token_to_idx.... | [
"Look up embedding vectors of tokens.\n\n\n Parameters\n ----------\n tokens : str or list of strs\n A token or a list of tokens.\n lower_case_backup : bool, default False\n If False, each token in the original case will be looked up; if True, each token in the\n ... |
Please provide a description of the function:def update_token_vectors(self, tokens, new_vectors):
assert self.idx_to_vec is not None, 'The property `idx_to_vec` has not been properly set.'
if not isinstance(tokens, list) or len(tokens) == 1:
assert isinstance(new_vectors, nd.NDArr... | [
"Updates embedding vectors for tokens.\n\n\n Parameters\n ----------\n tokens : str or a list of strs\n A token or a list of tokens whose embedding vector are to be updated.\n new_vectors : mxnet.ndarray.NDArray\n An NDArray to be assigned to the embedding vectors o... |
Please provide a description of the function:def _check_pretrained_file_names(cls, pretrained_file_name):
embedding_name = cls.__name__.lower()
if pretrained_file_name not in cls.pretrained_file_name_sha1:
raise KeyError('Cannot find pretrained file %s for token embedding %s. Valid... | [
"Checks if a pre-trained token embedding file name is valid.\n\n\n Parameters\n ----------\n pretrained_file_name : str\n The pre-trained token embedding file.\n "
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.