Code
stringlengths
103
85.9k
Summary
listlengths
0
94
Please provide a description of the function:def from_video(self, path): frames = self.get_video_frames(path) self.handle_type(frames) return self
[ "\n Read from videos\n " ]
Please provide a description of the function:def handle_type(self, frames): if self.vtype == 'mouth': self.process_frames_mouth(frames) elif self.vtype == 'face': self.process_frames_face(frames) else: raise Exception('Video type not found')
[ "\n Config video types\n " ]
Please provide a description of the function:def process_frames_face(self, frames): detector = dlib.get_frontal_face_detector() predictor = dlib.shape_predictor(self.face_predictor_path) mouth_frames = self.get_frames_mouth(detector, predictor, frames) self.face = np.array(frame...
[ "\n Preprocess from frames using face detector\n " ]
Please provide a description of the function:def process_frames_mouth(self, frames): self.face = np.array(frames) self.mouth = np.array(frames) self.set_data(frames)
[ "\n Preprocess from frames using mouth detector\n " ]
Please provide a description of the function:def get_frames_mouth(self, detector, predictor, frames): mouth_width = 100 mouth_height = 50 horizontal_pad = 0.19 normalize_ratio = None mouth_frames = [] for frame in frames: dets = detector(frame, 1) ...
[ "\n Get frames using mouth crop\n " ]
Please provide a description of the function:def get_video_frames(self, path): videogen = skvideo.io.vreader(path) frames = np.array([frame for frame in videogen]) return frames
[ "\n Get video frames\n " ]
Please provide a description of the function:def set_data(self, frames): data_frames = [] for frame in frames: #frame H x W x C frame = frame.swapaxes(0, 1) # swap width and height to form format W x H x C if len(frame.shape) < 3: frame = np.a...
[ "\n Prepare the input of model\n " ]
Please provide a description of the function:def reset(self): self.curr_idx = 0 random.shuffle(self.idx) for buck in self.data: np.random.shuffle(buck)
[ "Resets the iterator to the beginning of the data." ]
Please provide a description of the function:def next(self): if self.curr_idx == len(self.idx): raise StopIteration i, j = self.idx[self.curr_idx] self.curr_idx += 1 audio_paths = [] texts = [] for duration, audio_path, text in self.data[i][j:j+self....
[ "Returns the next batch of data." ]
Please provide a description of the function:def subtract_imagenet_mean_preprocess_batch(batch): batch = F.swapaxes(batch,0, 1) (r, g, b) = F.split(batch, num_outputs=3, axis=0) r = r - 123.680 g = g - 116.779 b = b - 103.939 batch = F.concat(b, g, r, dim=0) batch = F.swapaxes(batch,0, ...
[ "Subtract ImageNet mean pixel-wise from a BGR image." ]
Please provide a description of the function:def imagenet_clamp_batch(batch, low, high): F.clip(batch[:,0,:,:],low-123.680, high-123.680) F.clip(batch[:,1,:,:],low-116.779, high-116.779) F.clip(batch[:,2,:,:],low-103.939, high-103.939)
[ " Not necessary in practice " ]
Please provide a description of the function:def create_network(batch_size, update_freq): head = '%(asctime)-15s %(message)s' logging.basicConfig(level=logging.INFO, format=head) data = np.random.randint(1, 5, [1000, 2]) #Test_Train data split n_train = int(data.shape[0] * 0.8) weights = n...
[ "Create a linear regression network for performing SVRG optimization.\n :return: an instance of mx.io.NDArrayIter\n :return: an instance of mx.mod.svrgmodule for performing SVRG optimization\n " ]
Please provide a description of the function:def evaluate_accuracy(data_iterator, net): acc = mx.metric.Accuracy() for data, label in data_iterator: output = net(data) predictions = nd.argmax(output, axis=1) predictions = predictions.reshape((-1, 1)) acc.update(preds=predict...
[ "Function to evaluate accuracy of any data iterator passed to it as an argument" ]
Please provide a description of the function:def train(train_dir=None, train_csv=None, epochs=30, batch_size=32): if not train_dir or not os.path.exists(train_dir) or not train_csv: warnings.warn("No train directory could be found ") return # Make a dataset from the local folder containing...
[ "Function responsible for running the training the model." ]
Please provide a description of the function:def set_bulk_size(size): prev = ctypes.c_int() check_call(_LIB.MXEngineSetBulkSize( ctypes.c_int(size), ctypes.byref(prev))) return prev.value
[ "Set size limit on bulk execution.\n\n Bulk execution bundles many operators to run together.\n This can improve performance when running a lot of small\n operators sequentially.\n\n Parameters\n ----------\n size : int\n Maximum number of operators that can be bundled in a bulk.\n\n Ret...
Please provide a description of the function:def applyLM(parentBeam, childBeam, classes, lm): if lm and not childBeam.lmApplied: c1 = classes[parentBeam.labeling[-1] if parentBeam.labeling else classes.index(' ')] # first char c2 = classes[childBeam.labeling[-1]] # second char lmFactor ...
[ "\n calculate LM score of child beam by taking score from parent beam and bigram probability of last two chars\n " ]
Please provide a description of the function:def addBeam(beamState, labeling): if labeling not in beamState.entries: beamState.entries[labeling] = BeamEntry()
[ "\n add beam if it does not yet exist\n " ]
Please provide a description of the function:def ctcBeamSearch(mat, classes, lm, k, beamWidth): blankIdx = len(classes) maxT, maxC = mat.shape # initialise beam state last = BeamState() labeling = () last.entries[labeling] = BeamEntry() last.entries[labeling].prBlank = 1 last.entr...
[ "\n beam search as described by the paper of Hwang et al. and the paper of Graves et al.\n " ]
Please provide a description of the function:def norm(self): for (k, _) in self.entries.items(): labelingLen = len(self.entries[k].labeling) self.entries[k].prText = self.entries[k].prText ** (1.0 / (labelingLen if labelingLen else 1.0))
[ "\n length-normalise LM score\n " ]
Please provide a description of the function:def sort(self): beams = [v for (_, v) in self.entries.items()] sortedBeams = sorted(beams, reverse=True, key=lambda x: x.prTotal*x.prText) return [x.labeling for x in sortedBeams]
[ "\n return beam-labelings, sorted by probability\n " ]
Please provide a description of the function:def get_loc(data, attr={'lr_mult':'0.01'}): loc = mx.symbol.Convolution(data=data, num_filter=30, kernel=(5, 5), stride=(2,2)) loc = mx.symbol.Activation(data = loc, act_type='relu') loc = mx.symbol.Pooling(data=loc, kernel=(2, 2), stride=(2, 2), pool_type='...
[ "\n the localisation network in lenet-stn, it will increase acc about more than 1%,\n when num-epoch >=15\n " ]
Please provide a description of the function:def get_detector(net, prefix, epoch, data_shape, mean_pixels, ctx, num_class, nms_thresh=0.5, force_nms=True, nms_topk=400): if net is not None: if isinstance(data_shape, tuple): data_shape = data_shape[0] net = get_symbo...
[ "\n wrapper for initialize a detector\n\n Parameters:\n ----------\n net : str\n test network name\n prefix : str\n load model prefix\n epoch : int\n load model epoch\n data_shape : int\n resize image shape\n mean_pixels : tuple (float, float, float)\n mean...
Please provide a description of the function:def parse_class_names(class_names): if len(class_names) > 0: if os.path.isfile(class_names): # try to open it to read class names with open(class_names, 'r') as f: class_names = [l.strip() for l in f.readlines()] ...
[ " parse # classes and class_names if applicable " ]
Please provide a description of the function:def parse_data_shape(data_shape_str): ds = data_shape_str.strip().split(',') if len(ds) == 1: data_shape = (int(ds[0]), int(ds[0])) elif len(ds) == 2: data_shape = (int(ds[0]), int(ds[1])) else: raise ValueError("Unexpected data_s...
[ "Parse string to tuple or int" ]
Please provide a description of the function:def get_lenet(): source = mx.sym.Variable("data") source = (source - 128) * (1.0/128) frames = mx.sym.SliceChannel(source, num_outputs=30) diffs = [frames[i+1] - frames[i] for i in range(29)] source = mx.sym.Concat(*diffs) net = mx.sym.Convolutio...
[ " A lenet style net, takes difference of each frame as input.\n " ]
Please provide a description of the function:def CRPS(label, pred): for i in range(pred.shape[0]): for j in range(pred.shape[1] - 1): if pred[i, j] > pred[i, j + 1]: pred[i, j + 1] = pred[i, j] return np.sum(np.square(label - pred)) / label.size
[ " Custom evaluation metric on CRPS.\n " ]
Please provide a description of the function:def encode_label(label_data): systole = label_data[:, 1] diastole = label_data[:, 2] systole_encode = np.array([ (x < np.arange(600)) for x in systole ], dtype=np.uint8) diastole_encode = np.array([ (x < np.arange(600)) fo...
[ "Run encoding to encode the label into the CDF target.\n " ]
Please provide a description of the function:def _load_annotation(self, _coco, coco_ind_to_class_ind, index): im_ann = _coco.loadImgs(index)[0] filename = self._image_file_tmpl.format(im_ann['file_name']) width = im_ann['width'] height = im_ann['height'] annIds = _coco....
[ "\n coco ann: [u'segmentation', u'area', u'iscrowd', u'image_id', u'bbox', u'category_id', u'id']\n iscrowd:\n crowd instances are handled by marking their overlaps with all categories to -1\n and later excluded in training\n bbox:\n [x1, y1, w, h]\n :par...
Please provide a description of the function:def _write_coco_results(self, _coco, detections): cats = [cat['name'] for cat in _coco.loadCats(_coco.getCatIds())] class_to_coco_ind = dict(zip(cats, _coco.getCatIds())) results = [] for cls_ind, cls in enumerate(self.classes): ...
[ " example results\n [{\"image_id\": 42,\n \"category_id\": 18,\n \"bbox\": [258.15,41.29,348.26,243.78],\n \"score\": 0.236}, ...]\n " ]
Please provide a description of the function:def rand_zipfian(true_classes, num_sampled, range_max, ctx=None): if ctx is None: ctx = current_context() log_range = math.log(range_max + 1) rand = uniform(0, log_range, shape=(num_sampled,), dtype='float64', ctx=ctx) # make sure sampled_classes...
[ "Draw random samples from an approximately log-uniform or Zipfian distribution.\n\n This operation randomly samples *num_sampled* candidates the range of integers [0, range_max).\n The elements of sampled_candidates are drawn with replacement from the base distribution.\n\n The base distribution for this o...
Please provide a description of the function:def foreach(body, data, init_states): def check_input(inputs, in_type, msg): is_NDArray_or_list = True if isinstance(inputs, list): for i in inputs: if not isinstance(i, in_type): is_NDArray_or_list = ...
[ "Run a for loop with user-defined computation over NDArrays on dimension 0.\n\n This operator simulates a for loop and body has the computation for an iteration\n of the for loop. It runs the computation in body on each slice from the input\n NDArrays.\n\n body takes two arguments as input and outputs a...
Please provide a description of the function:def while_loop(cond, func, loop_vars, max_iterations=None): def _to_python_scalar(inputs, type_, name): if isinstance(inputs, ndarray.NDArray): inputs = inputs.asscalar() try: inputs = type_(inputs) except: ...
[ "Run a while loop with user-defined computation and loop condition.\n\n This operator simulates a while loop which iterately does customized computation\n as long as the condition is satisfied.\n\n `loop_vars` is a list of NDArrays on which the computation uses.\n\n `cond` is a user-defined function, us...
Please provide a description of the function:def cond(pred, then_func, else_func): def _to_python_scalar(inputs, type_, name): if hasattr(inputs, "asscalar"): inputs = inputs.asscalar() try: inputs = type_(inputs) except: raise ValueError("Ca...
[ "Run an if-then-else using user-defined condition and computation\n\n This operator simulates a if-like branch which chooses to do one of\n the two customized computations according to the specified condition.\n\n `pred` is a scalar MXNet NDArray,\n indicating which branch of computation should be used....
Please provide a description of the function:def isfinite(data): is_data_not_nan = data == data is_data_not_infinite = data.abs() != np.inf return ndarray.logical_and(is_data_not_infinite, is_data_not_nan)
[ "Performs an element-wise check to determine if the NDArray contains an infinite element\n or not.\n\n\n Parameters\n ----------\n input : NDArray\n An N-D NDArray.\n\n Returns\n -------\n output: NDArray\n The output NDarray, with same shape as input, where 1 indicates the array ...
Please provide a description of the function:def vanilla_lstm(num_hidden, indata, prev_state, param, seqidx, layeridx, is_batchnorm=False, gamma=None, beta=None, name=None): i2h = mx.sym.FullyConnected(data=indata, weight=param.i2h_weight, bias=pa...
[ "LSTM Cell symbol" ]
Please provide a description of the function:def lstm(num_hidden, indata, prev_state, param, seqidx, layeridx, dropout=0., num_hidden_proj=0, is_batchnorm=False, gamma=None, beta=None, name=None): # dropout input if dropout > 0.: indata = mx.sym.Dropout(data=indata, p=dropout) i2h = m...
[ "LSTM Cell symbol" ]
Please provide a description of the function:def get_image(roi_rec, short, max_size, mean, std): im = imdecode(roi_rec['image']) if roi_rec["flipped"]: im = im[:, ::-1, :] im, im_scale = resize(im, short, max_size) height, width = im.shape[:2] im_info = np.array([height, width, im_scale...
[ "\n read, resize, transform image, return im_tensor, im_info, gt_boxes\n roi_rec should have keys: [\"image\", \"boxes\", \"gt_classes\", \"flipped\"]\n 0 --- x (width, second dim of im)\n |\n y (height, first dim of im)\n " ]
Please provide a description of the function:def imdecode(image_path): import os assert os.path.exists(image_path), image_path + ' not found' im = cv2.imread(image_path) return im
[ "Return BGR image read by opencv" ]
Please provide a description of the function:def resize(im, short, max_size): im_shape = im.shape im_size_min = np.min(im_shape[0:2]) im_size_max = np.max(im_shape[0:2]) im_scale = float(short) / float(im_size_min) # prevent bigger axis from being more than max_size: if np.round(im_scale * ...
[ "\n only resize input image to target size and return scale\n :param im: BGR image input by opencv\n :param short: one dimensional size (the short side)\n :param max_size: one dimensional max size (the long side)\n :return: resized image (NDArray) and scale (float)\n " ]
Please provide a description of the function:def transform(im, mean, std): im_tensor = np.zeros((3, im.shape[0], im.shape[1])) for i in range(3): im_tensor[i, :, :] = (im[:, :, 2 - i] - mean[i]) / std[i] return im_tensor
[ "\n transform into mxnet tensor,\n subtract pixel size and transform to correct format\n :param im: [height, width, channel] in BGR\n :param mean: [RGB pixel mean]\n :param std: [RGB pixel std var]\n :return: [batch, channel, height, width]\n " ]
Please provide a description of the function:def transform_inverse(im_tensor, mean, std): assert im_tensor.shape[0] == 3 im = im_tensor.transpose((1, 2, 0)) im = im * std + mean im = im.astype(np.uint8) return im
[ "\n transform from mxnet im_tensor to ordinary RGB image\n im_tensor is limited to one image\n :param im_tensor: [batch, channel, height, width]\n :param mean: [RGB pixel mean]\n :param std: [RGB pixel std var]\n :return: im [height, width, channel(RGB)]\n " ]
Please provide a description of the function:def tensor_vstack(tensor_list, pad=0): if len(tensor_list) == 1: return tensor_list[0][np.newaxis, :] ndim = len(tensor_list[0].shape) dimensions = [len(tensor_list)] # first dim is batch size for dim in range(ndim): dimensions.append(m...
[ "\n vertically stack tensors by adding a new axis\n expand dims if only 1 tensor\n :param tensor_list: list of tensor to be stacked vertically\n :param pad: label to pad with\n :return: tensor with max shape\n " ]
Please provide a description of the function:def get_distance_matrix(x): square = nd.sum(x ** 2.0, axis=1, keepdims=True) distance_square = square + square.transpose() - (2.0 * nd.dot(x, x.transpose())) return nd.sqrt(distance_square)
[ "Get distance matrix given a matrix. Used in testing." ]
Please provide a description of the function:def evaluate_emb(emb, labels): d_mat = get_distance_matrix(emb) d_mat = d_mat.asnumpy() labels = labels.asnumpy() names = [] accs = [] for k in [1, 2, 4, 8, 16]: names.append('Recall@%d' % k) correct, cnt = 0.0, 0.0 for i...
[ "Evaluate embeddings based on Recall@k." ]
Please provide a description of the function:def get_lr(lr, epoch, steps, factor): for s in steps: if epoch >= s: lr *= factor return lr
[ "Get learning rate based on schedule." ]
Please provide a description of the function:def train(epochs, ctx): if isinstance(ctx, mx.Context): ctx = [ctx] net.initialize(mx.init.Xavier(magnitude=2), ctx=ctx) opt_options = {'learning_rate': opt.lr, 'wd': opt.wd} if opt.optimizer == 'sgd': opt_options['momentum'] = 0.9 i...
[ "Training function." ]
Please provide a description of the function:def _lstm_unroll_base(num_lstm_layer, seq_len, num_hidden): param_cells = [] last_states = [] for i in range(num_lstm_layer): param_cells.append(LSTMParam(i2h_weight=mx.sym.Variable("l%d_i2h_weight" % i), i2h_bias...
[ " Returns symbol for LSTM model up to loss/softmax" ]
Please provide a description of the function:def _add_warp_ctc_loss(pred, seq_len, num_label, label): label = mx.sym.Reshape(data=label, shape=(-1,)) label = mx.sym.Cast(data=label, dtype='int32') return mx.sym.WarpCTC(data=pred, label=label, label_length=num_label, input_length=seq_len)
[ " Adds Symbol.contrib.ctc_loss on top of pred symbol and returns the resulting symbol " ]
Please provide a description of the function:def _add_mxnet_ctc_loss(pred, seq_len, label): pred_ctc = mx.sym.Reshape(data=pred, shape=(-4, seq_len, -1, 0)) loss = mx.sym.contrib.ctc_loss(data=pred_ctc, label=label) ctc_loss = mx.sym.MakeLoss(loss) softmax_class = mx.symbol.SoftmaxActivation(data...
[ " Adds Symbol.WapCTC on top of pred symbol and returns the resulting symbol " ]
Please provide a description of the function:def _add_ctc_loss(pred, seq_len, num_label, loss_type): label = mx.sym.Variable('label') if loss_type == 'warpctc': print("Using WarpCTC Loss") sm = _add_warp_ctc_loss(pred, seq_len, num_label, label) else: print("Using MXNet CTC Loss...
[ " Adds CTC loss on top of pred symbol and returns the resulting symbol " ]
Please provide a description of the function:def lstm_unroll(num_lstm_layer, seq_len, num_hidden, num_label, loss_type=None): # Create the base (shared between training and inference) and add loss to the end pred = _lstm_unroll_base(num_lstm_layer, seq_len, num_hidden) if loss_type: # Training...
[ "\n Creates an unrolled LSTM symbol for inference if loss_type is not specified, and for training\n if loss_type is specified. loss_type must be one of 'ctc' or 'warpctc'\n\n Parameters\n ----------\n num_lstm_layer: int\n seq_len: int\n num_hidden: int\n num_label: int\n loss_type: str\n...
Please provide a description of the function:def init_states(batch_size, num_lstm_layer, num_hidden): init_c = [('l%d_init_c' % l, (batch_size, num_hidden)) for l in range(num_lstm_layer)] init_h = [('l%d_init_h' % l, (batch_size, num_hidden)) for l in range(num_lstm_layer)] return init_c + init_h
[ "\n Returns name and shape of init states of LSTM network\n\n Parameters\n ----------\n batch_size: list of tuple of str and tuple of int and int\n num_lstm_layer: int\n num_hidden: int\n\n Returns\n -------\n list of tuple of str and tuple of int and int\n " ]
Please provide a description of the function:def _imperative_invoke(handle, ndargs, keys, vals, out): if out is not None: original_output = out if isinstance(out, NDArrayBase): out = (out,) num_output = ctypes.c_int(len(out)) output_vars = c_handle_array(out) ...
[ "ctypes implementation of imperative invoke wrapper" ]
Please provide a description of the function:def set_is_training(is_train): prev = ctypes.c_int() check_call(_LIB.MXAutogradSetIsTraining( ctypes.c_int(is_train), ctypes.byref(prev))) check_call(_LIB.MXAutogradSetIsRecording( ctypes.c_int(is_train), ctypes.byref(prev))) return bool(...
[ "Set status to training/not training. When training, graph will be constructed\n for gradient computation. Operators will also run with ctx.is_train=True. For example,\n Dropout will drop inputs randomly when is_train=True while simply passing through\n if is_train=False.\n\n Parameters\n ----------\...
Please provide a description of the function:def backward(outputs, out_grads=None, retain_graph=False): assert isinstance(outputs, (list, tuple)), \ "outputs must be a list or tuple of NDArrays" if out_grads is None: check_call(_LIB.MXAutogradBackward( len(outputs), ...
[ "Compute the gradients of outputs w.r.t variables.\n\n Parameters\n ----------\n outputs: list of NDArray\n out_grads: list of NDArray or None\n " ]
Please provide a description of the function:def grad_and_loss(func, argnum=None): @functools.wraps(func) def wrapped(*args): variables = args if argnum is not None: argnum_ = argnum if isinstance(argnum, list) else [argnum] variables = [args[i] for i in arg...
[ "Return function that computes both gradient of arguments and loss value.\n\n Parameters\n ----------\n func: a python function\n The forward (loss) function.\n argnum: an int or a list of int\n The index of argument to calculate gradient for.\n\n Returns\n -------\n grad_and_loss...
Please provide a description of the function:def grad(func, argnum=None): grad_with_loss_func = grad_and_loss(func, argnum) @functools.wraps(grad_with_loss_func) def wrapped(*args): return grad_with_loss_func(*args)[0] return wrapped
[ "Return function that computes gradient of arguments.\n\n Parameters\n ----------\n func: a python function\n The forward (loss) function.\n argnum: an int or a list of int\n The index of argument to calculate gradient for.\n\n Returns\n -------\n grad_func: a python function\n ...
Please provide a description of the function:def split_data(data, num_slice, batch_axis=0, even_split=True): size = data.shape[batch_axis] if even_split and size % num_slice != 0: raise ValueError( "data with shape %s cannot be evenly split into %d slices along axis %d. " \ ...
[ "Splits an NDArray into `num_slice` slices along `batch_axis`.\n Usually used for data parallelism where each slices is sent\n to one device (i.e. GPU).\n\n Parameters\n ----------\n data : NDArray\n A batch of data.\n num_slice : int\n Number of desired slices.\n batch_axis : int...
Please provide a description of the function:def split_and_load(data, ctx_list, batch_axis=0, even_split=True): if not isinstance(data, ndarray.NDArray): data = ndarray.array(data, ctx=ctx_list[0]) if len(ctx_list) == 1: return [data.as_in_context(ctx_list[0])] slices = split_data(data...
[ "Splits an NDArray into `len(ctx_list)` slices along `batch_axis` and loads\n each slice to one context in `ctx_list`.\n\n Parameters\n ----------\n data : NDArray\n A batch of data.\n ctx_list : list of Context\n A list of Contexts.\n batch_axis : int, default 0\n The axis al...
Please provide a description of the function:def clip_global_norm(arrays, max_norm, check_isfinite=True): def _norm(array): if array.stype == 'default': x = array.reshape((-1,)) return ndarray.dot(x, x) return array.norm().square() assert len(arrays) > 0 ctx = ar...
[ "Rescales NDArrays so that the sum of their 2-norm is smaller than `max_norm`.\n\n Parameters\n ----------\n arrays : list of NDArray\n max_norm : float\n check_isfinite : bool, default True\n If True, check that the total_norm is finite (not nan or inf). This\n requires a blocking .a...
Please provide a description of the function:def _indent(s_, numSpaces): s = s_.split('\n') if len(s) == 1: return s_ first = s.pop(0) s = [first] + [(numSpaces * ' ') + line for line in s] s = '\n'.join(s) return s
[ "Indent string\n " ]
Please provide a description of the function:def check_sha1(filename, sha1_hash): sha1 = hashlib.sha1() with open(filename, 'rb') as f: while True: data = f.read(1048576) if not data: break sha1.update(data) return sha1.hexdigest() == sha1_ha...
[ "Check whether the sha1 hash of the file content matches the expected hash.\n\n Parameters\n ----------\n filename : str\n Path to the file.\n sha1_hash : str\n Expected sha1 hash in hexadecimal digits.\n\n Returns\n -------\n bool\n Whether the file content matches the exp...
Please provide a description of the function:def download(url, path=None, overwrite=False, sha1_hash=None, retries=5, verify_ssl=True): if path is None: fname = url.split('/')[-1] # Empty filenames are invalid assert fname, 'Can\'t construct file-name from this URL. ' \ 'Ple...
[ "Download an given URL\n\n Parameters\n ----------\n url : str\n URL to download\n path : str, optional\n Destination path to store downloaded file. By default stores to the\n current directory with same name as in url.\n overwrite : bool, optional\n Whether to overwrite d...
Please provide a description of the function:def _get_repo_url(): default_repo = 'https://apache-mxnet.s3-accelerate.dualstack.amazonaws.com/' repo_url = os.environ.get('MXNET_GLUON_REPO', default_repo) if repo_url[-1] != '/': repo_url = repo_url+'/' return repo_url
[ "Return the base URL for Gluon dataset and model repository." ]
Please provide a description of the function:def _get_repo_file_url(namespace, filename): return '{base_url}{namespace}/{filename}'.format(base_url=_get_repo_url(), namespace=namespace, filename=filename)
[ "Return the URL for hosted file in Gluon repository.\n\n Parameters\n ----------\n namespace : str\n Namespace of the file.\n filename : str\n Name of the file\n " ]
Please provide a description of the function:def _brief_print_list(lst, limit=7): lst = list(lst) if len(lst) > limit: return _brief_print_list(lst[:limit//2], limit) + ', ..., ' + \ _brief_print_list(lst[-limit//2:], limit) return ', '.join(["'%s'"%str(i) for i in lst])
[ "Print at most `limit` elements of list." ]
Please provide a description of the function:def _make_symbol_function(handle, name, func_name): code, doc_str = _generate_symbol_function_code(handle, name, func_name) local = {} exec(code, None, local) # pylint: disable=exec-used symbol_function = local[func_name] symbol_function.__name__ =...
[ "Create a symbol function by handle and function name." ]
Please provide a description of the function:def batch_row_ids(data_batch): item = data_batch.data[0] user = data_batch.data[1] return {'user_weight': user.astype(np.int64), 'item_weight': item.astype(np.int64)}
[ " Generate row ids based on the current mini-batch " ]
Please provide a description of the function:def all_row_ids(data_batch): all_users = mx.nd.arange(0, MOVIELENS['max_user'], dtype='int64') all_movies = mx.nd.arange(0, MOVIELENS['max_movie'], dtype='int64') return {'user_weight': all_users, 'item_weight': all_movies}
[ " Generate row ids for all rows " ]
Please provide a description of the function:def convert_model(prototxt_fname, caffemodel_fname, output_prefix=None): sym, input_dim = convert_symbol(prototxt_fname) arg_shapes, _, aux_shapes = sym.infer_shape(data=tuple(input_dim)) arg_names = sym.list_arguments() aux_names = sym.list_auxiliary_st...
[ "Convert caffe model\n\n Parameters\n ----------\n\n prototxt_fname : str\n Filename of the prototxt model definition\n caffemodel_fname : str\n Filename of the binary caffe model\n output_prefix : str, optinoal\n If given, then save the converted MXNet into output_prefx+'.jso...
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() ret = [] for i in output_name: exec("ret = " + i, globals(), _locals) ...
[ "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 get_vgg(num_layers, pretrained=False, ctx=cpu(), root=os.path.join(base.data_dir(), 'models'), **kwargs): r layers, filters = vgg_spec[num_layers] net = VGG(layers, filters, **kwargs) if pretrained: from ..model_store import get_model_...
[ "VGG model from the `\"Very Deep Convolutional Networks for Large-Scale Image Recognition\"\n <https://arxiv.org/abs/1409.1556>`_ paper.\n\n Parameters\n ----------\n num_layers : int\n Number of layers for the variant of densenet. Options are 11, 13, 16, 19.\n pretrained : bool, default False...
Please provide a description of the function:def check_with_uniform(uf, arg_shapes, dim=None, npuf=None, rmin=-10, type_list=[np.float32]): if isinstance(arg_shapes, int): assert dim shape = tuple(np.random.randint(1, int(1000**(1.0/dim)), size=dim)) arg_shapes = [shape] * arg_shapes ...
[ "check function consistency with uniform random numbers" ]
Please provide a description of the function:def filter_roidb(self): num_roidb = len(self._roidb) self._roidb = [roi_rec for roi_rec in self._roidb if len(roi_rec['gt_classes'])] num_after = len(self._roidb) logger.info('filter roidb: {} -> {}'.format(num_roidb, num_after))
[ "Remove images without usable rois" ]
Please provide a description of the function:def append_flipped_images(self): logger.info('%s append flipped images to roidb' % self._name) roidb_flipped = [] for roi_rec in self._roidb: boxes = roi_rec['boxes'].copy() oldx1 = boxes[:, 0].copy() oldx2...
[ "Only flip boxes coordinates, images will be flipped when loading into network" ]
Please provide a description of the function:def get_model_file(name, root=os.path.join(base.data_dir(), 'models')): r file_name = '{name}-{short_hash}'.format(name=name, short_hash=short_hash(name)) root = os.path.expanduser(root) file_path = os.path.join(ro...
[ "Return location for the pretrained on local file system.\n\n This function will download from online model zoo when model cannot be found or has mismatch.\n The root directory will be created if it doesn't exist.\n\n Parameters\n ----------\n name : str\n Name of the model.\n root : str, d...
Please provide a description of the function:def purge(root=os.path.join(base.data_dir(), 'models')): r root = os.path.expanduser(root) files = os.listdir(root) for f in files: if f.endswith(".params"): os.remove(os.path.join(root, f))
[ "Purge all pretrained model files in local file store.\n\n Parameters\n ----------\n root : str, default '$MXNET_HOME/models'\n Location for keeping the model parameters.\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.image_dir, 'images', name) assert os.path.isfile(image_file),...
[ "\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 _load_all(self, anno_file, shuffle): image_set_index = [] labels = [] coco = COCO(anno_file) img_ids = coco.getImgIds() # deal with class names cats = [cat['name'] for cat in coco.loadCats(coco.getCatIds())] ...
[ "\n initialize all entries given annotation json file\n\n Parameters:\n ----------\n anno_file: str\n annotation json file\n shuffle: bool\n whether to shuffle image list\n " ]
Please provide a description of the function:def init_params(self, initializer=mx.init.Uniform(0.01), **kwargs): self._module.init_params(initializer=initializer, **kwargs)
[ "Initializes the parameters and auxiliary states.\n " ]
Please provide a description of the function:def forward(self, data_batch, is_train=None, carry_state=True): # propagate states from the previous iteration if carry_state: if isinstance(self._next_states, (int, float)): self._module.set_states(value=self._next_states...
[ "Forward computation. States from previous forward computation are carried\n to the current iteration if `carry_state` is set to `True`.\n " ]
Please provide a description of the function:def update(self, max_norm=None): if max_norm is not None: self._clip_by_global_norm(max_norm) self._module.update()
[ "Updates parameters according to the installed optimizer and the gradients computed\n in the previous forward-backward batch. Gradients are clipped by their global norm\n if `max_norm` is set.\n\n Parameters\n ----------\n max_norm: float, optional\n If set, clip values...
Please provide a description of the function:def _clip_by_global_norm(self, max_norm): assert self._module.binded and self._module.params_initialized \ and self._module.optimizer_initialized grad_array = [] for grad in self._module._exec_group.grad_arrays: gra...
[ "Clips gradient norm.\n\n The norm is computed over all gradients together, as if they were\n concatenated into a single vector. Gradients are modified in-place.\n The method is first used in\n `[ICML2013] On the difficulty of training recurrent neural networks`\n\n Parameters\n ...
Please provide a description of the function:def visual(title, X, name): assert len(X.shape) == 4 X = X.transpose((0, 2, 3, 1)) X = np.clip((X - np.min(X))*(255.0/(np.max(X) - np.min(X))), 0, 255).astype(np.uint8) n = np.ceil(np.sqrt(X.shape[0])) buff = np.zeros((int(n*X.shape[1]), int(n*X.shap...
[ "Image visualization and preservation\n :param title: title\n :param X: images to visualized\n :param name: saved picture`s name\n :return:\n " ]
Please provide a description of the function:def transformer(data, label): # resize to 64x64 data = mx.image.imresize(data, 64, 64) # transpose from (64, 64, 3) to (3, 64, 64) data = mx.nd.transpose(data, (2, 0, 1)) # normalize to [-1, 1] data = data.astype(np.float32)/128 - 1 # if imag...
[ "Get the translation of images" ]
Please provide a description of the function:def get_dataset(dataset_name): # mnist if dataset == "mnist": train_data = gluon.data.DataLoader( gluon.data.vision.MNIST('./data', train=True, transform=transformer), batch_size, shuffle=True, last_batch='discard') val_d...
[ "Load the dataset and split it to train/valid data\n\n :param dataset_name: string\n\n Returns:\n train_data: int array\n training dataset\n val_data: int array\n valid dataset\n " ]
Please provide a description of the function:def get_netG(): # build the generator netG = nn.Sequential() with netG.name_scope(): # input is Z, going into a convolution netG.add(nn.Conv2DTranspose(ngf * 8, 4, 1, 0, use_bias=False)) netG.add(nn.BatchNorm()) netG.add(nn.Ac...
[ "Get net G" ]
Please provide a description of the function:def get_netD(): # build the discriminator netD = nn.Sequential() with netD.name_scope(): # input is (nc) x 64 x 64 netD.add(nn.Conv2D(ndf, 4, 2, 1, use_bias=False)) netD.add(nn.LeakyReLU(0.2)) # state size. (ndf) x 32 x 32 ...
[ "Get the netD" ]
Please provide a description of the function:def get_configurations(netG, netD): # loss loss = gluon.loss.SoftmaxCrossEntropyLoss() # initialize the generator and the discriminator netG.initialize(mx.init.Normal(0.02), ctx=ctx) netD.initialize(mx.init.Normal(0.02), ctx=ctx) # trainer for ...
[ "Get configurations for net" ]
Please provide a description of the function:def main(): print("|------- new changes!!!!!!!!!") # to get the dataset and net configuration train_data, val_data = get_dataset(dataset) netG = get_netG() netD = get_netD() loss, trainerG, trainerD = get_configurations(netG, netD) # set lab...
[ "Entry point to dcgan" ]
Please provide a description of the function:def getLogger(name=None, filename=None, filemode=None, level=WARNING): warnings.warn("getLogger is deprecated, Use get_logger instead.", DeprecationWarning, stacklevel=2) return get_logger(name, filename, filemode, level)
[ "Gets a customized logger.\n\n .. note:: `getLogger` is deprecated. Use `get_logger` instead.\n\n " ]
Please provide a description of the function:def get_logger(name=None, filename=None, filemode=None, level=WARNING): logger = logging.getLogger(name) if name is not None and not getattr(logger, '_init_done', None): logger._init_done = True if filename: mode = filemode if filemod...
[ "Gets a customized logger.\n\n Parameters\n ----------\n name: str, optional\n Name of the logger.\n filename: str, optional\n The filename to which the logger's output will be sent.\n filemode: str, optional\n The file mode to open the file (corresponding to `filename`),\n ...
Please provide a description of the function:def transformer(data, label): data = mx.image.imresize(data, IMAGE_SIZE, IMAGE_SIZE) data = mx.nd.transpose(data, (2, 0, 1)) data = data.astype(np.float32) / 128.0 - 1 return data, label
[ " data preparation " ]
Please provide a description of the function:def get_training_data(batch_size): return gluon.data.DataLoader( CIFAR10(train=True, transform=transformer), batch_size=batch_size, shuffle=True, last_batch='discard')
[ " helper function to get dataloader" ]
Please provide a description of the function:def get_resnet(version, num_layers, pretrained=False, ctx=cpu(), root=os.path.join(base.data_dir(), 'models'), **kwargs): r assert num_layers in resnet_spec, \ "Invalid number of layers: %d. Options are %s"%( num_layers, str(resnet_...
[ "ResNet V1 model from `\"Deep Residual Learning for Image Recognition\"\n <http://arxiv.org/abs/1512.03385>`_ paper.\n ResNet V2 model from `\"Identity Mappings in Deep Residual Networks\"\n <https://arxiv.org/abs/1603.05027>`_ paper.\n\n Parameters\n ----------\n version : int\n Version of...
Please provide a description of the function:def _random_helper(random, sampler, params, shape, dtype, kwargs): if isinstance(params[0], Symbol): for i in params[1:]: assert isinstance(i, Symbol), \ "Distribution parameters must all have the same type, but got " \ ...
[ "Helper function for random generators." ]
Please provide a description of the function:def poisson(lam=1, shape=_Null, dtype=_Null, **kwargs): return _random_helper(_internal._random_poisson, _internal._sample_poisson, [lam], shape, dtype, kwargs)
[ "Draw random samples from a Poisson distribution.\n\n Samples are distributed according to a Poisson distribution parametrized\n by *lambda* (rate). Samples will always be returned as a floating point data type.\n\n Parameters\n ----------\n lam : float or Symbol, optional\n Expectation of int...
Please provide a description of the function:def generalized_negative_binomial(mu=1, alpha=1, shape=_Null, dtype=_Null, **kwargs): return _random_helper(_internal._random_generalized_negative_binomial, _internal._sample_generalized_negative_binomial, [mu, alp...
[ "Draw random samples from a generalized negative binomial distribution.\n\n Samples are distributed according to a generalized negative binomial\n distribution parametrized by *mu* (mean) and *alpha* (dispersion).\n *alpha* is defined as *1/k* where *k* is the failure limit of the\n number of unsuccessf...
Please provide a description of the function:def multinomial(data, shape=_Null, get_prob=True, dtype='int32', **kwargs): return _internal._sample_multinomial(data, shape, get_prob, dtype=dtype, **kwargs)
[ "Concurrent sampling from multiple multinomial distributions.\n\n .. note:: The input distribution must be normalized, i.e. `data` must sum to\n 1 along its last dimension.\n\n Parameters\n ----------\n data : Symbol\n An *n* dimensional array whose last dimension has length `k`, whe...