INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
The data types of the aux data for the BaseSparseNDArray. | def _aux_types(self):
"""The data types of the aux data for the BaseSparseNDArray.
"""
aux_types = []
num_aux = self._num_aux
for i in range(num_aux):
aux_types.append(self._aux_type(i))
return aux_types |
Return a copy of the array after casting to a specified type. | def astype(self, dtype, copy=True):
"""Return a copy of the array after casting to a specified type.
Parameters
----------
dtype : numpy.dtype or str
The type of the returned array.
copy : bool
Default `True`. By default, astype always returns a newly
... |
Check whether the NDArray format is valid. | def check_format(self, full_check=True):
"""Check whether the NDArray format is valid.
Parameters
----------
full_check : bool, optional
If `True`, rigorous check, O(N) operations. Otherwise
basic check, O(1) operations (default True).
"""
check_c... |
A deep copy NDArray of the data array associated with the BaseSparseNDArray. | def _data(self):
"""A deep copy NDArray of the data array associated with the BaseSparseNDArray.
This function blocks. Do not use it in performance critical code.
"""
self.wait_to_read()
hdl = NDArrayHandle()
check_call(_LIB.MXNDArrayGetDataNDArray(self.handle, ctypes.by... |
Get a deep copy NDArray of the i - th aux data array associated with the BaseSparseNDArray. | def _aux_data(self, i):
""" Get a deep copy NDArray of the i-th aux data array associated with the
BaseSparseNDArray.
This function blocks. Do not use it in performance critical code.
"""
self.wait_to_read()
hdl = NDArrayHandle()
check_call(_LIB.MXNDArrayGetAuxND... |
Returns a scipy. sparse. csr. csr_matrix object with value copied from this array | def asscipy(self):
"""Returns a ``scipy.sparse.csr.csr_matrix`` object with value copied from this array
Examples
--------
>>> x = mx.nd.sparse.zeros('csr', (2,3))
>>> y = x.asscipy()
>>> type(y)
<type 'scipy.sparse.csr.csr_matrix'>
>>> y
<2x3 spa... |
Return a copy of the array with chosen storage type. | def tostype(self, stype):
"""Return a copy of the array with chosen storage type.
Returns
-------
NDArray or RowSparseNDArray
A copy of the array with the chosen storage stype
"""
# pylint: disable= no-member, protected-access
if stype == 'csr':
... |
Copies the value of this array to another array. | def copyto(self, other):
"""Copies the value of this array to another array.
If ``other`` is a ``NDArray`` or ``RowSparseNDArray`` object, then ``other.shape``
and ``self.shape`` should be the same. This function copies the value from
``self`` to ``other``.
If ``other`` is a co... |
Exports the MXNet model file passed as a parameter into ONNX model. Accepts both symbol parameter objects as well as json and params filepaths as input. Operator support and coverage - https:// cwiki. apache. org/ confluence/ display/ MXNET/ MXNet - ONNX + Integration | def export_model(sym, params, input_shape, input_type=np.float32,
onnx_file_path='model.onnx', verbose=False):
"""Exports the MXNet model file, passed as a parameter, into ONNX model.
Accepts both symbol,parameter objects as well as json and params filepaths as input.
Operator support and c... |
Benchmarking both storage and dot | 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"):
""" Benchmarking both storage and dot
"""
lhs_nd = rand_ndarray((lhs_row_dim, lhs_col_dim), lhs_stype, density, distributio... |
Convert caffe mean | def convert_mean(binaryproto_fname, output=None):
"""Convert caffe mean
Parameters
----------
binaryproto_fname : str
Filename of the mean
output : str, optional
Save the mean into mxnet's format
Returns
-------
NDArray
Mean in ndarray
"""
mean_blob = ca... |
r Densenet - BC model from the Densely Connected Convolutional Networks <https:// arxiv. org/ pdf/ 1608. 06993. pdf > _ paper. | def get_densenet(num_layers, pretrained=False, ctx=cpu(),
root=os.path.join(base.data_dir(), 'models'), **kwargs):
r"""Densenet-BC model from the
`"Densely Connected Convolutional Networks" <https://arxiv.org/pdf/1608.06993.pdf>`_ paper.
Parameters
----------
num_layers : int
... |
Loads the MXNet model file and returns MXNet symbol and params ( weights ). | def load_module(sym_filepath, params_filepath):
"""Loads the MXNet model file and
returns MXNet symbol and params (weights).
Parameters
----------
json_path : str
Path to the json file
params_path : str
Path to the params file
Returns
-------
sym : MXNet symbol
... |
Helper function to import module | def import_module(module_name):
"""Helper function to import module"""
import sys, os
import importlib
sys.path.append(os.path.dirname(__file__))
return importlib.import_module(module_name) |
Build network symbol for training SSD | 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):
"""Build network symbol for training SSD
Parameters
------... |
Build network for testing SSD | 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):
"""Build network for testing SSD
Parameters
----------
network : str
... |
This is an internal helper function that can be used for either of these but not both at the same time: 1. Record the output and gradient of output of an intermediate convolutional layer. 2. Record the gradients of the image. | def _get_grad(net, image, class_id=None, conv_layer_name=None, image_grad=False):
"""This is an internal helper function that can be used for either of these
but not both at the same time:
1. Record the output and gradient of output of an intermediate convolutional layer.
2. Record the gradients of the ... |
Get the output and gradients of output of a convolutional layer. | def get_conv_out_grad(net, image, class_id=None, conv_layer_name=None):
"""Get the output and gradients of output of a convolutional layer.
Parameters:
----------
net: Block
Network to use for visualization.
image: NDArray
Preprocessed image to use for visualization.
class_id: i... |
Get the gradients of the image. | def get_image_grad(net, image, class_id=None):
"""Get the gradients of the image.
Parameters:
----------
net: Block
Network to use for visualization.
image: NDArray
Preprocessed image to use for visualization.
class_id: int
Category ID this image belongs to. If not provi... |
Convert gradients of image obtained using get_image_grad into image. This shows parts of the image that is most strongly activating the output neurons. | def grad_to_image(gradient):
"""Convert gradients of image obtained using `get_image_grad`
into image. This shows parts of the image that is most strongly activating
the output neurons."""
gradient = gradient - gradient.min()
gradient /= gradient.max()
gradient = np.uint8(gradient * 255).transpo... |
Compute CAM. Refer section 3 of https:// arxiv. org/ abs/ 1610. 02391 for details | def get_cam(imggrad, conv_out):
"""Compute CAM. Refer section 3 of https://arxiv.org/abs/1610.02391 for details"""
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, (i... |
Draw a heatmap on top of the original image using intensities from activation_map | def get_img_heatmap(orig_img, activation_map):
"""Draw a heatmap on top of the original image using intensities from 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... |
Convert gradients to grayscale. This gives a saliency map. | def to_grayscale(cv2im):
"""Convert gradients to grayscale. This gives a saliency map."""
# 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(grays... |
Helper function for checking shape of label and prediction | def check_label_shapes(labels, preds, wrap=False, shape=False):
"""Helper function for checking shape of label and prediction
Parameters
----------
labels : list of `NDArray`
The labels of the data.
preds : list of `NDArray`
Predicted values.
wrap : boolean
If True, wr... |
Creates evaluation metric from metric names or instances of EvalMetric or a custom metric function. | def create(metric, *args, **kwargs):
"""Creates evaluation metric from metric names or instances of EvalMetric
or a custom metric function.
Parameters
----------
metric : str or callable
Specifies the metric to create.
This argument must be one of the below:
- Name of a met... |
Creates a custom evaluation metric that receives its inputs as numpy arrays. | def np(numpy_feval, name=None, allow_extra_outputs=False):
"""Creates a custom evaluation metric that receives its inputs as numpy arrays.
Parameters
----------
numpy_feval : callable(label, pred)
Custom evaluation function that receives labels and predictions for a minibatch
as numpy a... |
Save configurations of metric. Can be recreated from configs with metric. create ( ** config ) | def get_config(self):
"""Save configurations of metric. Can be recreated
from configs with metric.create(``**config``)
"""
config = self._kwargs.copy()
config.update({
'metric': self.__class__.__name__,
'name': self.name,
'output_names': self.o... |
Update the internal evaluation with named label and pred | def update_dict(self, label, pred):
"""Update the internal evaluation with named label and pred
Parameters
----------
labels : OrderedDict of str -> NDArray
name to array mapping for labels.
preds : OrderedDict of str -> NDArray
name to array mapping of ... |
Resets the internal evaluation result to initial state. | def reset(self):
"""Resets the internal evaluation result to initial state."""
self.num_inst = 0
self.sum_metric = 0.0
self.global_num_inst = 0
self.global_sum_metric = 0.0 |
Gets the current evaluation result. | def get(self):
"""Gets the current evaluation result.
Returns
-------
names : list of str
Name of the metrics.
values : list of float
Value of the evaluations.
"""
if self.num_inst == 0:
return (self.name, float('nan'))
e... |
Gets the current global evaluation result. | def get_global(self):
"""Gets the current global evaluation result.
Returns
-------
names : list of str
Name of the metrics.
values : list of float
Value of the evaluations.
"""
if self._has_global_stats:
if self.global_num_inst ... |
Returns zipped name and value pairs. | def get_name_value(self):
"""Returns zipped name and value pairs.
Returns
-------
list of tuples
A (name, value) tuple list.
"""
name, value = self.get()
if not isinstance(name, list):
name = [name]
if not isinstance(value, list):
... |
Returns zipped name and value pairs for global results. | def get_global_name_value(self):
"""Returns zipped name and value pairs for global results.
Returns
-------
list of tuples
A (name, value) tuple list.
"""
if self._has_global_stats:
name, value = self.get_global()
if not isinstance(nam... |
Update various binary classification counts for a single ( label pred ) pair. | def update_binary_stats(self, label, pred):
"""
Update various binary classification counts for a single (label, pred)
pair.
Parameters
----------
label : `NDArray`
The labels of the data.
pred : `NDArray`
Predicted values.
"""
... |
Calculate the Matthew s Correlation Coefficent | def matthewscc(self, use_global=False):
"""
Calculate the Matthew's Correlation Coefficent
"""
if use_global:
if not self.global_total_examples:
return 0.
true_pos = float(self.global_true_positives)
false_pos = float(self.global_false... |
Returns a new dataset with each sample transformed by the transformer function fn. | def transform(self, fn, lazy=True):
"""Returns a new dataset with each sample transformed by the
transformer function `fn`.
Parameters
----------
fn : callable
A transformer function that takes a sample as input and
returns the transformed sample.
... |
Returns a new dataset with the first element of each sample transformed by the transformer function fn. | def transform_first(self, fn, lazy=True):
"""Returns a new dataset with the first element of each sample
transformed by the transformer function `fn`.
This is useful, for example, when you only want to transform data
while keeping label as is.
Parameters
----------
... |
Forward the image through the LSTM network model | def forward_ocr(self, img_):
"""Forward the image through the LSTM network model
Parameters
----------
img_: int of array
Returns
----------
label_list: string of list
"""
img_ = cv2.resize(img_, (80, 30))
img_ = img_.transpose(1, 0)
... |
Return a caffe_pb2. NetParameter object that defined in a prototxt file | def read_prototxt(fname):
"""Return a caffe_pb2.NetParameter object that defined in a prototxt file
"""
proto = caffe_pb2.NetParameter()
with open(fname, 'r') as f:
text_format.Merge(str(f.read()), proto)
return proto |
Returns layers in a caffe_pb2. NetParameter object | def get_layers(proto):
"""Returns layers in a caffe_pb2.NetParameter object
"""
if len(proto.layer):
return proto.layer
elif len(proto.layers):
return proto.layers
else:
raise ValueError('Invalid proto file.') |
Return a caffe_pb2. NetParameter object that defined in a binary caffemodel file | def read_caffemodel(prototxt_fname, caffemodel_fname):
"""Return a caffe_pb2.NetParameter object that defined in a binary
caffemodel file
"""
if use_caffe:
caffe.set_mode_cpu()
net = caffe.Net(prototxt_fname, caffemodel_fname, caffe.TEST)
layer_names = net._layer_names
la... |
Iterate over all layers | def layer_iter(layers, layer_names):
"""Iterate over all layers"""
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 (layer_name, layer_... |
Set up the configure of profiler ( only accepts keyword arguments ). | def set_config(**kwargs):
"""Set up the configure of profiler (only accepts keyword arguments).
Parameters
----------
filename : string,
output file for profile data
profile_all : boolean,
all profile types enabled
profile_symbolic : boolean,
whether to profile symbolic ... |
Set up the configure of profiler ( Deprecated ). | def profiler_set_config(mode='symbolic', filename='profile.json'):
"""Set up the configure of profiler (Deprecated).
Parameters
----------
mode : string, optional
Indicates whether to enable the profiler, can
be 'symbolic', or 'all'. Defaults to `symbolic`.
filename : string, option... |
Set up the profiler state to run or stop. | def set_state(state='stop', profile_process='worker'):
"""Set up the profiler state to 'run' or 'stop'.
Parameters
----------
state : string, optional
Indicates whether to run the profiler, can
be 'stop' or 'run'. Default is `stop`.
profile_process : string
whether to profil... |
Dump profile and stop profiler. Use this to save profile in advance in case your program cannot exit normally. | def dump(finished=True, profile_process='worker'):
"""Dump profile and stop profiler. Use this to save profile
in advance in case your program cannot exit normally.
Parameters
----------
finished : boolean
Indicates whether to stop statistic output (dumping) after this dump.
Default... |
Return a printable string of aggregate profile stats. | def dumps(reset=False):
"""Return a printable string of aggregate profile stats.
Parameters
----------
reset: boolean
Indicates whether to clean aggeregate statistical data collected up to this point
"""
debug_str = ctypes.c_char_p()
do_reset = 1 if reset is True else 0
check_ca... |
Pause profiling. | def pause(profile_process='worker'):
"""Pause profiling.
Parameters
----------
profile_process : string
whether to profile kvstore `server` or `worker`.
server can only be profiled when kvstore is of type dist.
if this is not passed, defaults to `worker`
"""
profile_proc... |
Resume paused profiling. | def resume(profile_process='worker'):
"""
Resume paused profiling.
Parameters
----------
profile_process : string
whether to profile kvstore `server` or `worker`.
server can only be profiled when kvstore is of type dist.
if this is not passed, defaults to `worker`
"""
... |
Set counter value. | def set_value(self, value):
"""Set counter value.
Parameters
----------
value : int
Value for the counter
"""
check_call(_LIB.MXProfileSetCounter(self.handle, int(value))) |
Increment counter value. | def increment(self, delta=1):
"""Increment counter value.
Parameters
----------
value_change : int
Amount by which to add to the counter
"""
check_call(_LIB.MXProfileAdjustCounter(self.handle, int(delta))) |
Decrement counter value. | def decrement(self, delta=1):
"""Decrement counter value.
Parameters
----------
value_change : int
Amount by which to subtract from the counter
"""
check_call(_LIB.MXProfileAdjustCounter(self.handle, -int(delta))) |
Set up the profiler state to record operator. | def mark(self, scope='process'):
"""Set up the profiler state to record operator.
Parameters
----------
scope : string, optional
Indicates what scope the marker should refer to.
Can be 'global', 'process', thread', task', and 'marker'
Default is `proc... |
r Get CUDA kernel from compiled module. | def get_kernel(self, name, signature):
r"""Get CUDA kernel from compiled module.
Parameters
----------
name : str
String name of the kernel.
signature : str
Function signature for the kernel. For example, if a kernel is
declared as::
... |
Launch cuda kernel. | def launch(self, args, ctx, grid_dims, block_dims, shared_mem=0):
"""Launch cuda kernel.
Parameters
----------
args : tuple of NDArray or numbers
List of arguments for kernel. NDArrays are expected for pointer
types (e.g. `float*`, `double*`) while numbers are ex... |
Clear the internal statistics to initial state. | def reset(self):
"""Clear the internal statistics to initial state."""
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 = dic... |
Update internal records. This function now only update internal buffer sum_metric and num_inst are updated in _update () function instead when get () is called to return results. | def update(self, labels, preds):
"""
Update internal records. This function now only update internal buffer,
sum_metric and num_inst are updated in _update() function instead when
get() is called to return results.
Params:
----------
labels: mx.nd.array (n * 6) o... |
update num_inst and sum_metric | def _update(self):
""" update num_inst and sum_metric """
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 < (self... |
get recall and precision from internal records | def _recall_prec(self, record, count):
""" get recall and precision from internal records """
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)
... |
calculate average precision | def _average_precision(self, rec, prec):
"""
calculate average precision
Params:
----------
rec : numpy.array
cumulated recall
prec : numpy.array
cumulated precision
Returns:
----------
ap as float
"""
# app... |
Insert records according to key | def _insert(self, key, records, count):
""" Insert records according to key """
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[key], r... |
calculate average precision override the default one special 11 - point metric | def _average_precision(self, rec, prec):
"""
calculate average precision, override the default one,
special 11-point metric
Params:
----------
rec : numpy.array
cumulated recall
prec : numpy.array
cumulated precision
Returns:
... |
symbol: the pre - trained network symbol arg_params: the argument parameters of the pre - trained model num_classes: the number of classes for the fine - tune datasets layer_name: the layer name before the last fully - connected layer | def get_fine_tune_model(symbol, arg_params, num_classes, layer_name, dtype='float32'):
"""
symbol: the pre-trained network symbol
arg_params: the argument parameters of the pre-trained model
num_classes: the number of classes for the fine-tune datasets
layer_name: the layer name before the last full... |
Description: generate list for lip images | def _list_images(self, root):
"""
Description : generate list for lip images
"""
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... |
Description: Align to lip position | def align_generation(self, file_nm, padding=75):
"""
Description : Align to lip position
"""
align = Align(self._align_root + '/' + file_nm + '.align')
return nd.array(align.sentence(padding)) |
Switch on/ off verbose mode | def set_verbosity(self, verbose=False, print_func=None):
"""Switch on/off verbose mode
Parameters
----------
verbose : bool
switch on/off verbose mode
print_func : function
A function that computes statistics of initialized arrays.
Takes an `N... |
Internal verbose print function | def _verbose_print(self, desc, init, arr):
"""Internal verbose print function
Parameters
----------
desc : InitDesc or str
name of the array
init : str
initializer pattern
arr : NDArray
initialized array
"""
if self._ve... |
Legacy initialization method. | def _legacy_init(self, name, arr):
"""Legacy initialization method.
Parameters
----------
name : str
Name of corresponding NDArray.
arr : NDArray
NDArray to be initialized.
"""
warnings.warn(
"\033[91mCalling initializer with ... |
save imglist to disk | def save_imglist(self, fname=None, root=None, shuffle=False):
"""
save imglist to disk
Parameters:
----------
fname : str
saved filename
"""
def progress_bar(count, total, suffix=''):
import sys
bar_len = 24
filled_... |
load class names from text file | def _load_class_names(self, filename, dirname):
"""
load class names from text file
Parameters:
----------
filename: str
file stores class names
dirname: str
file directory
"""
full_path = osp.join(dirname, filename)
classe... |
download and read data into numpy | def read_data(label, image):
"""
download and read data into numpy
"""
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(), ... |
create data iterator with NDArrayIter | def get_mnist_iter(args, kv):
"""
create data iterator with NDArrayIter
"""
(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... |
Function factory for file extension argparse assertion Args: extension ( string ): the file extension to assert | def make_file_extension_assertion(extension):
"""Function factory for file extension argparse assertion
Args:
extension (string): the file extension to assert
Returns:
string: the supplied extension, if assertion is successful.
"""
def file_extension_assertion(file_... |
generates the colormap for visualizing the segmentation mask Args: num_colors ( int ): the number of colors to generate in the output palette | def get_palette(num_colors=256):
"""generates the colormap for visualizing the segmentation mask
Args:
num_colors (int): the number of colors to generate in the output palette
Returns:
string: the supplied extension, if assertion is successful.
"""
p... |
get the ( 1 3 h w ) np. array data for the supplied image Args: img_path ( string ): the input image path | def get_data(img_path):
"""get the (1, 3, h, w) np.array data for the supplied image
Args:
img_path (string): the input image path
Returns:
np.array: image data in a (1, 3, h, w) shape
"""
mean = np.array([123.68, 116.779, 103.939]) ... |
Module main execution | def main():
"""Module main execution"""
# 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, fcnxs_auxs = mx.... |
check input imdbs make sure they have same classes | def _check_classes(self):
"""
check input imdbs, make sure they have same classes
"""
try:
self.classes = self.imdbs[0].classes
self.num_classes = len(self.classes)
except AttributeError:
# fine, if no classes is provided
pass
... |
get total number of images init indices | def _load_image_set_index(self, shuffle):
"""
get total number of images, init indices
Parameters
----------
shuffle : bool
whether to shuffle the initial indices
"""
self.num_images = 0
for db in self.imdbs:
self.num_images += db.... |
given index find out sub - db and sub - index | def _locate_index(self, index):
"""
given index, find out sub-db and sub-index
Parameters
----------
index : int
index of a specific image
Returns
----------
a tuple (sub-db, sub-index)
"""
assert index >= 0 and index < self.n... |
given image index find out full path | def image_path_from_index(self, index):
"""
given image index, find out full path
Parameters
----------
index: int
index of a specific image
Returns
----------
full path of this image
"""
assert self.image_set_index is not Non... |
Callback to checkpoint Module to prefix every epoch. | def module_checkpoint(mod, prefix, period=1, save_optimizer_states=False):
"""Callback to checkpoint Module to prefix every epoch.
Parameters
----------
mod : subclass of BaseModule
The module to checkpoint.
prefix : str
The file prefix for this checkpoint.
period : int
... |
A callback that saves a model checkpoint every few epochs. Each checkpoint is made up of a couple of binary files: a model description file and a parameters ( weights and biases ) file. The model description file is named prefix -- symbol. json and the parameters file is named prefix - epoch_number. params | def do_checkpoint(prefix, period=1):
"""A callback that saves a model checkpoint every few epochs.
Each checkpoint is made up of a couple of binary files: a model description file and a
parameters (weights and biases) file. The model description file is named
`prefix`--symbol.json and the parameters fil... |
Callback to log the training evaluation result every period. | def log_train_metric(period, auto_reset=False):
"""Callback to log the training evaluation result every period.
Parameters
----------
period : int
The number of batch to log the training evaluation metric.
auto_reset : bool
Reset the metric after each log.
Returns
-------
... |
install callback to executor. Supports installing to multiple exes. | def install(self, exe):
"""install callback to executor.
Supports installing to multiple exes.
Parameters
----------
exe : mx.executor.Executor
The Executor (returned by symbol.bind) to install to.
"""
exe.set_monitor_callback(self.stat_helper, self.m... |
Start collecting stats for current batch. Call before calling forward. | def tic(self):
"""Start collecting stats for current batch.
Call before calling forward."""
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:
... |
End collecting for current batch and return results. Call after computation of current batch. | def toc(self):
"""End collecting for current batch and return results.
Call after computation of current batch.
Returns
-------
res : list of """
if not self.activated:
return []
for exe in self.exes:
for array in exe.arg_arrays:
... |
End collecting and print results. | def toc_print(self):
"""End collecting and print results."""
res = self.toc()
for n, k, v in res:
logging.info('Batch: {:7d} {:30s} {:s}'.format(n, k, v)) |
make a random data iteration plan | 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.batch_size))
self.data[i] = self.data... |
Expand the pending files in the current stage. | def expand(x, pending, stage):
"""
Expand the pending files in the current stage.
Parameters
----------
x: str
The file to expand.
pending : str
The list of pending files to expand.
stage: str
The current stage for file expansion, used for matching the prefix of f... |
Dataset loader with preprocessing. | def get_imagenet_iterator(root, batch_size, num_workers, data_shape=224, dtype='float32'):
"""Dataset loader with preprocessing."""
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 take a b... |
Creates an instance of token embedding. | def create(embedding_name, **kwargs):
"""Creates an instance of token embedding.
Creates a token embedding instance by loading embedding vectors from an externally hosted
pre-trained token embedding file, such as those of GloVe and FastText. To get all the valid
`embedding_name` and `pretrained_file_n... |
Get valid token embedding names and their pre - trained file names. | def get_pretrained_file_names(embedding_name=None):
"""Get valid token embedding names and their pre-trained file names.
To load token embedding vectors from an externally hosted pre-trained token embedding file,
such as those of GloVe and FastText, one should use
`mxnet.contrib.text.embedding.create(... |
Load embedding vectors from the pre - trained token embedding file. | def _load_embedding(self, pretrained_file_path, elem_delim, init_unknown_vec, encoding='utf8'):
"""Load embedding vectors from the pre-trained token embedding file.
For every unknown token, if its representation `self.unknown_token` is encountered in the
pre-trained token embedding file, index... |
Sets the mapping between token indices and token embedding vectors. | def _set_idx_to_vec_by_embeddings(self, token_embeddings, vocab_len, vocab_idx_to_token):
"""Sets the mapping between token indices and token embedding vectors.
Parameters
----------
token_embeddings : instance or list `mxnet.contrib.text.embedding._TokenEmbedding`
One or m... |
Look up embedding vectors of tokens. | def get_vecs_by_tokens(self, tokens, lower_case_backup=False):
"""Look up embedding vectors of tokens.
Parameters
----------
tokens : str or list of strs
A token or a list of tokens.
lower_case_backup : bool, default False
If False, each token in the ori... |
Updates embedding vectors for tokens. | def update_token_vectors(self, tokens, new_vectors):
"""Updates embedding vectors for tokens.
Parameters
----------
tokens : str or a list of strs
A token or a list of tokens whose embedding vector are to be updated.
new_vectors : mxnet.ndarray.NDArray
A... |
Checks if a pre - trained token embedding file name is valid. | def _check_pretrained_file_names(cls, pretrained_file_name):
"""Checks if a pre-trained token embedding file name is valid.
Parameters
----------
pretrained_file_name : str
The pre-trained token embedding file.
"""
embedding_name = cls.__name__.lower()
... |
Calculate gradient | def calc_grad(exe, exe_grads, params, X, Y, label_name=None, outgrad_f=None):
"""Calculate gradient"""
exe.copy_params_from(params)
exe.arg_dict['data'][:] = X
if outgrad_f is None:
exe.arg_dict[label_name][:] = Y
exe.forward(is_train=True)
exe.backward()
else:
exe.fo... |
Generate the implementation of step HMC | def step_HMC(exe, exe_params, exe_grads, label_key, noise_precision, prior_precision, L=10, eps=1E-6):
"""Generate the implementation of step HMC"""
init_params = {k: v.copyto(v.context) for k, v in exe_params.items()}
end_params = {k: v.copyto(v.context) for k, v in exe_params.items()}
init_momentums =... |
Generate the implementation of HMC | def HMC(sym, data_inputs, X, Y, X_test, Y_test, sample_num,
initializer=None, noise_precision=1 / 9.0, prior_precision=0.1,
learning_rate=1E-6, L=10, dev=mx.gpu()):
"""Generate the implementation of HMC"""
label_key = list(set(data_inputs.keys()) - set(['data']))[0]
exe, exe_params, exe_grad... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.