Code stringlengths 103 85.9k | Summary listlengths 0 94 |
|---|---|
Please provide a description of the function:def to_array(tensor): # type: (TensorProto) -> np.ndarray[Any]
if tensor.HasField("segment"):
raise ValueError(
"Currently not supporting loading segments.")
if tensor.data_type == TensorProto.UNDEFINED:
raise ValueError("The data ty... | [
"Converts a tensor def object to a numpy array.\n\n Inputs:\n tensor: a TensorProto object.\n Returns:\n arr: the converted array.\n "
] |
Please provide a description of the function:def from_array(arr, name=None): # type: (np.ndarray[Any], Optional[Text]) -> TensorProto
tensor = TensorProto()
tensor.dims.extend(arr.shape)
if name:
tensor.name = name
if arr.dtype == np.object:
# Special care for strings.
ten... | [
"Converts a numpy array to a tensor def.\n\n Inputs:\n arr: a numpy array.\n name: (optional) the name of the tensor.\n Returns:\n tensor_def: the converted tensor def.\n "
] |
Please provide a description of the function:def _serialize(proto): # type: (Union[bytes, google.protobuf.message.Message]) -> bytes
'''
Serialize a in-memory proto to bytes
@params
proto is a in-memory proto, such as a ModelProto, TensorProto, etc
@return
Serialized proto in bytes
'''
... | [] |
Please provide a description of the function:def _deserialize(s, proto): # type: (bytes, _Proto) -> _Proto
'''
Parse bytes into a in-memory proto
@params
s is bytes containing serialized proto
proto is a in-memory proto object
@return
The proto instance filled in by s
'''
if not i... | [] |
Please provide a description of the function:def load_model(f, format=None, load_external_data=True): # type: (Union[IO[bytes], Text], Optional[Any], bool) -> ModelProto
'''
Loads a serialized ModelProto into memory
@params
f can be a file-like object (has "read" function) or a string containing a fil... | [] |
Please provide a description of the function:def load_tensor(f, format=None): # type: (Union[IO[bytes], Text], Optional[Any]) -> TensorProto
'''
Loads a serialized TensorProto into memory
@params
f can be a file-like object (has "read" function) or a string containing a file name
format is for fut... | [] |
Please provide a description of the function:def save_model(proto, f, format=None): # type: (Union[ModelProto, bytes], Union[IO[bytes], Text], Optional[Any]) -> None
'''
Saves the ModelProto to the specified path.
@params
proto should be a in-memory ModelProto
f can be a file-like object (has "wri... | [] |
Please provide a description of the function:def polish_model(model): # type: (ModelProto) -> ModelProto
'''
This function combines several useful utility functions together.
'''
onnx.checker.check_model(model)
onnx.helper.strip_doc_string(model)
model = onnx.shape_inference.infer_shapes(mo... | [] |
Please provide a description of the function:def dynamic_unroll(cell, inputs, begin_state, drop_inputs=0, drop_outputs=0,
layout='TNC', valid_length=None):
# Merge is always True, so we don't need length.
inputs, axis, F, _ = _format_sequence(0, inputs, layout, True)
if axis != 0:
... | [
"Unrolls an RNN cell across time steps.\n\n Currently, 'TNC' is a preferred layout. unroll on the input of this layout\n runs much faster.\n\n Parameters\n ----------\n cell : an object whose base class is RNNCell.\n The RNN cell to run on the input sequence.\n inputs : Symbol\n It s... |
Please provide a description of the function:def unroll(self, length, inputs, begin_state=None, layout='NTC', merge_outputs=None,
valid_length=None):
# Dropout on inputs and outputs can be performed on the whole sequence
# only when state dropout is not present.
if self.... | [
"Unrolls an RNN cell across time steps.\n\n Parameters\n ----------\n length : int\n Number of steps to unroll.\n inputs : Symbol, list of Symbol, or None\n If `inputs` is a single Symbol (usually the output\n of Embedding symbol), it should have shape\n ... |
Please provide a description of the function:def _fix_attribute_names(attrs, change_map):
new_attr = {}
for k in attrs.keys():
if k in change_map:
new_attr[change_map[k]] = attrs[k]
else:
new_attr[k] = attrs[k]
return new_attr | [
"\n Change attribute names as per values in change_map dictionary.\n Parameters\n ----------\n :param attrs : dict Dict of operator attributes\n :param change_map : dict Dict of onnx attribute name to mxnet attribute names.\n\n Returns\n -------\n :return new_attr : dict Converted dict of op... |
Please provide a description of the function:def _remove_attributes(attrs, remove_list):
new_attrs = {}
for attr in attrs.keys():
if attr not in remove_list:
new_attrs[attr] = attrs[attr]
return new_attrs | [
"\n Removes attributes in the remove list from the input attribute dict\n :param attrs : Dict of operator attributes\n :param remove_list : list of attributes to be removed\n\n :return new_attr : Dict of operator attributes without the listed attributes.\n "
] |
Please provide a description of the function:def _add_extra_attributes(attrs, extra_attr_map):
for attr in extra_attr_map:
if attr not in attrs:
attrs[attr] = extra_attr_map[attr]
return attrs | [
"\n :param attrs: Current Attribute list\n :param extraAttrMap: Additional attributes to be added\n :return: new_attr\n "
] |
Please provide a description of the function:def _pad_sequence_fix(attr, kernel_dim=None):
new_attr = ()
if len(attr) % 2 == 0:
for index in range(int(len(attr) / 2)):
new_attr = new_attr + attr[index::int(len(attr) / 2)]
# Making sure pad values are in the attr for all axes.
... | [
"Changing onnx's pads sequence to match with mxnet's pad_width\n mxnet: (x1_begin, x1_end, ... , xn_begin, xn_end)\n onnx: (x1_begin, x2_begin, ... , xn_end, xn_end)"
] |
Please provide a description of the function:def _fix_pooling(pool_type, inputs, new_attr):
stride = new_attr.get('stride')
kernel = new_attr.get('kernel')
padding = new_attr.get('pad')
p_value = new_attr.get('p_value')
# Adding default stride.
if stride is None:
stride = (1,) * le... | [
"onnx pooling operator supports asymmetrical padding\n Adding pad operator before pooling in mxnet to work with onnx"
] |
Please provide a description of the function:def _fix_bias(op_name, attrs, num_inputs):
if num_inputs == 3:
attrs['no_bias'] = False
elif num_inputs == 2:
attrs['no_bias'] = True
else:
raise ValueError("Unexpected number of inputs for: {}".format(op_name))
return attrs | [
"A workaround for 'use_bias' attribute since onnx don't provide this attribute,\n we have to check the number of inputs to decide it."
] |
Please provide a description of the function:def _fix_broadcast(op_name, inputs, broadcast_axis, proto_obj):
if int(len(proto_obj._params)) > 0:
assert len(list(inputs)) == 2
input0_shape = get_input_shape(inputs[0], proto_obj)
#creating reshape shape
reshape_shape = list(len(i... | [
"A workaround to reshape bias term to (1, num_channel)."
] |
Please provide a description of the function:def _fix_channels(op_name, attrs, inputs, proto_obj):
weight_name = inputs[1].name
if not weight_name in proto_obj._params:
raise ValueError("Unable to get channels/units attr from onnx graph.")
else:
wshape = proto_obj._params[weight_name].s... | [
"A workaround for getting 'channels' or 'units' since onnx don't provide\n these attributes. We check the shape of weights provided to get the number.\n "
] |
Please provide a description of the function:def _fix_gemm(op_name, inputs, old_attr, proto_obj):
op_sym = getattr(symbol, op_name, None)
alpha = float(old_attr.get('alpha', 1.0))
beta = float(old_attr.get('beta', 1.0))
trans_a = int(old_attr.get('transA', 0))
trans_b = int(old_attr.get('transB... | [
"Using FullyConnected operator in place of linalg_gemm to perform same operation"
] |
Please provide a description of the function:def get_input_shape(sym, proto_obj):
arg_params = proto_obj.arg_dict
aux_params = proto_obj.aux_dict
model_input_shape = [data[1] for data in proto_obj.model_metadata.get('input_tensor_data')]
data_names = [data[0] for data in proto_obj.model_metadata... | [
"Helper function to obtain the shape of an array"
] |
Please provide a description of the function:def imresize(src, w, h, *args, **kwargs):
r
return _internal._cvimresize(src, w, h, *args, **kwargs) | [
"Resize image with OpenCV.\n\n .. note:: `imresize` uses OpenCV (not the CV2 Python library). MXNet must have been built\n with USE_OPENCV=1 for `imresize` to work.\n\n Parameters\n ----------\n src : NDArray\n source image\n w : int, required\n Width of resized image.\n h : in... |
Please provide a description of the function:def imdecode(buf, *args, **kwargs):
if not isinstance(buf, nd.NDArray):
if sys.version_info[0] == 3 and not isinstance(buf, (bytes, bytearray, np.ndarray)):
raise ValueError('buf must be of type bytes, bytearray or numpy.ndarray,'
... | [
"Decode an image to an NDArray.\n\n .. note:: `imdecode` uses OpenCV (not the CV2 Python library).\n MXNet must have been built with USE_OPENCV=1 for `imdecode` to work.\n\n Parameters\n ----------\n buf : str/bytes/bytearray or numpy.ndarray\n Binary image data as string or numpy ndarray.\... |
Please provide a description of the function:def scale_down(src_size, size):
w, h = size
sw, sh = src_size
if sh < h:
w, h = float(w * sh) / h, sh
if sw < w:
w, h = sw, float(h * sw) / w
return int(w), int(h) | [
"Scales down crop size if it's larger than image size.\n\n If width/height of the crop is larger than the width/height of the image,\n sets the width/height to the width/height of the image.\n\n Parameters\n ----------\n src_size : tuple of int\n Size of the image in (width, height) format.\n ... |
Please provide a description of the function:def copyMakeBorder(src, top, bot, left, right, *args, **kwargs):
return _internal._cvcopyMakeBorder(src, top, bot, left, right, *args, **kwargs) | [
"Pad image border with OpenCV.\n\n Parameters\n ----------\n src : NDArray\n source image\n top : int, required\n Top margin.\n bot : int, required\n Bottom margin.\n left : int, required\n Left margin.\n right : int, required\n Right margin.\n type : int, ... |
Please provide a description of the function:def _get_interp_method(interp, sizes=()):
if interp == 9:
if sizes:
assert len(sizes) == 4
oh, ow, nh, nw = sizes
if nh > oh and nw > ow:
return 2
elif nh < oh and nw < ow:
retur... | [
"Get the interpolation method for resize functions.\n The major purpose of this function is to wrap a random interp method selection\n and a auto-estimation method.\n\n Parameters\n ----------\n interp : int\n interpolation method for all resizing operations\n\n Possible values:\n ... |
Please provide a description of the function:def resize_short(src, size, interp=2):
h, w, _ = src.shape
if h > w:
new_h, new_w = size * h // w, size
else:
new_h, new_w = size, size * w // h
return imresize(src, new_w, new_h, interp=_get_interp_method(interp, (h, w, new_h, new_w))) | [
"Resizes shorter edge to size.\n\n .. note:: `resize_short` uses OpenCV (not the CV2 Python library).\n MXNet must have been built with OpenCV for `resize_short` to work.\n\n Resizes the original image by setting the shorter edge to size\n and setting the longer edge accordingly.\n Resizing functi... |
Please provide a description of the function:def fixed_crop(src, x0, y0, w, h, size=None, interp=2):
out = nd.slice(src, begin=(y0, x0, 0), end=(y0 + h, x0 + w, int(src.shape[2])))
if size is not None and (w, h) != size:
sizes = (h, w, size[1], size[0])
out = imresize(out, *size, interp=_ge... | [
"Crop src at fixed location, and (optionally) resize it to size.\n\n Parameters\n ----------\n src : NDArray\n Input image\n x0 : int\n Left boundary of the cropping area\n y0 : int\n Top boundary of the cropping area\n w : int\n Width of the cropping area\n h : int\... |
Please provide a description of the function:def center_crop(src, size, interp=2):
h, w, _ = src.shape
new_w, new_h = scale_down((w, h), size)
x0 = int((w - new_w) / 2)
y0 = int((h - new_h) / 2)
out = fixed_crop(src, x0, y0, new_w, new_h, size, interp)
return out, (x0, y0, new_w, new_h) | [
"Crops the image `src` to the given `size` by trimming on all four\n sides and preserving the center of the image. Upsamples if `src` is smaller\n than `size`.\n\n .. note:: This requires MXNet to be compiled with USE_OPENCV.\n\n Parameters\n ----------\n src : NDArray\n Binary source image... |
Please provide a description of the function:def color_normalize(src, mean, std=None):
if mean is not None:
src -= mean
if std is not None:
src /= std
return src | [
"Normalize src with mean and std.\n\n Parameters\n ----------\n src : NDArray\n Input image\n mean : NDArray\n RGB mean to be subtracted\n std : NDArray\n RGB standard deviation to be divided\n\n Returns\n -------\n NDArray\n An `NDArray` containing the normalized... |
Please provide a description of the function:def random_size_crop(src, size, area, ratio, interp=2, **kwargs):
h, w, _ = src.shape
src_area = h * w
if 'min_area' in kwargs:
warnings.warn('`min_area` is deprecated. Please use `area` instead.',
DeprecationWarning)
a... | [
"Randomly crop src with size. Randomize area and aspect ratio.\n\n Parameters\n ----------\n src : NDArray\n Input image\n size : tuple of (int, int)\n Size of the crop formatted as (width, height).\n area : float in (0, 1] or tuple of (float, float)\n If tuple, minimum area and ... |
Please provide a description of the function:def CreateAugmenter(data_shape, resize=0, rand_crop=False, rand_resize=False, rand_mirror=False,
mean=None, std=None, brightness=0, contrast=0, saturation=0, hue=0,
pca_noise=0, rand_gray=0, inter_method=2):
auglist = []
... | [
"Creates an augmenter list.\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 : bool\n Whether to enable random cropping other than center crop\n rand_resize : bool\... |
Please provide a description of the function:def dumps(self):
return json.dumps([self.__class__.__name__.lower(), self._kwargs]) | [
"Saves the Augmenter to string\n\n Returns\n -------\n str\n JSON formatted string that describes the Augmenter.\n "
] |
Please provide a description of the function:def dumps(self):
return [self.__class__.__name__.lower(), [x.dumps() for x in self.ts]] | [
"Override the default to avoid duplicate dump."
] |
Please provide a description of the function:def reset(self):
if self.seq is not None and self.shuffle:
random.shuffle(self.seq)
if self.last_batch_handle != 'roll_over' or \
self._cache_data is None:
if self.imgrec is not None:
self.imgrec.re... | [
"Resets the iterator to the beginning of the data."
] |
Please provide a description of the function:def hard_reset(self):
if self.seq is not None and self.shuffle:
random.shuffle(self.seq)
if self.imgrec is not None:
self.imgrec.reset()
self.cur = 0
self._allow_read = True
self._cache_data = None
... | [
"Resets the iterator and ignore roll over data"
] |
Please provide a description of the function:def next_sample(self):
if self._allow_read is False:
raise StopIteration
if self.seq is not None:
if self.cur < self.num_image:
idx = self.seq[self.cur]
else:
if self.last_batch_hand... | [
"Helper function for reading in next sample."
] |
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:
... | [
"Helper function for batchifying data"
] |
Please provide a description of the function:def imdecode(self, s):
def locate():
if self.seq is not None:
idx = self.seq[(self.cur % self.num_image) - 1]
else:
idx = (self.cur % self.num_image) - 1
if self.imglist is not ... | [
"Decodes a string or byte string to an NDArray.\n See mx.img.imdecode for more details.",
"Locate the image file/index if decode fails."
] |
Please provide a description of the function:def read_image(self, fname):
with open(os.path.join(self.path_root, fname), 'rb') as fin:
img = fin.read()
return img | [
"Reads an input image `fname` and returns the decoded raw bytes.\n Examples\n --------\n >>> dataIter.read_image('Face.jpg') # returns decoded raw bytes.\n "
] |
Please provide a description of the function:def facc(label, pred):
pred = pred.ravel()
label = label.ravel()
return ((pred > 0.5) == label).mean() | [
" evaluate accuracy "
] |
Please provide a description of the function:def word_to_vector(word):
vector = []
for char in list(word):
vector.append(char2int(char))
return vector | [
"\n Convert character vectors to integer vectors.\n "
] |
Please provide a description of the function:def vector_to_word(vector):
word = ""
for vec in vector:
word = word + int2char(vec)
return word | [
"\n Convert integer vectors to character vectors.\n "
] |
Please provide a description of the function:def char_conv(out):
out_conv = list()
for i in range(out.shape[0]):
tmp_str = ''
for j in range(out.shape[1]):
if int(out[i][j]) >= 0:
tmp_char = int2char(int(out[i][j]))
if int(out[i][j]) == 27:
... | [
"\n Convert integer vectors to character vectors for batch.\n "
] |
Please provide a description of the function:def add_pooling_with_padding_types(builder, name, height, width, stride_height, stride_width,
layer_type, padding_type, input_name, output_name,
padding_top = 0, padding_bottom = 0, padding_left = 0, padding_right = 0,
same_padding_asymmetry_mode =... | [
"\r\n Add a pooling layer to the model.\r\n\r\n This is our own implementation of add_pooling since current CoreML's version (0.5.0) of builder\r\n doesn't provide support for padding types apart from valid. This support will be added in the\r\n next release of coremltools. When that happens, this can b... |
Please provide a description of the function:def get_frames(root_path):
ret = []
for root, _, files in os.walk(root_path):
root=root.replace('\\','/')
files=[s for s in files if ".dcm" in s]
if len(files) == 0 or not files[0].endswith(".dcm") or root.find("sax") == -1:
continue... | [
"Get path to all the frame in view SAX and contain complete frames"
] |
Please provide a description of the function:def write_data_csv(fname, frames, preproc):
fdata = open(fname, "w")
dr = Parallel()(delayed(get_data)(lst,preproc) for lst in frames)
data,result = zip(*dr)
for entry in data:
fdata.write(','.join(entry)+'\r\n')
print("All finished, %d slices in tot... | [
"Write data to csv file"
] |
Please provide a description of the function:def crop_resize(img, size):
if img.shape[0] < img.shape[1]:
img = img.T
# we crop image from center
short_egde = min(img.shape[:2])
yy = int((img.shape[0] - short_egde) / 2)
xx = int((img.shape[1] - short_egde) / 2)
crop_img = img[yy : yy + short... | [
"crop center and resize"
] |
Please provide a description of the function:def get_generator():
g_net = gluon.nn.Sequential()
with g_net.name_scope():
g_net.add(gluon.nn.Conv2DTranspose(
channels=512, kernel_size=4, strides=1, padding=0, use_bias=False))
g_net.add(gluon.nn.BatchNorm())
g_net.add(glu... | [
" construct and return generator "
] |
Please provide a description of the function:def get_descriptor(ctx):
d_net = gluon.nn.Sequential()
with d_net.name_scope():
d_net.add(SNConv2D(num_filter=64, kernel_size=4, strides=2, padding=1, in_channels=3, ctx=ctx))
d_net.add(gluon.nn.LeakyReLU(0.2))
d_net.add(SNConv2D(num_fi... | [
" construct and return descriptor "
] |
Please provide a description of the function:def _spectral_norm(self):
w = self.params.get('weight').data(self.ctx)
w_mat = nd.reshape(w, [w.shape[0], -1])
_u = self.u.data(self.ctx)
_v = None
for _ in range(POWER_ITERATION):
_v = nd.L2Normalization(nd.dot(... | [
" spectral normalization "
] |
Please provide a description of the function:def conv_output_length(input_length, filter_size, border_mode, stride,
dilation=1):
if input_length is None:
return None
assert border_mode in {'same', 'valid'}
dilated_filter_size = filter_size + (filter_size - 1) * (dilation ... | [
" Compute the length of the output sequence after 1D convolution along\n time. Note that this function is in line with the function used in\n Convolution1D class from Keras.\n Params:\n input_length (int): Length of the input sequence.\n filter_size (int): Width of the convolution ker... |
Please provide a description of the function:def spectrogram(samples, fft_length=256, sample_rate=2, hop_length=128):
assert not np.iscomplexobj(samples), "Must not pass in complex numbers"
window = np.hanning(fft_length)[:, None]
window_norm = np.sum(window ** 2)
# The scaling below follows the ... | [
"\n Compute the spectrogram for a real signal.\n The parameters follow the naming convention of\n matplotlib.mlab.specgram\n Args:\n samples (1D array): input audio signal\n fft_length (int): number of elements in fft window\n sample_rate (scalar): sample rate\n hop_length (i... |
Please provide a description of the function:def spectrogram_from_file(filename, step=10, window=20, max_freq=None,
eps=1e-14, overwrite=False, save_feature_as_csvfile=False):
csvfilename = filename.replace(".wav", ".csv")
if (os.path.isfile(csvfilename) is False) or overwrite:
... | [
" Calculate the log of linear spectrogram from FFT energy\n Params:\n filename (str): Path to the audio file\n step (int): Step size in milliseconds between windows\n window (int): FFT window size in milliseconds\n max_freq (int): Only FFT bins corresponding to frequencies between\n ... |
Please provide a description of the function:def sample(self, label):
samples = []
count = 0
for trial in range(self.max_trials):
if count >= self.max_sample:
return samples
scale = np.random.uniform(self.min_scale, self.max_scale)
min... | [
"\n generate random cropping boxes according to parameters\n if satifactory crops generated, apply to ground-truth as well\n\n Parameters:\n ----------\n label : numpy.array (n x 5 matrix)\n ground-truths\n\n Returns:\n ----------\n list of (crop_bo... |
Please provide a description of the function:def _check_satisfy(self, rand_box, gt_boxes):
l, t, r, b = rand_box
num_gt = gt_boxes.shape[0]
ls = np.ones(num_gt) * l
ts = np.ones(num_gt) * t
rs = np.ones(num_gt) * r
bs = np.ones(num_gt) * b
mask = np.where... | [
"\n check if overlap with any gt box is larger than threshold\n "
] |
Please provide a description of the function:def sample(self, label):
samples = []
count = 0
for trial in range(self.max_trials):
if count >= self.max_sample:
return samples
scale = np.random.uniform(self.min_scale, self.max_scale)
min... | [
"\n generate random padding boxes according to parameters\n if satifactory padding generated, apply to ground-truth as well\n\n Parameters:\n ----------\n label : numpy.array (n x 5 matrix)\n ground-truths\n\n Returns:\n ----------\n list of (crop_b... |
Please provide a description of the function:def measure_cost(repeat, scipy_trans_lhs, scipy_dns_lhs, func_name, *args, **kwargs):
mx.nd.waitall()
args_list = []
for arg in args:
args_list.append(arg)
start = time.time()
if scipy_trans_lhs:
args_list[0] = np.transpose(args_list[... | [
"Measure time cost of running a function\n "
] |
Please provide a description of the function:def info(self):
for key, value in self.dataset['info'].items():
print('{}: {}'.format(key, value)) | [
"\n Print information about the annotation file.\n :return:\n "
] |
Please provide a description of the function:def getCatIds(self, catNms=[], supNms=[], catIds=[]):
catNms = catNms if type(catNms) == list else [catNms]
supNms = supNms if type(supNms) == list else [supNms]
catIds = catIds if type(catIds) == list else [catIds]
if len(catNms) ==... | [
"\n filtering parameters. default skips that filter.\n :param catNms (str array) : get cats for given cat names\n :param supNms (str array) : get cats for given supercategory names\n :param catIds (int array) : get cats for given cat ids\n :return: ids (int array) : integer a... |
Please provide a description of the function:def loadAnns(self, ids=[]):
if type(ids) == list:
return [self.anns[id] for id in ids]
elif type(ids) == int:
return [self.anns[ids]] | [
"\n Load anns with the specified ids.\n :param ids (int array) : integer ids specifying anns\n :return: anns (object array) : loaded ann objects\n "
] |
Please provide a description of the function:def loadCats(self, ids=[]):
if type(ids) == list:
return [self.cats[id] for id in ids]
elif type(ids) == int:
return [self.cats[ids]] | [
"\n Load cats with the specified ids.\n :param ids (int array) : integer ids specifying cats\n :return: cats (object array) : loaded cat objects\n "
] |
Please provide a description of the function:def loadImgs(self, ids=[]):
if type(ids) == list:
return [self.imgs[id] for id in ids]
elif type(ids) == int:
return [self.imgs[ids]] | [
"\n Load anns with the specified ids.\n :param ids (int array) : integer ids specifying img\n :return: imgs (object array) : loaded img objects\n "
] |
Please provide a description of the function:def showAnns(self, anns):
if len(anns) == 0:
return 0
if 'segmentation' in anns[0] or 'keypoints' in anns[0]:
datasetType = 'instances'
elif 'caption' in anns[0]:
datasetType = 'captions'
else:
... | [
"\n Display the specified annotations.\n :param anns (array of object): annotations to display\n :return: None\n "
] |
Please provide a description of the function:def download(self, tarDir = None, imgIds = [] ):
'''
Download COCO images from mscoco.org server.
:param tarDir (str): COCO results directory name
imgIds (list): images to be downloaded
:return:
'''
if tarDir is ... | [] |
Please provide a description of the function:def loadNumpyAnnotations(self, data):
print('Converting ndarray to lists...')
assert(type(data) == np.ndarray)
print(data.shape)
assert(data.shape[1] == 7)
N = data.shape[0]
ann = []
for i in range(N):
... | [
"\n Convert result data from a numpy array [Nx7] where each row contains {imageID,x1,y1,w,h,score,class}\n :param data (numpy.ndarray)\n :return: annotations (python nested list)\n "
] |
Please provide a description of the function:def annToRLE(self, ann):
t = self.imgs[ann['image_id']]
h, w = t['height'], t['width']
segm = ann['segmentation']
if type(segm) == list:
# polygon -- a single object might consist of multiple parts
# we merge a... | [
"\n Convert annotation which can be polygons, uncompressed RLE to RLE.\n :return: binary mask (numpy 2D array)\n "
] |
Please provide a description of the function:def save_model():
if not os.path.exists("checkpoint"):
os.mkdir("checkpoint")
return mx.callback.do_checkpoint("checkpoint/checkpoint", args.save_period) | [
"Save cnn model\n Returns\n ----------\n callback: A callback function that can be passed as epoch_end_callback to fit\n "
] |
Please provide a description of the function:def highway(data):
_data = data
high_weight = mx.sym.Variable('high_weight')
high_bias = mx.sym.Variable('high_bias')
high_fc = mx.sym.FullyConnected(data=data, weight=high_weight, bias=high_bias, num_hidden=300, name='high_fc')
high_relu = mx.sym.Ac... | [
"Construct highway net\n Parameters\n ----------\n data:\n Returns\n ----------\n Highway Networks\n "
] |
Please provide a description of the function:def train(symbol_data, train_iterator, valid_iterator, data_column_names, target_names):
devs = mx.cpu() # default setting
if args.gpus is not None:
for i in args.gpus.split(','):
mx.gpu(int(i))
devs = mx.gpu()
module = mx.mod.Mo... | [
"Train cnn model\n Parameters\n ----------\n symbol_data: symbol\n train_iterator: DataIter\n Train DataIter\n valid_iterator: DataIter\n Valid DataIter\n data_column_names: list of str\n Defaults to ('data') for a typical model used in i... |
Please provide a description of the function:def default_batchify_fn(data):
if isinstance(data[0], nd.NDArray):
return nd.stack(*data)
elif isinstance(data[0], tuple):
data = zip(*data)
return [default_batchify_fn(i) for i in data]
else:
data = np.asarray(data)
r... | [
"Collate data into batch."
] |
Please provide a description of the function:def default_mp_batchify_fn(data):
if isinstance(data[0], nd.NDArray):
out = nd.empty((len(data),) + data[0].shape, dtype=data[0].dtype,
ctx=context.Context('cpu_shared', 0))
return nd.stack(*data, out=out)
elif isinstance(d... | [
"Collate data into batch. Use shared memory for stacking."
] |
Please provide a description of the function:def _as_in_context(data, ctx):
if isinstance(data, nd.NDArray):
return data.as_in_context(ctx)
elif isinstance(data, (list, tuple)):
return [_as_in_context(d, ctx) for d in data]
return data | [
"Move data into new context."
] |
Please provide a description of the function:def worker_loop_v1(dataset, key_queue, data_queue, batchify_fn):
while True:
idx, samples = key_queue.get()
if idx is None:
break
batch = batchify_fn([dataset[i] for i in samples])
data_queue.put((idx, batch)) | [
"Worker loop for multiprocessing DataLoader."
] |
Please provide a description of the function:def fetcher_loop_v1(data_queue, data_buffer, pin_memory=False,
pin_device_id=0, data_buffer_lock=None):
while True:
idx, batch = data_queue.get()
if idx is None:
break
if pin_memory:
batch = _as_in_... | [
"Fetcher loop for fetching data from queue and put in reorder dict."
] |
Please provide a description of the function:def _worker_fn(samples, batchify_fn, dataset=None):
# pylint: disable=unused-argument
# it is required that each worker process has to fork a new MXIndexedRecordIO handle
# preserving dataset as global variable can save tons of overhead and is safe in new pr... | [
"Function for processing data in worker process."
] |
Please provide a description of the function:def send(self, obj):
buf = io.BytesIO()
ForkingPickler(buf, pickle.HIGHEST_PROTOCOL).dump(obj)
self.send_bytes(buf.getvalue()) | [
"Send object"
] |
Please provide a description of the function:def _push_next(self):
r = next(self._iter, None)
if r is None:
return
self._key_queue.put((self._sent_idx, r))
self._sent_idx += 1 | [
"Assign next batch workload to workers."
] |
Please provide a description of the function:def shutdown(self):
if not self._shutdown:
# send shutdown signal to the fetcher and join data queue first
# Remark: loop_fetcher need to be joined prior to the workers.
# otherwise, the the fetcher may fail at... | [
"Shutdown internal workers by pushing terminate signals."
] |
Please provide a description of the function:def _push_next(self):
r = next(self._iter, None)
if r is None:
return
async_ret = self._worker_pool.apply_async(
self._worker_fn, (r, self._batchify_fn, self._dataset))
self._data_buffer[self._sent_idx] = async... | [
"Assign next batch workload to workers."
] |
Please provide a description of the function:def _ctype_key_value(keys, vals):
if isinstance(keys, (tuple, list)):
assert(len(keys) == len(vals))
c_keys = []
c_vals = []
use_str_keys = None
for key, val in zip(keys, vals):
c_key_i, c_val_i, str_keys_i = _ctyp... | [
"\n Returns ctype arrays for the key-value args, and the whether string keys are used.\n For internal use only.\n "
] |
Please provide a description of the function:def _ctype_dict(param_dict):
assert(isinstance(param_dict, dict)), \
"unexpected type for param_dict: " + str(type(param_dict))
c_keys = c_array(ctypes.c_char_p, [c_str(k) for k in param_dict.keys()])
c_vals = c_array(ctypes.c_char_p, [c_str(str(v)) ... | [
"\n Returns ctype arrays for keys and values(converted to strings) in a dictionary\n "
] |
Please provide a description of the function:def _updater_wrapper(updater):
def updater_handle(key, lhs_handle, rhs_handle, _):
lhs = _ndarray_cls(NDArrayHandle(lhs_handle))
rhs = _ndarray_cls(NDArrayHandle(rhs_handle))
updater(key, lhs, rhs)
return updater_handle | [
"A wrapper for the user-defined handle.",
" ctypes function "
] |
Please provide a description of the function:def create(name='local'):
if not isinstance(name, string_types):
raise TypeError('name must be a string')
handle = KVStoreHandle()
check_call(_LIB.MXKVStoreCreate(c_str(name),
ctypes.byref(handle)))
kv = KVStor... | [
"Creates a new KVStore.\n\n For single machine training, there are two commonly used types:\n\n ``local``: Copies all gradients to CPU memory and updates weights there.\n\n ``device``: Aggregates gradients and updates weights on GPUs. With this setting,\n the KVStore also attempts to use GPU peer-to-pee... |
Please provide a description of the function:def init(self, key, value):
ckeys, cvals, use_str_keys = _ctype_key_value(key, value)
if use_str_keys:
check_call(_LIB.MXKVStoreInitEx(self.handle, mx_uint(len(ckeys)), ckeys, cvals))
else:
check_call(_LIB.MXKVStoreIni... | [
" Initializes a single or a sequence of key-value pairs into the store.\n\n For each key, one must `init` it before calling `push` or `pull`.\n When multiple workers invoke `init` for the same key, only\n the value supplied by worker with rank `0` is used. This function returns\n after d... |
Please provide a description of the function:def push(self, key, value, priority=0):
ckeys, cvals, use_str_keys = _ctype_key_value(key, value)
if use_str_keys:
check_call(_LIB.MXKVStorePushEx(
self.handle, mx_uint(len(ckeys)), ckeys, cvals, ctypes.c_int(priority)))
... | [
" Pushes a single or a sequence of key-value pairs into the store.\n\n This function returns immediately after adding an operator to the engine.\n The actual operation is executed asynchronously. If there are consecutive\n pushes to the same key, there is no guarantee on the serialization of pu... |
Please provide a description of the function:def pull(self, key, out=None, priority=0, ignore_sparse=True):
assert(out is not None)
ckeys, cvals, use_str_keys = _ctype_key_value(key, out)
if use_str_keys:
check_call(_LIB.MXKVStorePullWithSparseEx(self.handle, mx_uint(len(cke... | [
" Pulls a single value or a sequence of values from the store.\n\n This function returns immediately after adding an operator to the engine.\n Subsequent attempts to read from the `out` variable will be blocked until the\n pull operation completes.\n\n `pull` is executed asynchronously a... |
Please provide a description of the function:def row_sparse_pull(self, key, out=None, priority=0, row_ids=None):
assert(out is not None)
assert(row_ids is not None)
if isinstance(row_ids, NDArray):
row_ids = [row_ids]
assert(isinstance(row_ids, list)), \
... | [
" Pulls a single RowSparseNDArray value or a sequence of RowSparseNDArray values \\\n from the store with specified row_ids. When there is only one row_id, KVStoreRowSparsePull \\\n is invoked just once and the result is broadcast to all the rest of outputs.\n\n `row_sparse_pull` is executed as... |
Please provide a description of the function:def set_gradient_compression(self, compression_params):
if ('device' in self.type) or ('dist' in self.type): # pylint: disable=unsupported-membership-test
ckeys, cvals = _ctype_dict(compression_params)
check_call(_LIB.MXKVStoreSetGrad... | [
" Specifies type of low-bit quantization for gradient compression \\\n and additional arguments depending on the type of compression being used.\n\n 2bit Gradient Compression takes a positive float `threshold`.\n The technique works by thresholding values such that positive values in the\n ... |
Please provide a description of the function:def set_optimizer(self, optimizer):
is_worker = ctypes.c_int()
check_call(_LIB.MXKVStoreIsWorkerNode(ctypes.byref(is_worker)))
# pylint: disable=invalid-name
if 'dist' in self.type and is_worker.value: # pylint: disable=unsupported-m... | [
" Registers an optimizer with the kvstore.\n\n When using a single machine, this function updates the local optimizer.\n If using multiple machines and this operation is invoked from a worker node,\n it will serialized the optimizer with pickle and send it to all servers.\n The function ... |
Please provide a description of the function:def type(self):
kv_type = ctypes.c_char_p()
check_call(_LIB.MXKVStoreGetType(self.handle, ctypes.byref(kv_type)))
return py_str(kv_type.value) | [
" Returns the type of this kvstore.\n\n Returns\n -------\n type : str\n the string type\n "
] |
Please provide a description of the function:def rank(self):
rank = ctypes.c_int()
check_call(_LIB.MXKVStoreGetRank(self.handle, ctypes.byref(rank)))
return rank.value | [
" Returns the rank of this worker node.\n\n Returns\n -------\n rank : int\n The rank of this node, which is in range [0, num_workers())\n "
] |
Please provide a description of the function:def num_workers(self):
size = ctypes.c_int()
check_call(_LIB.MXKVStoreGetGroupSize(self.handle, ctypes.byref(size)))
return size.value | [
"Returns the number of worker nodes.\n\n Returns\n -------\n size :int\n The number of worker nodes.\n "
] |
Please provide a description of the function:def save_optimizer_states(self, fname, dump_optimizer=False):
assert self._updater is not None, "Cannot save states for distributed training"
with open(fname, 'wb') as fout:
fout.write(self._updater.get_states(dump_optimizer)) | [
"Saves the optimizer (updater) state to a file. This is often used when checkpointing\n the model during training.\n\n Parameters\n ----------\n fname : str\n Path to the output states file.\n dump_optimizer : bool, default False\n Whether to also save the op... |
Please provide a description of the function:def load_optimizer_states(self, fname):
assert self._updater is not None, "Cannot load states for distributed training"
self._updater.set_states(open(fname, 'rb').read()) | [
"Loads the optimizer (updater) state from the file.\n\n Parameters\n ----------\n fname : str\n Path to input states file.\n "
] |
Please provide a description of the function:def _set_updater(self, updater):
self._updater = updater
# set updater with int keys
_updater_proto = ctypes.CFUNCTYPE(
None, ctypes.c_int, NDArrayHandle, NDArrayHandle, ctypes.c_void_p)
self._updater_func = _updater_proto... | [
"Sets a push updater into the store.\n\n This function only changes the local store. When running on multiple machines one must\n use `set_optimizer`.\n\n Parameters\n ----------\n updater : function\n The updater function.\n\n Examples\n --------\n ... |
Please provide a description of the function:def _send_command_to_servers(self, head, body):
check_call(_LIB.MXKVStoreSendCommmandToServers(
self.handle, mx_uint(head), c_str(body))) | [
"Sends a command to all server nodes.\n\n Sending command to a server node will cause that server node to invoke\n ``KVStoreServer.controller`` to execute the command.\n\n This function returns after the command has been executed on all server\n nodes.\n\n Parameters\n ----... |
Please provide a description of the function:def add(self, module, **kwargs):
self._modules.append(module)
# a sanity check to avoid typo
for key in kwargs:
assert key in self._meta_keys, ('Unknown meta "%s", a typo?' % key)
self._metas.append(kwargs)
# af... | [
"Add a module to the chain.\n\n Parameters\n ----------\n module : BaseModule\n The new module to add.\n kwargs : ``**keywords``\n All the keyword arguments are saved as meta information\n for the added module. The currently known meta includes\n\n ... |
Please provide a description of the function:def get_params(self):
assert self.binded and self.params_initialized
arg_params = dict()
aux_params = dict()
for module in self._modules:
arg, aux = module.get_params()
arg_params.update(arg)
aux_... | [
"Gets current parameters.\n\n Returns\n -------\n (arg_params, aux_params)\n A pair of dictionaries each mapping parameter names to NDArray values. This\n is a merged dictionary of all the parameters in the modules.\n "
] |
Please provide a description of the function:def init_params(self, initializer=Uniform(0.01), arg_params=None, aux_params=None,
allow_missing=False, force_init=False, allow_extra=False):
if self.params_initialized and not force_init:
return
assert self.binded, 'c... | [
"Initializes parameters.\n\n Parameters\n ----------\n initializer : Initializer\n arg_params : dict\n Default ``None``. Existing parameters. This has higher priority\n than `initializer`.\n aux_params : dict\n Default ``None``. Existing auxiliary ... |
Please provide a description of the function:def bind(self, data_shapes, label_shapes=None, for_training=True,
inputs_need_grad=False, force_rebind=False, shared_module=None,
grad_req='write'):
if self.binded and not force_rebind:
self.logger.warning('Already bound... | [
"Binds the symbols to construct executors. This is necessary before one\n can perform computation with the module.\n\n Parameters\n ----------\n data_shapes : list of (str, tuple)\n Typically is `data_iter.provide_data`.\n label_shapes : list of (str, tuple)\n ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.