Code stringlengths 103 85.9k | Summary listlengths 0 94 |
|---|---|
Please provide a description of the function:def init_optimizer(self, kvstore='local', optimizer='sgd',
optimizer_params=(('learning_rate', 0.01),),
force_init=False):
assert self.binded and self.params_initialized
if self.optimizer_initialized and ... | [
"Installs and initializes optimizers.\n\n Parameters\n ----------\n kvstore : str or KVStore\n Default `'local'`.\n optimizer : str or Optimizer\n Default `'sgd'`\n optimizer_params : dict\n Default ``(('learning_rate', 0.01),)``. The default value... |
Please provide a description of the function:def forward(self, data_batch, is_train=None):
assert self.binded and self.params_initialized
# make a shallow copy, just to maintain necessary properties (if any) like
# bucket_key, pad, etc.
data_batch = copy.copy(data_batch)
... | [
"Forward computation.\n\n Parameters\n ----------\n data_batch : DataBatch\n is_train : bool\n Default is ``None``, in which case `is_train` is take as ``self.for_training``.\n "
] |
Please provide a description of the function:def backward(self, out_grads=None):
assert self.binded and self.params_initialized
for i_layer, module in reversed(list(zip(range(len(self._modules)), self._modules))):
module.backward(out_grads=out_grads)
if i_layer == 0:
... | [
"Backward computation."
] |
Please provide a description of the function:def update(self):
assert self.binded and self.params_initialized and self.optimizer_initialized
for module in self._modules:
module.update() | [
"Updates parameters according to installed optimizer and the gradient computed\n in the previous forward-backward cycle.\n "
] |
Please provide a description of the function:def get_outputs(self, merge_multi_context=True):
assert self.binded and self.params_initialized
return self._modules[-1].get_outputs(merge_multi_context=merge_multi_context) | [
"Gets outputs from a previous forward computation.\n\n Parameters\n ----------\n merge_multi_context : bool\n Default is ``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 get_input_grads(self, merge_multi_context=True):
assert self.binded and self.params_initialized and self.inputs_need_grad
return self._modules[0].get_input_grads(merge_multi_context=merge_multi_context) | [
"Gets the gradients with respect to the inputs of the module.\n\n Parameters\n ----------\n merge_multi_context : bool\n Default is ``True``. In the case when data-parallelism is used, the outputs\n will be collected from multiple devices. A ``True`` value indicate that we... |
Please provide a description of the function:def update_metric(self, eval_metric, labels, pre_sliced=False):
assert self.binded and self.params_initialized
for meta, module in zip(self._metas, self._modules):
if SequentialModule.META_TAKE_LABELS in meta and \
me... | [
"Evaluates and accumulates evaluation metric on outputs of the last forward computation.\n\n Parameters\n ----------\n eval_metric : EvalMetric\n labels : list of NDArray\n Typically ``data_batch.label``.\n "
] |
Please provide a description of the function:def install_monitor(self, mon):
assert self.binded
for module in self._modules:
module.install_monitor(mon) | [
"Installs monitor on all executors."
] |
Please provide a description of the function:def get_iterator(data_shape, use_caffe_data):
def get_iterator_impl_mnist(args, kv):
# download data
get_mnist_ubyte()
flat = False if len(data_shape) != 1 else True
train = mx.io.MNISTIter(
image="data/train-ima... | [
"Generate the iterator of mnist dataset",
"return train and val iterators for mnist"
] |
Please provide a description of the function:def predict(prediction_dir='./Test'):
if not os.path.exists(prediction_dir):
warnings.warn("The directory on which predictions are to be made is not found!")
return
if len(os.listdir(prediction_dir)) == 0:
warnings.warn("The directory o... | [
"The function is used to run predictions on the audio files in the directory `pred_directory`.\n\n Parameters\n ----------\n net:\n The model that has been trained.\n prediction_dir: string, default ./Test\n The directory that contains the audio files on which predictions are to be made\n\... |
Please provide a description of the function:def _proc_loop(proc_id, alive, queue, fn):
print("proc {} started".format(proc_id))
try:
while alive.value:
data = fn()
put_success = False
while alive.value and not put_success:
... | [
"Thread loop for generating data\n\n Parameters\n ----------\n proc_id: int\n Process id\n alive: multiprocessing.Value\n variable for signaling whether process should continue or not\n queue: multiprocessing.Queue\n queue for passing data back\n ... |
Please provide a description of the function:def _init_proc(self):
if not self.proc:
self.proc = [
mp.Process(target=self._proc_loop, args=(i, self.alive, self.queue, self.fn))
for i in range(self.num_proc)
]
self.alive.value = True
... | [
"Start processes if not already started"
] |
Please provide a description of the function:def reset(self):
self.alive.value = False
qsize = 0
try:
while True:
self.queue.get(timeout=0.1)
qsize += 1
except QEmptyExcept:
pass
print("Queue size on reset: {}".form... | [
"Resets the generator by stopping all processes"
] |
Please provide a description of the function:def with_metaclass(meta, *bases):
# This requires a bit of explanation: the basic idea is to make a dummy
# metaclass for one level of class instantiation that replaces itself with
# the actual metaclass.
class metaclass(type):
def __new__(cls, ... | [
"Create a base class with a metaclass."
] |
Please provide a description of the function:def _load_lib():
lib_path = libinfo.find_lib_path()
lib = ctypes.CDLL(lib_path[0], ctypes.RTLD_LOCAL)
# DMatrix functions
lib.MXGetLastError.restype = ctypes.c_char_p
return lib | [
"Load library by searching possible path."
] |
Please provide a description of the function:def c_array(ctype, values):
out = (ctype * len(values))()
out[:] = values
return out | [
"Create ctypes array from a Python array.\n\n Parameters\n ----------\n ctype : ctypes data type\n Data type of the array we want to convert to, such as mx_float.\n\n values : tuple or list\n Data content.\n\n Returns\n -------\n out : ctypes array\n Created ctypes array.\n... |
Please provide a description of the function:def c_handle_array(objs):
arr = (ctypes.c_void_p * len(objs))()
arr[:] = [o.handle for o in objs]
return arr | [
"Create ctypes const void ** from a list of MXNet objects with handles.\n\n Parameters\n ----------\n objs : list of NDArray/Symbol.\n MXNet objects.\n\n Returns\n -------\n (ctypes.c_void_p * len(objs))\n A void ** pointer that can be passed to C API.\n "
] |
Please provide a description of the function:def ctypes2numpy_shared(cptr, shape):
if not isinstance(cptr, ctypes.POINTER(mx_float)):
raise RuntimeError('expected float pointer')
size = 1
for s in shape:
size *= s
dbuffer = (mx_float * size).from_address(ctypes.addressof(cptr.conten... | [
"Convert a ctypes pointer to a numpy array.\n\n The resulting NumPy array shares the memory with the pointer.\n\n Parameters\n ----------\n cptr : ctypes.POINTER(mx_float)\n pointer to the memory region\n\n shape : tuple\n Shape of target `NDArray`.\n\n Returns\n -------\n out ... |
Please provide a description of the function:def build_param_doc(arg_names, arg_types, arg_descs, remove_dup=True):
param_keys = set()
param_str = []
for key, type_info, desc in zip(arg_names, arg_types, arg_descs):
if key in param_keys and remove_dup:
continue
if key == 'nu... | [
"Build argument docs in python style.\n\n arg_names : list of str\n Argument names.\n\n arg_types : list of str\n Argument type information.\n\n arg_descs : list of str\n Argument description information.\n\n remove_dup : boolean, optional\n Whether remove duplication or not.... |
Please provide a description of the function:def add_fileline_to_docstring(module, incursive=True):
def _add_fileline(obj):
if obj.__doc__ is None or 'From:' in obj.__doc__:
return
fname = inspect.getsourcefile(obj)
if fname is None:
return
try:... | [
"Append the definition position to each function contained in module.\n\n Examples\n --------\n # Put the following codes at the end of a file\n add_fileline_to_docstring(__name__)\n ",
"Add fileinto to a object.\n "
] |
Please provide a description of the function:def _init_op_module(root_namespace, module_name, make_op_func):
plist = ctypes.POINTER(ctypes.c_char_p)()
size = ctypes.c_uint()
check_call(_LIB.MXListAllOpNames(ctypes.byref(size),
ctypes.byref(plist)))
op_names = [... | [
"\n Registers op functions created by `make_op_func` under\n `root_namespace.module_name.[submodule_name]`,\n where `submodule_name` is one of `_OP_SUBMODULE_NAME_LIST`.\n\n Parameters\n ----------\n root_namespace : str\n Top level module name, `mxnet` in the current cases.\n module_nam... |
Please provide a description of the function:def _generate_op_module_signature(root_namespace, module_name, op_code_gen_func):
def get_module_file(module_name):
path = os.path.dirname(__file__)
module_path = module_name.split('.')
module_path[-1] = 'gen_' + module_path[-1]
... | [
"\n Generate op functions created by `op_code_gen_func` and write to the source file\n of `root_namespace.module_name.[submodule_name]`,\n where `submodule_name` is one of `_OP_SUBMODULE_NAME_LIST`.\n\n Parameters\n ----------\n root_namespace : str\n Top level module name, `mxnet` in the c... |
Please provide a description of the function:def set_np_compat(active):
prev = ctypes.c_int()
check_call(_LIB.MXSetIsNumpyCompatible(ctypes.c_int(active), ctypes.byref(prev)))
return bool(prev.value) | [
"\n Turns on/off NumPy compatibility. NumPy-compatibility is turned off by default in backend.\n\n Parameters\n ----------\n active : bool\n Indicates whether to turn on/off NumPy compatibility.\n\n Returns\n -------\n A bool value indicating the previous state of NumPy compatibility... |
Please provide a description of the function:def is_np_compat():
curr = ctypes.c_bool()
check_call(_LIB.MXIsNumpyCompatible(ctypes.byref(curr)))
return curr.value | [
"\n Checks whether the NumPy compatibility is currently turned on.\n NumPy-compatibility is turned off by default in backend.\n\n Returns\n -------\n A bool value indicating whether the NumPy compatibility is currently on.\n "
] |
Please provide a description of the function:def use_np_compat(func):
@wraps(func)
def _with_np_compat(*args, **kwargs):
with np_compat(active=True):
return func(*args, **kwargs)
return _with_np_compat | [
"Wraps a function with an activated NumPy-compatibility scope. This ensures\n that the execution of the function is guaranteed with NumPy compatible semantics,\n such as zero-dim and zero size tensors.\n\n Example::\n import mxnet as mx\n @mx.use_np_compat\n def scalar_one():\n ... |
Please provide a description of the function:def rse(label, pred):
numerator = np.sqrt(np.mean(np.square(label - pred), axis = None))
denominator = np.std(label, axis = None)
return numerator / denominator | [
"computes the root relative squared error (condensed using standard deviation formula)"
] |
Please provide a description of the function:def rae(label, pred):
numerator = np.mean(np.abs(label - pred), axis=None)
denominator = np.mean(np.abs(label - np.mean(label, axis=None)), axis=None)
return numerator / denominator | [
"computes the relative absolute error (condensed using standard deviation formula)"
] |
Please provide a description of the function:def corr(label, pred):
numerator1 = label - np.mean(label, axis=0)
numerator2 = pred - np.mean(pred, axis = 0)
numerator = np.mean(numerator1 * numerator2, axis=0)
denominator = np.std(label, axis=0) * np.std(pred, axis=0)
return np.mean(numerator / ... | [
"computes the empirical correlation coefficient"
] |
Please provide a description of the function:def get_custom_metrics():
_rse = mx.metric.create(rse)
_rae = mx.metric.create(rae)
_corr = mx.metric.create(corr)
return mx.metric.create([_rae, _rse, _corr]) | [
"\n :return: mxnet metric object\n "
] |
Please provide a description of the function:def _get_input(proto):
layer = caffe_parser.get_layers(proto)
if len(proto.input_dim) > 0:
input_dim = proto.input_dim
elif len(proto.input_shape) > 0:
input_dim = proto.input_shape[0].dim
elif layer[0].type == "Input":
input_dim ... | [
"Get input size\n "
] |
Please provide a description of the function:def _convert_conv_param(param):
param_string = "num_filter=%d" % param.num_output
pad_w = 0
pad_h = 0
if isinstance(param.pad, int):
pad = param.pad
param_string += ", pad=(%d, %d)" % (pad, pad)
else:
if len(param.pad) > 0:
... | [
"\n Convert convolution layer parameter from Caffe to MXNet\n "
] |
Please provide a description of the function:def _convert_pooling_param(param):
param_string = "pooling_convention='full', "
if param.global_pooling:
param_string += "global_pool=True, kernel=(1,1)"
else:
param_string += "pad=(%d,%d), kernel=(%d,%d), stride=(%d,%d)" % (
para... | [
"Convert the pooling layer parameter\n "
] |
Please provide a description of the function:def _parse_proto(prototxt_fname):
proto = caffe_parser.read_prototxt(prototxt_fname)
# process data layer
input_name, input_dim, layers = _get_input(proto)
# only support single input, so always use `data` as the input data
mapping = {input_name: 'd... | [
"Parse Caffe prototxt into symbol string\n "
] |
Please provide a description of the function:def convert_symbol(prototxt_fname):
sym, output_name, input_dim = _parse_proto(prototxt_fname)
exec(sym) # pylint: disable=exec-used
_locals = locals()
exec("ret = " + output_name, globals(), _locals) # pylint: disable=exec-used
re... | [
"Convert caffe model definition into Symbol\n\n Parameters\n ----------\n prototxt_fname : str\n Filename of the prototxt file\n\n Returns\n -------\n Symbol\n Converted Symbol\n tuple\n Input shape\n "
] |
Please provide a description of the function:def train_episode(agent, envs, preprocessors, t_max, render):
num_envs = len(envs)
# Buffers to hold trajectories, e.g. `env_xs[i]` will hold the observations
# for environment `i`.
env_xs, env_as = _2d_list(num_envs), _2d_list(num_envs)
env_rs, env... | [
"Complete an episode's worth of training for each environment."
] |
Please provide a description of the function:def parse_caffemodel(file_path):
f = open(file_path, 'rb')
contents = f.read()
net_param = caffe_pb2.NetParameter()
net_param.ParseFromString(contents)
layers = find_layers(net_param)
return layers | [
"\n parses the trained .caffemodel file\n\n filepath: /path/to/trained-model.caffemodel\n\n returns: layers\n "
] |
Please provide a description of the function:def featurize(self, audio_clip, overwrite=False, save_feature_as_csvfile=False):
return spectrogram_from_file(
audio_clip, step=self.step, window=self.window,
max_freq=self.max_freq, overwrite=overwrite,
save_feature_as_cs... | [
" For a given audio clip, calculate the log of its Fourier Transform\n Params:\n audio_clip(str): Path to the audio clip\n "
] |
Please provide a description of the function:def load_metadata_from_desc_file(self, desc_file, partition='train',
max_duration=16.0,):
logger = logUtil.getlogger()
logger.info('Reading description file: {} for partition: {}'
.format(desc_... | [
" Read metadata from the description file\n (possibly takes long, depending on the filesize)\n Params:\n desc_file (str): Path to a JSON-line file that contains labels and\n paths to the audio files\n partition (str): One of 'train', 'validation' or 'test'\n ... |
Please provide a description of the function:def prepare_minibatch(self, audio_paths, texts, overwrite=False,
is_bi_graphemes=False, seq_length=-1, save_feature_as_csvfile=False):
assert len(audio_paths) == len(texts),\
"Inputs and outputs to the network must be of... | [
" Featurize a minibatch of audio, zero pad them and return a dictionary\n Params:\n audio_paths (list(str)): List of paths to audio files\n texts (list(str)): List of texts corresponding to the audio files\n Returns:\n dict: See below for contents\n "
] |
Please provide a description of the function:def sample_normalize(self, k_samples=1000, overwrite=False):
log = logUtil.getlogger()
log.info("Calculating mean and std from samples")
# if k_samples is negative then it goes through total dataset
if k_samples < 0:
audio... | [
" Estimate the mean and std of the features from the training set\n Params:\n k_samples (int): Use this number of samples for estimation\n "
] |
Please provide a description of the function:def gru(num_hidden, indata, prev_state, param, seqidx, layeridx, dropout=0., is_batchnorm=False, gamma=None, beta=None, name=None):
if dropout > 0.:
indata = mx.sym.Dropout(data=indata, p=dropout)
i2h = mx.sym.FullyConnected(data=indata,
... | [
"\n GRU Cell symbol\n Reference:\n * Chung, Junyoung, et al. \"Empirical evaluation of gated recurrent neural\n networks on sequence modeling.\" arXiv preprint arXiv:1412.3555 (2014).\n "
] |
Please provide a description of the function:def save_image(data, epoch, image_size, batch_size, output_dir, padding=2):
data = data.asnumpy().transpose((0, 2, 3, 1))
datanp = np.clip(
(data - np.min(data))*(255.0/(np.max(data) - np.min(data))), 0, 255).astype(np.uint8)
x_dim = min(8, batch_siz... | [
" save image "
] |
Please provide a description of the function:def list_image(root, recursive, exts):
i = 0
if recursive:
cat = {}
for path, dirs, files in os.walk(root, followlinks=True):
dirs.sort()
files.sort()
for fname in files:
fpath = os.path.join(p... | [
"Traverses the root of directory that contains images and\n generates image list iterator.\n Parameters\n ----------\n root: string\n recursive: bool\n exts: string\n Returns\n -------\n image iterator that contains all the image under the specified path\n "
] |
Please provide a description of the function:def write_list(path_out, image_list):
with open(path_out, 'w') as fout:
for i, item in enumerate(image_list):
line = '%d\t' % item[0]
for j in item[2:]:
line += '%f\t' % j
line += '%s\n' % item[1]
... | [
"Hepler function to write image list into the file.\n The format is as below,\n integer_image_index \\t float_label_index \\t path_to_image\n Note that the blank between number and tab is only used for readability.\n Parameters\n ----------\n path_out: string\n image_list: list\n "
] |
Please provide a description of the function:def make_list(args):
image_list = list_image(args.root, args.recursive, args.exts)
image_list = list(image_list)
if args.shuffle is True:
random.seed(100)
random.shuffle(image_list)
N = len(image_list)
chunk_size = (N + args.chunks - ... | [
"Generates .lst file.\n Parameters\n ----------\n args: object that contains all the arguments\n "
] |
Please provide a description of the function:def read_list(path_in):
with open(path_in) as fin:
while True:
line = fin.readline()
if not line:
break
line = [i.strip() for i in line.strip().split('\t')]
line_len = len(line)
# ch... | [
"Reads the .lst file and generates corresponding iterator.\n Parameters\n ----------\n path_in: string\n Returns\n -------\n item iterator that contains information in .lst file\n "
] |
Please provide a description of the function:def image_encode(args, i, item, q_out):
fullpath = os.path.join(args.root, item[1])
if len(item) > 3 and args.pack_label:
header = mx.recordio.IRHeader(0, item[2:], item[0], 0)
else:
header = mx.recordio.IRHeader(0, item[2], item[0], 0)
... | [
"Reads, preprocesses, packs the image and put it back in output queue.\n Parameters\n ----------\n args: object\n i: int\n item: list\n q_out: queue\n "
] |
Please provide a description of the function:def read_worker(args, q_in, q_out):
while True:
deq = q_in.get()
if deq is None:
break
i, item = deq
image_encode(args, i, item, q_out) | [
"Function that will be spawned to fetch the image\n from the input queue and put it back to output queue.\n Parameters\n ----------\n args: object\n q_in: queue\n q_out: queue\n "
] |
Please provide a description of the function:def write_worker(q_out, fname, working_dir):
pre_time = time.time()
count = 0
fname = os.path.basename(fname)
fname_rec = os.path.splitext(fname)[0] + '.rec'
fname_idx = os.path.splitext(fname)[0] + '.idx'
record = mx.recordio.MXIndexedRecordIO(o... | [
"Function that will be spawned to fetch processed image\n from the output queue and write to the .rec file.\n Parameters\n ----------\n q_out: queue\n fname: string\n working_dir: string\n "
] |
Please provide a description of the function:def parse_args():
parser = argparse.ArgumentParser(
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
description='Create an image list or \
make a record database by reading from an image list')
parser.add_argument('prefix', help='... | [
"Defines all arguments.\n Returns\n -------\n args object that contains all the params\n "
] |
Please provide a description of the function:def transform(data, target_wd, target_ht, is_train, box):
if box is not None:
x, y, w, h = box
data = data[y:min(y+h, data.shape[0]), x:min(x+w, data.shape[1])]
# Resize to target_wd * target_ht.
data = mx.image.imresize(data, target_wd, tar... | [
"Crop and normnalize an image nd array."
] |
Please provide a description of the function:def cub200_iterator(data_path, batch_k, batch_size, data_shape):
return (CUB200Iter(data_path, batch_k, batch_size, data_shape, is_train=True),
CUB200Iter(data_path, batch_k, batch_size, data_shape, is_train=False)) | [
"Return training and testing iterator for the CUB200-2011 dataset."
] |
Please provide a description of the function:def get_image(self, img, is_train):
img_arr = mx.image.imread(img)
img_arr = transform(img_arr, 256, 256, is_train, self.boxes[img])
return img_arr | [
"Load and transform an image."
] |
Please provide a description of the function:def sample_train_batch(self):
batch = []
labels = []
num_groups = self.batch_size // self.batch_k
# For CUB200, we use the first 100 classes for training.
sampled_classes = np.random.choice(100, num_groups, replace=False)
... | [
"Sample a training batch (data and label)."
] |
Please provide a description of the function:def next(self):
if self.is_train:
data, labels = self.sample_train_batch()
else:
if self.test_count * self.batch_size < len(self.test_image_files):
data, labels = self.get_test_batch()
self.test... | [
"Return a batch."
] |
Please provide a description of the function:def load_mnist(training_num=50000):
data_path = os.path.join(os.path.dirname(os.path.realpath('__file__')), 'mnist.npz')
if not os.path.isfile(data_path):
from six.moves import urllib
origin = (
'https://github.com/sxjscience/mxnet/ra... | [
"Load mnist dataset"
] |
Please provide a description of the function:def feature_list():
lib_features_c_array = ctypes.POINTER(Feature)()
lib_features_size = ctypes.c_size_t()
check_call(_LIB.MXLibInfoFeatures(ctypes.byref(lib_features_c_array), ctypes.byref(lib_features_size)))
features = [lib_features_c_array[i] for i i... | [
"\n Check the library for compile-time features. The list of features are maintained in libinfo.h and libinfo.cc\n\n Returns\n -------\n list\n List of :class:`.Feature` objects\n "
] |
Please provide a description of the function:def is_enabled(self, feature_name):
feature_name = feature_name.upper()
if feature_name not in self:
raise RuntimeError("Feature '{}' is unknown, known features are: {}".format(
feature_name, list(self.keys())))
re... | [
"\n Check for a particular feature by name\n\n Parameters\n ----------\n feature_name: str\n The name of a valid feature as string for example 'CUDA'\n\n Returns\n -------\n Boolean\n True if it's enabled, False if it's disabled, RuntimeError if... |
Please provide a description of the function:def cache_path(self):
cache_path = os.path.join(os.path.dirname(__file__), '..', 'cache')
if not os.path.exists(cache_path):
os.mkdir(cache_path)
return cache_path | [
"\n make a directory to store all caches\n\n Returns:\n ---------\n cache path\n "
] |
Please provide a description of the function:def _load_image_set_index(self, shuffle):
image_set_index_file = os.path.join(self.data_path, 'ImageSets', 'Main', self.image_set + '.txt')
assert os.path.exists(image_set_index_file), 'Path does not exist: {}'.format(image_set_index_file)
wi... | [
"\n find out which indexes correspond to given image set (train or val)\n\n Parameters:\n ----------\n shuffle : boolean\n whether to shuffle the image list\n Returns:\n ----------\n entire list of images specified in the setting\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"
name = self.image_set_index[index]
image_file = os.path.join(self.data_path, 'JPEGImages', name + self.extension)
assert os.pat... | [
"\n given image index, find out full path\n\n Parameters:\n ----------\n index: int\n index of a specific image\n Returns:\n ----------\n full path of this image\n "
] |
Please provide a description of the function:def _label_path_from_index(self, index):
label_file = os.path.join(self.data_path, 'Annotations', index + '.xml')
assert os.path.exists(label_file), 'Path does not exist: {}'.format(label_file)
return label_file | [
"\n given image index, find out annotation path\n\n Parameters:\n ----------\n index: int\n index of a specific image\n\n Returns:\n ----------\n full path of annotation file\n "
] |
Please provide a description of the function:def _load_image_labels(self):
temp = []
# load ground-truth from xml annotations
for idx in self.image_set_index:
label_file = self._label_path_from_index(idx)
tree = ET.parse(label_file)
root = tree.getro... | [
"\n preprocess all ground-truths\n\n Returns:\n ----------\n labels packed in [num_images x max_num_objects x 5] tensor\n "
] |
Please provide a description of the function:def evaluate_detections(self, detections):
# make all these folders for results
result_dir = os.path.join(self.devkit_path, 'results')
if not os.path.exists(result_dir):
os.mkdir(result_dir)
year_folder = os.path.join(self... | [
"\n top level evaluations\n Parameters:\n ----------\n detections: list\n result list, each entry is a matrix of detections\n Returns:\n ----------\n None\n "
] |
Please provide a description of the function:def get_result_file_template(self):
res_file_folder = os.path.join(self.devkit_path, 'results', 'VOC' + self.year, 'Main')
comp_id = self.config['comp_id']
filename = comp_id + '_det_' + self.image_set + '_{:s}.txt'
path = os.path.joi... | [
"\n this is a template\n VOCdevkit/results/VOC2007/Main/<comp_id>_det_test_aeroplane.txt\n\n Returns:\n ----------\n a string template\n "
] |
Please provide a description of the function:def write_pascal_results(self, all_boxes):
for cls_ind, cls in enumerate(self.classes):
print('Writing {} VOC results file'.format(cls))
filename = self.get_result_file_template().format(cls)
with open(filename, 'wt') as f... | [
"\n write results files in pascal devkit path\n Parameters:\n ----------\n all_boxes: list\n boxes to be processed [bbox, confidence]\n Returns:\n ----------\n None\n "
] |
Please provide a description of the function:def do_python_eval(self):
annopath = os.path.join(self.data_path, 'Annotations', '{:s}.xml')
imageset_file = os.path.join(self.data_path, 'ImageSets', 'Main', self.image_set + '.txt')
cache_dir = os.path.join(self.cache_path, self.name)
... | [
"\n python evaluation wrapper\n\n Returns:\n ----------\n None\n "
] |
Please provide a description of the function:def _get_imsize(self, im_name):
img = cv2.imread(im_name)
return (img.shape[0], img.shape[1]) | [
"\n get image size info\n Returns:\n ----------\n tuple of (height, width)\n "
] |
Please provide a description of the function:def add_fit_args(parser):
train = parser.add_argument_group('Training', 'model training')
train.add_argument('--network', type=str,
help='the neural network to use')
train.add_argument('--num-layers', type=int,
h... | [
"\n parser : argparse.ArgumentParser\n return a parser added with args required by fit\n "
] |
Please provide a description of the function:def fit(args, network, data_loader, **kwargs):
# kvstore
kv = mx.kvstore.create(args.kv_store)
if args.gc_type != 'none':
kv.set_gradient_compression({'type': args.gc_type,
'threshold': args.gc_threshold})
if ... | [
"\n train a model\n args : argparse returns\n network : the symbol definition of the nerual network\n data_loader : function that returns the train and val data iterators\n "
] |
Please provide a description of the function:def CreateMultiRandCropAugmenter(min_object_covered=0.1, aspect_ratio_range=(0.75, 1.33),
area_range=(0.05, 1.0), min_eject_coverage=0.3,
max_attempts=50, skip_prob=0):
def align_parameters(params):
... | [
"Helper function to create multiple random crop augmenters.\n\n Parameters\n ----------\n min_object_covered : float or list of float, default=0.1\n The cropped area of the image must contain at least this fraction of\n any bounding box supplied. The value of this parameter should be non-nega... |
Please provide a description of the function:def CreateDetAugmenter(data_shape, resize=0, rand_crop=0, rand_pad=0, rand_gray=0,
rand_mirror=False, mean=None, std=None, brightness=0, contrast=0,
saturation=0, pca_noise=0, hue=0, inter_method=2, min_object_covered=0.1,
... | [
"Create augmenters for detection.\n\n Parameters\n ----------\n data_shape : tuple of int\n Shape for output data\n resize : int\n Resize shorter edge if larger than 0 at the begining\n rand_crop : float\n [0, 1], probability to apply random cropping\n rand_pad : float\n ... |
Please provide a description of the function:def dumps(self):
return [self.__class__.__name__.lower(), [x.dumps() for x in self.aug_list]] | [
"Override default."
] |
Please provide a description of the function:def _calculate_areas(self, label):
heights = np.maximum(0, label[:, 3] - label[:, 1])
widths = np.maximum(0, label[:, 2] - label[:, 0])
return heights * widths | [
"Calculate areas for multiple labels"
] |
Please provide a description of the function:def _intersect(self, label, xmin, ymin, xmax, ymax):
left = np.maximum(label[:, 0], xmin)
right = np.minimum(label[:, 2], xmax)
top = np.maximum(label[:, 1], ymin)
bot = np.minimum(label[:, 3], ymax)
invalid = np.where(np.logi... | [
"Calculate intersect areas, normalized."
] |
Please provide a description of the function:def _check_satisfy_constraints(self, label, xmin, ymin, xmax, ymax, width, height):
if (xmax - xmin) * (ymax - ymin) < 2:
return False # only 1 pixel
x1 = float(xmin) / width
y1 = float(ymin) / height
x2 = float(xmax) / w... | [
"Check if constrains are satisfied"
] |
Please provide a description of the function:def _update_labels(self, label, crop_box, height, width):
xmin = float(crop_box[0]) / width
ymin = float(crop_box[1]) / height
w = float(crop_box[2]) / width
h = float(crop_box[3]) / height
out = label.copy()
out[:, (1... | [
"Convert labels according to crop box"
] |
Please provide a description of the function:def _random_crop_proposal(self, label, height, width):
from math import sqrt
if not self.enabled or height <= 0 or width <= 0:
return ()
min_area = self.area_range[0] * height * width
max_area = self.area_range[1] * heigh... | [
"Propose cropping areas"
] |
Please provide a description of the function:def _update_labels(self, label, pad_box, height, width):
out = label.copy()
out[:, (1, 3)] = (out[:, (1, 3)] * width + pad_box[0]) / pad_box[2]
out[:, (2, 4)] = (out[:, (2, 4)] * height + pad_box[1]) / pad_box[3]
return out | [
"Update label according to padding region"
] |
Please provide a description of the function:def _random_pad_proposal(self, label, height, width):
from math import sqrt
if not self.enabled or height <= 0 or width <= 0:
return ()
min_area = self.area_range[0] * height * width
max_area = self.area_range[1] * height ... | [
"Generate random padding region"
] |
Please provide a description of the function:def _check_valid_label(self, label):
if len(label.shape) != 2 or label.shape[1] < 5:
msg = "Label with shape (1+, 5+) required, %s received." % str(label)
raise RuntimeError(msg)
valid_label = np.where(np.logical_and(label[:, ... | [
"Validate label and its shape."
] |
Please provide a description of the function:def _estimate_label_shape(self):
max_count = 0
self.reset()
try:
while True:
label, _ = self.next_sample()
label = self._parse_label(label)
max_count = max(max_count, label.shape[0])... | [
"Helper function to estimate label shape"
] |
Please provide a description of the function:def _parse_label(self, label):
if isinstance(label, nd.NDArray):
label = label.asnumpy()
raw = label.ravel()
if raw.size < 7:
raise RuntimeError("Label shape is invalid: " + str(raw.shape))
header_width = int(r... | [
"Helper function to parse object detection label.\n\n Format for raw label:\n n \\t k \\t ... \\t [id \\t xmin\\t ymin \\t xmax \\t ymax \\t ...] \\t [repeat]\n where n is the width of header, 2 or larger\n k is the width of each object annotation, can be arbitrary, at least 5\n "... |
Please provide a description of the function:def reshape(self, data_shape=None, label_shape=None):
if data_shape is not None:
self.check_data_shape(data_shape)
self.provide_data = [(self.provide_data[0][0], (self.batch_size,) + data_shape)]
self.data_shape = data_sha... | [
"Reshape iterator for data_shape or label_shape.\n\n Parameters\n ----------\n data_shape : tuple or None\n Reshape the data_shape to the new shape if not None\n label_shape : tuple or None\n Reshape label shape to new shape if not None\n "
] |
Please provide a description of the function:def _batchify(self, batch_data, batch_label, start=0):
i = start
batch_size = self.batch_size
try:
while i < batch_size:
label, s = self.next_sample()
data = self.imdecode(s)
try:
... | [
"Override the helper function for batchifying data"
] |
Please provide a description of the function:def next(self):
batch_size = self.batch_size
c, h, w = self.data_shape
# if last batch data is rolled over
if self._cache_data is not None:
# check both the data and label have values
assert self._cache_label i... | [
"Override the function for returning next batch."
] |
Please provide a description of the function:def augmentation_transform(self, data, label): # pylint: disable=arguments-differ
for aug in self.auglist:
data, label = aug(data, label)
return (data, label) | [
"Override Transforms input data with specified augmentations."
] |
Please provide a description of the function:def check_label_shape(self, label_shape):
if not len(label_shape) == 2:
raise ValueError('label_shape should have length 2')
if label_shape[0] < self.label_shape[0]:
msg = 'Attempts to reduce label count from %d to %d, not all... | [
"Checks if the new label shape is valid"
] |
Please provide a description of the function:def draw_next(self, color=None, thickness=2, mean=None, std=None, clip=True,
waitKey=None, window_name='draw_next', id2labels=None):
try:
import cv2
except ImportError as e:
warnings.warn('Unable to import cv... | [
"Display next image with bounding boxes drawn.\n\n Parameters\n ----------\n color : tuple\n Bounding box color in RGB, use None for random color\n thickness : int\n Bounding box border thickness\n mean : True or numpy.ndarray\n Compensate for the ... |
Please provide a description of the function:def sync_label_shape(self, it, verbose=False):
assert isinstance(it, ImageDetIter), 'Synchronize with invalid iterator.'
train_label_shape = self.label_shape
val_label_shape = it.label_shape
assert train_label_shape[1] == val_label_sh... | [
"Synchronize label shape with the input iterator. This is useful when\n train/validation iterators have different label padding.\n\n Parameters\n ----------\n it : ImageDetIter\n The other iterator to synchronize\n verbose : bool\n Print verbose log if true\n... |
Please provide a description of the function:def _generate_base_anchors(base_size, scales, ratios):
base_anchor = np.array([1, 1, base_size, base_size]) - 1
ratio_anchors = AnchorGenerator._ratio_enum(base_anchor, ratios)
anchors = np.vstack([AnchorGenerator._scale_enum(ratio_anchors[i,... | [
"\n Generate anchor (reference) windows by enumerating aspect ratios X\n scales wrt a reference (0, 0, 15, 15) window.\n "
] |
Please provide a description of the function:def _whctrs(anchor):
w = anchor[2] - anchor[0] + 1
h = anchor[3] - anchor[1] + 1
x_ctr = anchor[0] + 0.5 * (w - 1)
y_ctr = anchor[1] + 0.5 * (h - 1)
return w, h, x_ctr, y_ctr | [
"\n Return width, height, x center, and y center for an anchor (window).\n "
] |
Please provide a description of the function:def _mkanchors(ws, hs, x_ctr, y_ctr):
ws = ws[:, np.newaxis]
hs = hs[:, np.newaxis]
anchors = np.hstack((x_ctr - 0.5 * (ws - 1),
y_ctr - 0.5 * (hs - 1),
x_ctr + 0.5 * (ws - 1),
... | [
"\n Given a vector of widths (ws) and heights (hs) around a center\n (x_ctr, y_ctr), output a set of anchors (windows).\n "
] |
Please provide a description of the function:def _ratio_enum(anchor, ratios):
w, h, x_ctr, y_ctr = AnchorGenerator._whctrs(anchor)
size = w * h
size_ratios = size / ratios
ws = np.round(np.sqrt(size_ratios))
hs = np.round(ws * ratios)
anchors = AnchorGenerator._m... | [
"\n Enumerate a set of anchors for each aspect ratio wrt an anchor.\n "
] |
Please provide a description of the function:def _scale_enum(anchor, scales):
w, h, x_ctr, y_ctr = AnchorGenerator._whctrs(anchor)
ws = w * scales
hs = h * scales
anchors = AnchorGenerator._mkanchors(ws, hs, x_ctr, y_ctr)
return anchors | [
"\n Enumerate a set of anchors for each scale wrt an anchor.\n "
] |
Please provide a description of the function:def prepare_data(args):
rnn_type = args.config.get("arch", "rnn_type")
num_rnn_layer = args.config.getint("arch", "num_rnn_layer")
num_hidden_rnn_list = json.loads(args.config.get("arch", "num_hidden_rnn_list"))
batch_size = args.config.getint("common",... | [
"\n set atual shape of data\n "
] |
Please provide a description of the function:def arch(args, seq_len=None):
if isinstance(args, argparse.Namespace):
mode = args.config.get("common", "mode")
is_bucketing = args.config.getboolean("arch", "is_bucketing")
if mode == "train" or is_bucketing:
channel_num = args.c... | [
"\n define deep speech 2 network\n "
] |
Please provide a description of the function:def main():
parser = argparse.ArgumentParser()
parser.add_argument('--batch_size', type=int, default=64)
parser.add_argument('--epochs', type=int, default=100)
parser.add_argument('--image_path', type=str, default='./data/datasets/')
parser.add_argum... | [
"\n Description : run lipnet training code using argument info\n "
] |
Please provide a description of the function:def vis_detection(im_orig, detections, class_names, thresh=0.7):
import matplotlib.pyplot as plt
import random
plt.imshow(im_orig)
colors = [(random.random(), random.random(), random.random()) for _ in class_names]
for [cls, conf, x1, y1, x2, y2] in ... | [
"visualize [cls, conf, x1, y1, x2, y2]"
] |
Please provide a description of the function:def check_error(model, path, shapes, output = 'softmax_output', verbose = True):
coreml_model = _coremltools.models.MLModel(path)
input_data = {}
input_data_copy = {}
for ip in shapes:
input_data[ip] = _np.random.rand(*shapes[ip]).astype('f')
... | [
"\n Check the difference between predictions from MXNet and CoreML.\n "
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.