Code stringlengths 103 85.9k | Summary listlengths 0 94 |
|---|---|
Please provide a description of the function:def clip(attrs, inputs, proto_obj):
new_attrs = translation_utils._fix_attribute_names(attrs, {'min' : 'a_min',
'max' : 'a_max'})
if 'a_max' not in new_attrs:
new_attrs = translation_utils._a... | [
"Clips (limits) the values in an array."
] |
Please provide a description of the function:def power(attrs, inputs, proto_obj):
new_attrs = translation_utils._fix_attribute_names(attrs, {'exponent':'exp'})
if 'broadcast' in attrs:
new_attrs = translation_utils._remove_attributes(new_attrs, ['broadcast'])
if attrs['broadcast'] == 1:
... | [
"Returns element-wise result of base element raised to powers from exp element."
] |
Please provide a description of the function:def reduce_max(attrs, inputs, proto_obj):
new_attrs = translation_utils._fix_attribute_names(attrs, {'axes':'axis'})
return 'max', new_attrs, inputs | [
"Reduce the array along a given axis by maximum value"
] |
Please provide a description of the function:def reduce_mean(attrs, inputs, proto_obj):
new_attrs = translation_utils._fix_attribute_names(attrs, {'axes':'axis'})
return 'mean', new_attrs, inputs | [
"Reduce the array along a given axis by mean value"
] |
Please provide a description of the function:def reduce_min(attrs, inputs, proto_obj):
new_attrs = translation_utils._fix_attribute_names(attrs, {'axes':'axis'})
return 'min', new_attrs, inputs | [
"Reduce the array along a given axis by minimum value"
] |
Please provide a description of the function:def reduce_sum(attrs, inputs, proto_obj):
new_attrs = translation_utils._fix_attribute_names(attrs, {'axes':'axis'})
return 'sum', new_attrs, inputs | [
"Reduce the array along a given axis by sum value"
] |
Please provide a description of the function:def reduce_prod(attrs, inputs, proto_obj):
new_attrs = translation_utils._fix_attribute_names(attrs, {'axes':'axis'})
return 'prod', new_attrs, inputs | [
"Reduce the array along a given axis by product value"
] |
Please provide a description of the function:def reduce_log_sum(attrs, inputs, proto_obj):
keep_dims = True if 'keepdims' not in attrs else attrs.get('keepdims')
sum_op = symbol.sum(inputs[0], axis=attrs.get('axes'),
keepdims=keep_dims)
log_sym = symbol.log(sum_op)
return lo... | [
"Reduce the array along a given axis by log sum value"
] |
Please provide a description of the function:def reduce_log_sum_exp(attrs, inputs, proto_obj):
keep_dims = True if 'keepdims' not in attrs else attrs.get('keepdims')
exp_op = symbol.exp(inputs[0])
sum_op = symbol.sum(exp_op, axis=attrs.get('axes'),
keepdims=keep_dims)
log_sy... | [
"Reduce the array along a given axis by log sum exp value"
] |
Please provide a description of the function:def reduce_sum_square(attrs, inputs, proto_obj):
square_op = symbol.square(inputs[0])
sum_op = symbol.sum(square_op, axis=attrs.get('axes'),
keepdims=attrs.get('keepdims'))
return sum_op, attrs, inputs | [
"Reduce the array along a given axis by sum square value"
] |
Please provide a description of the function:def reduce_l1(attrs, inputs, proto_obj):
new_attrs = translation_utils._fix_attribute_names(attrs, {'axes':'axis'})
new_attrs = translation_utils._add_extra_attributes(new_attrs,
{'ord' : 1})
return 'no... | [
"Reduce input tensor by l1 normalization."
] |
Please provide a description of the function:def reduce_l2(attrs, inputs, proto_obj):
new_attrs = translation_utils._fix_attribute_names(attrs, {'axes':'axis'})
return 'norm', new_attrs, inputs | [
"Reduce input tensor by l2 normalization."
] |
Please provide a description of the function:def avg_pooling(attrs, inputs, proto_obj):
new_attrs = translation_utils._fix_attribute_names(attrs,
{'kernel_shape': 'kernel',
'strides': 'stride',
... | [
" Average pooling"
] |
Please provide a description of the function:def lp_pooling(attrs, inputs, proto_obj):
p_value = attrs.get('p', 2)
new_attrs = translation_utils._fix_attribute_names(attrs,
{'kernel_shape': 'kernel',
... | [
"LP Pooling"
] |
Please provide a description of the function:def max_roi_pooling(attrs, inputs, proto_obj):
new_attrs = translation_utils._fix_attribute_names(attrs,
{'pooled_shape': 'pooled_size',
'spatial_scale': '... | [
"Max ROI Pooling."
] |
Please provide a description of the function:def depthtospace(attrs, inputs, proto_obj):
new_attrs = translation_utils._fix_attribute_names(attrs, {'blocksize':'block_size'})
return "depth_to_space", new_attrs, inputs | [
"Rearranges data from depth into blocks of spatial data."
] |
Please provide a description of the function:def spacetodepth(attrs, inputs, proto_obj):
new_attrs = translation_utils._fix_attribute_names(attrs, {'blocksize':'block_size'})
return "space_to_depth", new_attrs, inputs | [
"Rearranges blocks of spatial data into depth."
] |
Please provide a description of the function:def hardmax(attrs, inputs, proto_obj):
input_tensor_data = proto_obj.model_metadata.get('input_tensor_data')[0]
input_shape = input_tensor_data[1]
axis = int(attrs.get('axis', 1))
axis = axis if axis >= 0 else len(input_shape) + axis
if axis == len... | [
"Returns batched one-hot vectors."
] |
Please provide a description of the function:def lpnormalization(attrs, inputs, proto_obj):
new_attrs = translation_utils._fix_attribute_names(attrs, {'p': 'ord'})
axis = int(attrs.get("axis", -1))
new_attrs.update(axis=axis)
return 'norm', new_attrs, inputs | [
"ONNX does not have eps attribute, so cannot map it to L2normalization in MXNet\n without that, it works as norm operator discussion in PR:\n https://github.com/onnx/onnx/pull/1330"
] |
Please provide a description of the function:def download_mp4(from_idx, to_idx, _params):
succ = set()
fail = set()
for idx in range(from_idx, to_idx):
name = 's' + str(idx)
save_folder = '{src_path}/{nm}'.format(src_path=_params['src_path'], nm=name)
if idx == 0 or os.path.isdi... | [
"\n download mp4s\n "
] |
Please provide a description of the function:def download_align(from_idx, to_idx, _params):
succ = set()
fail = set()
for idx in range(from_idx, to_idx):
name = 's' + str(idx)
if idx == 0:
continue
script = "http://spandh.dcs.shef.ac.uk/gridcorpus/{nm}/align/{nm}.tar... | [
"\n download aligns\n "
] |
Please provide a description of the function:def run_ut_py3_qemu():
from vmcontrol import VM
with VM() as vm:
qemu_provision(vm.ssh_port)
logging.info("execute tests")
qemu_ssh(vm.ssh_port, "./runtime_functions.py", "run_ut_python3_qemu_internal")
qemu_rsync_to_host(vm.ssh_p... | [
"Run unit tests in the emulator and copy the results back to the host through the mounted\n volume in /mxnet"
] |
Please provide a description of the function:def run_ut_python3_qemu_internal():
pkg = glob.glob('mxnet_dist/*.whl')[0]
logging.info("=== NOW Running inside QEMU ===")
logging.info("PIP Installing %s", pkg)
check_call(['sudo', 'pip3', 'install', pkg])
logging.info("PIP Installing mxnet/test_req... | [
"this runs inside the vm"
] |
Please provide a description of the function:def _get_subword_units(token, gram):
if token == '</s>': # special token for padding purpose.
return [token]
t = '#' + token + '#'
return [t[i:i + gram] for i in range(0, len(t) - gram + 1)] | [
"Return subword-units presentation, given a word/token.\n "
] |
Please provide a description of the function:def fit(args, network, data_loader, eval_metrics=None, batch_end_callback=None):
# kvstore
kv = mx.kvstore.create(args.kv_store)
# logging
head = '%(asctime)-15s Node[' + str(kv.rank) + '] %(message)s'
if 'log_file' in args and args.log_file is not ... | [
"Train the model using Caffe operator in MXNet"
] |
Please provide a description of the function:def preprocess(self, img):
# Crop, down-sample, erase background and set foreground to 1.
# See https://gist.github.com/karpathy/a4166c7fe253700972fcbc77e4ea32c5
img = img[35:195]
img = img[::2, ::2, 0]
img[img == 144] = 0
... | [
"\n Preprocess a 210x160x3 uint8 frame into a 6400 (80x80) (1 x input_size)\n float vector.\n "
] |
Please provide a description of the function:def _new_empty_handle():
hdl = NDArrayHandle()
check_call(_LIB.MXNDArrayCreateNone(ctypes.byref(hdl)))
return hdl | [
"Returns a new empty handle.\n\n Empty handle can be used to hold a result.\n\n Returns\n -------\n handle\n A new empty `NDArray` handle.\n "
] |
Please provide a description of the function:def _new_alloc_handle(shape, ctx, delay_alloc, dtype=mx_real_t):
hdl = NDArrayHandle()
check_call(_LIB.MXNDArrayCreateEx(
c_array_buf(mx_uint, native_array('I', shape)),
mx_uint(len(shape)),
ctypes.c_int(ctx.device_typeid),
ctypes... | [
"Return a new handle with specified shape and context.\n\n Empty handle is only used to hold results.\n\n Returns\n -------\n handle\n A new empty `NDArray` handle.\n "
] |
Please provide a description of the function:def _get_indexing_dispatch_code(key):
if isinstance(key, (NDArray, np.ndarray)):
return _NDARRAY_ADVANCED_INDEXING
elif isinstance(key, list):
# TODO(junwu): Add support for nested lists besides integer list
for i in key:
if n... | [
"Returns a dispatch code for calling basic or advanced indexing functions."
] |
Please provide a description of the function:def _get_index_range(start, stop, length, step=1):
if step == 0:
raise ValueError('step size cannot be zero')
if length < 0:
raise ValueError('array length cannot be less than zero')
if step is None:
step = 1
if start is None:
... | [
"Given start, stop, step and array length, return\n absolute values of start, stop, and step for generating index range.\n The returned values have been compensated by adding length if they\n are less than zero for all the cases but slice(None, None, -1).\n Note that the returned value of stop is not ne... |
Please provide a description of the function:def _get_oshape_of_gather_nd_op(dshape, ishape):
assert len(dshape) > 0 and len(ishape) > 0
oshape = list(ishape[1:])
if ishape[0] < len(dshape):
oshape.extend(dshape[ishape[0]:])
return tuple(oshape) | [
"Given data and index shapes, get the output `NDArray` shape.\n This basically implements the infer shape logic of op gather_nd."
] |
Please provide a description of the function:def _get_dim_size(start, stop, step):
assert step != 0
if step > 0:
assert start < stop
dim_size = (stop - start - 1) // step + 1
else:
assert stop < start
dim_size = (start - stop - 1) // (-step) + 1
return dim_size | [
"Given start, stop, and stop, calculate the number of elements\n of this slice."
] |
Please provide a description of the function:def _get_broadcast_shape(shape1, shape2):
if shape1 == shape2:
return shape1
length1 = len(shape1)
length2 = len(shape2)
if length1 > length2:
shape = list(shape1)
else:
shape = list(shape2)
i = max(length1, length2) - 1
... | [
"Given two shapes that are not identical, find the shape\n that both input shapes can broadcast to."
] |
Please provide a description of the function:def ones(shape, ctx=None, dtype=None, **kwargs):
# pylint: disable= unused-argument
if ctx is None:
ctx = current_context()
dtype = mx_real_t if dtype is None else dtype
# pylint: disable= no-member, protected-access
return _internal._ones(sh... | [
"Returns a new array filled with all ones, with the given shape and type.\n\n Parameters\n ----------\n shape : int or tuple of int or list of int\n The shape of the empty array.\n ctx : Context, optional\n An optional device context.\n Defaults to the current default context (``mxn... |
Please provide a description of the function:def full(shape, val, ctx=None, dtype=mx_real_t, out=None):
out = empty(shape, ctx, dtype) if out is None else out
out[:] = val
return out | [
"Returns a new array of given shape and type, filled with the given value `val`.\n\n Parameters\n --------\n shape : int or tuple of int\n The shape of the new array.\n val : scalar\n Fill value.\n ctx : Context, optional\n Device context (default is the current default context).... |
Please provide a description of the function:def array(source_array, ctx=None, dtype=None):
if isinstance(source_array, NDArray):
dtype = source_array.dtype if dtype is None else dtype
else:
dtype = mx_real_t if dtype is None else dtype
if not isinstance(source_array, np.ndarray):
... | [
"Creates an array from any object exposing the array interface.\n\n Parameters\n ----------\n source_array : array_like\n An object exposing the array interface, an object whose `__array__`\n method returns an array, or any (nested) sequence.\n ctx : Context, optional\n Device conte... |
Please provide a description of the function:def moveaxis(tensor, source, destination):
try:
source = np.core.numeric.normalize_axis_tuple(source, tensor.ndim)
except IndexError:
raise ValueError('Source should verify 0 <= source < tensor.ndim'
'Got %d' % source)
... | [
"Moves the `source` axis into the `destination` position\n while leaving the other axes in their original order\n\n Parameters\n ----------\n tensor : mx.nd.array\n The array which axes should be reordered\n source : int or sequence of int\n Original position of the axes to move. Can be... |
Please provide a description of the function:def arange(start, stop=None, step=1.0, repeat=1, infer_range=None, ctx=None, dtype=mx_real_t):
if infer_range is not None:
warnings.warn('`infer_range` argument has been deprecated',
DeprecationWarning)
if ctx is None:
ctx =... | [
"Returns evenly spaced values within a given interval.\n\n Values are generated within the half-open interval [`start`, `stop`). In other\n words, the interval includes `start` but excludes `stop`. The function is\n similar to the built-in Python function `range` and to `numpy.arange`,\n but returns an ... |
Please provide a description of the function:def _ufunc_helper(lhs, rhs, fn_array, fn_scalar, lfn_scalar, rfn_scalar=None):
if isinstance(lhs, numeric_types):
if isinstance(rhs, numeric_types):
return fn_scalar(lhs, rhs)
else:
if rfn_scalar is None:
# com... | [
" Helper function for element-wise operation.\n The function will perform numpy-like broadcasting if needed and call different functions.\n\n Parameters\n --------\n lhs : NDArray or numeric value\n Left-hand side operand.\n\n rhs : NDArray or numeric value\n Right-hand operand,\n\n ... |
Please provide a description of the function:def add(lhs, rhs):
# pylint: disable= no-member, protected-access
return _ufunc_helper(
lhs,
rhs,
op.broadcast_add,
operator.add,
_internal._plus_scalar,
None) | [
"Returns element-wise sum of the input arrays with broadcasting.\n\n Equivalent to ``lhs + rhs``, ``mx.nd.broadcast_add(lhs, rhs)`` and\n ``mx.nd.broadcast_plus(lhs, rhs)``.\n\n .. note::\n\n If the corresponding dimensions of two arrays have the same size or one of them has size 1,\n then the ... |
Please provide a description of the function:def subtract(lhs, rhs):
# pylint: disable= no-member, protected-access
return _ufunc_helper(
lhs,
rhs,
op.broadcast_sub,
operator.sub,
_internal._minus_scalar,
_internal._rminus_scalar) | [
"Returns element-wise difference of the input arrays with broadcasting.\n\n Equivalent to ``lhs - rhs``, ``mx.nd.broadcast_sub(lhs, rhs)`` and\n ``mx.nd.broadcast_minus(lhs, rhs)``.\n\n .. note::\n\n If the corresponding dimensions of two arrays have the same size or one of them has size 1,\n t... |
Please provide a description of the function:def multiply(lhs, rhs):
# pylint: disable= no-member, protected-access
return _ufunc_helper(
lhs,
rhs,
op.broadcast_mul,
operator.mul,
_internal._mul_scalar,
None) | [
"Returns element-wise product of the input arrays with broadcasting.\n\n Equivalent to ``lhs * rhs`` and ``mx.nd.broadcast_mul(lhs, rhs)``.\n\n .. note::\n\n If the corresponding dimensions of two arrays have the same size or one of them has size 1,\n then the arrays are broadcastable to a common ... |
Please provide a description of the function:def divide(lhs, rhs):
# pylint: disable= no-member, protected-access
return _ufunc_helper(
lhs,
rhs,
op.broadcast_div,
operator.truediv,
_internal._div_scalar,
_internal._rdiv_scalar) | [
"Returns element-wise division of the input arrays with broadcasting.\n\n Equivalent to ``lhs / rhs`` and ``mx.nd.broadcast_div(lhs, rhs)``.\n\n .. note::\n\n If the corresponding dimensions of two arrays have the same size or one of them has size 1,\n then the arrays are broadcastable to a common... |
Please provide a description of the function:def modulo(lhs, rhs):
# pylint: disable= no-member, protected-access
return _ufunc_helper(
lhs,
rhs,
op.broadcast_mod,
operator.mod,
_internal._mod_scalar,
_internal._rmod_scalar) | [
"Returns element-wise modulo of the input arrays with broadcasting.\n\n Equivalent to ``lhs % rhs`` and ``mx.nd.broadcast_mod(lhs, rhs)``.\n\n .. note::\n\n If the corresponding dimensions of two arrays have the same size or one of them has size 1,\n then the arrays are broadcastable to a common s... |
Please provide a description of the function:def power(base, exp):
# pylint: disable= no-member, protected-access
return _ufunc_helper(
base,
exp,
op.broadcast_power,
operator.pow,
_internal._power_scalar,
_internal._rpower_scalar) | [
"Returns result of first array elements raised to powers from second array, element-wise\n with broadcasting.\n\n Equivalent to ``base ** exp`` and ``mx.nd.broadcast_power(lhs, rhs)``.\n\n .. note::\n\n If the corresponding dimensions of two arrays have the same size or one of them has size 1,\n ... |
Please provide a description of the function:def maximum(lhs, rhs):
# pylint: disable= no-member, protected-access
return _ufunc_helper(
lhs,
rhs,
op.broadcast_maximum,
lambda x, y: x if x > y else y,
_internal._maximum_scalar,
None) | [
"Returns element-wise maximum of the input arrays with broadcasting.\n\n Equivalent to ``mx.nd.broadcast_maximum(lhs, rhs)``.\n\n .. note::\n\n If the corresponding dimensions of two arrays have the same size or one of them has size 1,\n then the arrays are broadcastable to a common shape.\n\n ... |
Please provide a description of the function:def minimum(lhs, rhs):
# pylint: disable= no-member, protected-access
return _ufunc_helper(
lhs,
rhs,
op.broadcast_minimum,
lambda x, y: x if x < y else y,
_internal._minimum_scalar,
None) | [
"Returns element-wise minimum of the input arrays with broadcasting.\n\n Equivalent to ``mx.nd.broadcast_minimum(lhs, rhs)``.\n\n .. note::\n\n If the corresponding dimensions of two arrays have the same size or one of them has size 1,\n then the arrays are broadcastable to a common shape.\n\n ... |
Please provide a description of the function:def equal(lhs, rhs):
# pylint: disable= no-member, protected-access
return _ufunc_helper(
lhs,
rhs,
op.broadcast_equal,
lambda x, y: 1 if x == y else 0,
_internal._equal_scalar,
None) | [
"Returns the result of element-wise **equal to** (==) comparison operation with\n broadcasting.\n\n For each element in input arrays, return 1(true) if corresponding elements are same,\n otherwise return 0(false).\n\n Equivalent to ``lhs == rhs`` and ``mx.nd.broadcast_equal(lhs, rhs)``.\n\n .. note::... |
Please provide a description of the function:def not_equal(lhs, rhs):
# pylint: disable= no-member, protected-access
return _ufunc_helper(
lhs,
rhs,
op.broadcast_not_equal,
lambda x, y: 1 if x != y else 0,
_internal._not_equal_scalar,
None) | [
"Returns the result of element-wise **not equal to** (!=) comparison operation\n with broadcasting.\n\n For each element in input arrays, return 1(true) if corresponding elements are different,\n otherwise return 0(false).\n\n Equivalent to ``lhs != rhs`` and ``mx.nd.broadcast_not_equal(lhs, rhs)``.\n\n... |
Please provide a description of the function:def greater(lhs, rhs):
# pylint: disable= no-member, protected-access
return _ufunc_helper(
lhs,
rhs,
op.broadcast_greater,
lambda x, y: 1 if x > y else 0,
_internal._greater_scalar,
_internal._lesser_scalar) | [
"Returns the result of element-wise **greater than** (>) comparison operation\n with broadcasting.\n\n For each element in input arrays, return 1(true) if lhs elements are greater than rhs,\n otherwise return 0(false).\n\n Equivalent to ``lhs > rhs`` and ``mx.nd.broadcast_greater(lhs, rhs)``.\n\n .. ... |
Please provide a description of the function:def greater_equal(lhs, rhs):
# pylint: disable= no-member, protected-access
return _ufunc_helper(
lhs,
rhs,
op.broadcast_greater_equal,
lambda x, y: 1 if x >= y else 0,
_internal._greater_equal_scalar,
_internal._l... | [
"Returns the result of element-wise **greater than or equal to** (>=) comparison\n operation with broadcasting.\n\n For each element in input arrays, return 1(true) if lhs elements are greater than equal to rhs,\n otherwise return 0(false).\n\n Equivalent to ``lhs >= rhs`` and ``mx.nd.broadcast_greater_... |
Please provide a description of the function:def lesser(lhs, rhs):
# pylint: disable= no-member, protected-access
return _ufunc_helper(
lhs,
rhs,
op.broadcast_lesser,
lambda x, y: 1 if x < y else 0,
_internal._lesser_scalar,
_internal._greater_scalar) | [
"Returns the result of element-wise **lesser than** (<) comparison operation\n with broadcasting.\n\n For each element in input arrays, return 1(true) if lhs elements are less than rhs,\n otherwise return 0(false).\n\n Equivalent to ``lhs < rhs`` and ``mx.nd.broadcast_lesser(lhs, rhs)``.\n\n .. note:... |
Please provide a description of the function:def lesser_equal(lhs, rhs):
# pylint: disable= no-member, protected-access
return _ufunc_helper(
lhs,
rhs,
op.broadcast_lesser_equal,
lambda x, y: 1 if x <= y else 0,
_internal._lesser_equal_scalar,
_internal._grea... | [
"Returns the result of element-wise **lesser than or equal to** (<=) comparison\n operation with broadcasting.\n\n For each element in input arrays, return 1(true) if lhs elements are\n lesser than equal to rhs, otherwise return 0(false).\n\n Equivalent to ``lhs <= rhs`` and ``mx.nd.broadcast_lesser_equ... |
Please provide a description of the function:def logical_and(lhs, rhs):
# pylint: disable= no-member, protected-access
return _ufunc_helper(
lhs,
rhs,
op.broadcast_logical_and,
lambda x, y: 1 if x and y else 0,
_internal._logical_and_scalar,
None) | [
"Returns the result of element-wise **logical and** comparison\n operation with broadcasting.\n\n For each element in input arrays, return 1(true) if lhs elements and rhs elements\n are true, otherwise return 0(false).\n\n Equivalent to ``lhs and rhs`` and ``mx.nd.broadcast_logical_and(lhs, rhs)``.\n\n ... |
Please provide a description of the function:def logical_or(lhs, rhs):
# pylint: disable= no-member, protected-access
return _ufunc_helper(
lhs,
rhs,
op.broadcast_logical_or,
lambda x, y: 1 if x or y else 0,
_internal._logical_or_scalar,
None) | [
"Returns the result of element-wise **logical or** comparison\n operation with broadcasting.\n\n For each element in input arrays, return 1(true) if lhs elements or rhs elements\n are true, otherwise return 0(false).\n\n Equivalent to ``lhs or rhs`` and ``mx.nd.broadcast_logical_or(lhs, rhs)``.\n\n .... |
Please provide a description of the function:def logical_xor(lhs, rhs):
# pylint: disable= no-member, protected-access
return _ufunc_helper(
lhs,
rhs,
op.broadcast_logical_xor,
lambda x, y: 1 if bool(x) ^ bool(y) else 0,
_internal._logical_xor_scalar,
None) | [
"Returns the result of element-wise **logical xor** comparison\n operation with broadcasting.\n\n For each element in input arrays, return 1(true) if lhs elements or rhs elements\n are true, otherwise return 0(false).\n\n Equivalent to ``bool(lhs) ^ bool(rhs)`` and ``mx.nd.broadcast_logical_xor(lhs, rhs... |
Please provide a description of the function:def concatenate(arrays, axis=0, always_copy=True):
assert isinstance(arrays, list)
assert len(arrays) > 0
assert isinstance(arrays[0], NDArray)
if not always_copy and len(arrays) == 1:
return arrays[0]
shape_axis = arrays[0].shape[axis]
... | [
"DEPRECATED, use ``concat`` instead\n\n Parameters\n ----------\n arrays : list of `NDArray`\n Arrays to be concatenate. They must have identical shape except\n the first dimension. They also must have the same data type.\n axis : int\n The axis along which to concatenate.\n alwa... |
Please provide a description of the function:def imdecode(str_img, clip_rect=(0, 0, 0, 0), out=None, index=0, channels=3, mean=None):
# pylint: disable= no-member, protected-access, too-many-arguments
if mean is None:
mean = NDArray(_new_empty_handle())
if out is None:
return _internal.... | [
"DEPRECATED, use mx.img instead\n\n Parameters\n ----------\n str_img : str\n Binary image data\n clip_rect : iterable of 4 int\n Clip decoded image to rectangle (x0, y0, x1, y1).\n out : NDArray\n Output buffer. Can be 3 dimensional (c, h, w) or 4 dimensional (n, c, h, w).\n ... |
Please provide a description of the function:def zeros(shape, ctx=None, dtype=None, **kwargs):
# pylint: disable= unused-argument
if ctx is None:
ctx = current_context()
dtype = mx_real_t if dtype is None else dtype
# pylint: disable= no-member, protected-access
return _internal._zeros(... | [
"Returns a new array filled with all zeros, with the given shape and type.\n\n Parameters\n ----------\n shape : int or tuple of int\n The shape of the empty array.\n ctx : Context, optional\n An optional device context (default is the current default context).\n dtype : str or numpy.dt... |
Please provide a description of the function:def eye(N, M=0, k=0, ctx=None, dtype=None, **kwargs):
# pylint: disable= unused-argument
if ctx is None:
ctx = current_context()
dtype = mx_real_t if dtype is None else dtype
# pylint: disable= no-member, protected-access
return _internal._ey... | [
"Return a 2-D array with ones on the diagonal and zeros elsewhere.\n\n Parameters\n ----------\n N: int\n Number of rows in the output.\n M: int, optional\n Number of columns in the output. If 0, defaults to N.\n k: int, optional\n Index of the diagonal: 0 (the default) refers to... |
Please provide a description of the function:def empty(shape, ctx=None, dtype=None):
if isinstance(shape, int):
shape = (shape, )
if ctx is None:
ctx = current_context()
if dtype is None:
dtype = mx_real_t
return NDArray(handle=_new_alloc_handle(shape, ctx, False, dtype)) | [
"Returns a new array of given shape and type, without initializing entries.\n\n Parameters\n ----------\n shape : int or tuple of int\n The shape of the empty array.\n ctx : Context, optional\n An optional device context (default is the current default context).\n dtype : str or numpy.d... |
Please provide a description of the function:def histogram(a, bins=10, range=None):
# pylint: disable= no-member, protected-access
if isinstance(bins, NDArray):
return _internal._histogram(data=a, bins=bins)
elif isinstance(bins, integer_types):
if range is None:
warnings.w... | [
"Compute the histogram of the input data.\n\n Parameters\n ----------\n a : NDArray\n Input data. The histogram is computed over the flattened array.\n bins : int or sequence of scalars\n If bins is an int, it defines the number of equal-width bins in the\n given range (10, by defau... |
Please provide a description of the function:def split_v2(ary, indices_or_sections, axis=0, squeeze_axis=False):
indices = []
axis_size = ary.shape[axis]
if isinstance(indices_or_sections, int):
sections = indices_or_sections
if axis_size % sections:
raise ValueError('array ... | [
"Split an array into multiple sub-arrays.\n\n Parameters\n ----------\n ary : NDArray\n Array to be divided into sub-arrays.\n indices_or_sections : int or tuple of ints\n If `indices_or_sections` is an integer, N, the array will be divided\n into N equal arrays along `axis`. If su... |
Please provide a description of the function:def to_dlpack_for_read(data):
data.wait_to_read()
dlpack = DLPackHandle()
check_call(_LIB.MXNDArrayToDLPack(data.handle, ctypes.byref(dlpack)))
return ctypes.pythonapi.PyCapsule_New(dlpack, _c_str_dltensor, _c_dlpack_deleter) | [
"Returns a reference view of NDArray that represents as DLManagedTensor until\n all previous write operations on the current array are finished.\n\n Parameters\n ----------\n data: NDArray\n input data.\n\n Returns\n -------\n PyCapsule (the pointer of DLManagedTensor)\n a refe... |
Please provide a description of the function:def to_dlpack_for_write(data):
check_call(_LIB.MXNDArrayWaitToWrite(data.handle))
dlpack = DLPackHandle()
check_call(_LIB.MXNDArrayToDLPack(data.handle, ctypes.byref(dlpack)))
return ctypes.pythonapi.PyCapsule_New(dlpack, _c_str_dltensor, _c_dlpack_delet... | [
"Returns a reference view of NDArray that represents as DLManagedTensor until\n all previous read/write operations on the current array are finished.\n\n Parameters\n ----------\n data: NDArray\n input data.\n\n Returns\n -------\n PyCapsule (the pointer of DLManagedTensor)\n a... |
Please provide a description of the function:def from_dlpack(dlpack):
handle = NDArrayHandle()
dlpack = ctypes.py_object(dlpack)
assert ctypes.pythonapi.PyCapsule_IsValid(dlpack, _c_str_dltensor), ValueError(
'Invalid DLPack Tensor. DLTensor capsules can be consumed only once.')
dlpack_hand... | [
"Returns a NDArray backed by a dlpack tensor.\n\n Parameters\n ----------\n dlpack: PyCapsule (the pointer of DLManagedTensor)\n input data\n\n Returns\n -------\n NDArray\n a NDArray backed by a dlpack tensor\n\n Examples\n --------\n >>> x = mx.nd.ones((2,3))\n >>> y = ... |
Please provide a description of the function:def from_numpy(ndarray, zero_copy=True):
def _make_manager_ctx(obj):
pyobj = ctypes.py_object(obj)
void_p = ctypes.c_void_p.from_buffer(pyobj)
ctypes.pythonapi.Py_IncRef(pyobj)
return void_p
def _make_dl_tensor(array):
i... | [
"Returns an MXNet's NDArray backed by Numpy's ndarray.\n\n Parameters\n ----------\n ndarray: numpy.ndarray\n input data\n\n zero_copy: bool\n Whether we use DLPack's zero-copy conversion to convert to MXNet's NDArray.\n This is only available for c-contiguous arrays, i.e. array.fla... |
Please provide a description of the function:def _get_index_nd(self, key):
def _is_advanced_index(index):
return not isinstance(index, py_slice)
if isinstance(key, (NDArray, np.ndarray, list, integer_types, py_slice)):
key = (key,)
assert isinstanc... | [
"Returns an index array for use in scatter_nd and gather_nd.",
"The definition of advanced index here includes integers as well, while\n integers are considered as basic index type when the key contains only\n slices and integers."
] |
Please provide a description of the function:def _prepare_value_nd(self, value, vshape):
if isinstance(value, numeric_types):
value_nd = full(shape=vshape, val=value, ctx=self.context, dtype=self.dtype)
elif isinstance(value, NDArray):
value_nd = value.as_in_context(self... | [
"Given value and vshape, create an `NDArray` from value with the same\n context and dtype as the current one and broadcast it to vshape."
] |
Please provide a description of the function:def _set_nd_basic_indexing(self, key, value):
shape = self.shape
if isinstance(key, integer_types):
if key < 0:
key += shape[0]
if key < 0 or key >= shape[0]:
if key < 0:
key... | [
"This function is called by __setitem__ when key is a basic index, i.e.\n an integer, or a slice, or a tuple of integers and slices. No restrictions\n on the values of slices' steps."
] |
Please provide a description of the function:def _set_nd_advanced_indexing(self, key, value):
indices = self._get_index_nd(key)
vshape = _get_oshape_of_gather_nd_op(self.shape, indices.shape)
value_nd = self._prepare_value_nd(value, vshape)
_internal._scatter_set_nd(lhs=self, rh... | [
"This function is called by __setitem__ when key is an advanced index."
] |
Please provide a description of the function:def _get_nd_basic_indexing(self, key):
shape = self.shape
if isinstance(key, integer_types):
if key > shape[0] - 1:
raise IndexError(
'index {} is out of bounds for axis 0 with size {}'.format(
... | [
"This function is called when key is a slice, or an integer,\n or a tuple of slices or integers"
] |
Please provide a description of the function:def _sync_copyfrom(self, source_array):
if not isinstance(source_array, np.ndarray):
try:
source_array = np.array(source_array, dtype=self.dtype)
except:
raise TypeError('array must consist of array-lik... | [
"Performs a synchronized copy from the `source_array` to the current array.\n This is called through ``x[:] = source_array``, where the `source_array`\n is a `numpy.ndarray` or array-like object.\n This function blocks until all the pending read/write operations with respect\n to the cur... |
Please provide a description of the function:def _slice(self, start, stop):
handle = NDArrayHandle()
start, stop, _ = _get_index_range(start, stop, self.shape[0])
check_call(_LIB.MXNDArraySlice(
self.handle, mx_uint(start), mx_uint(stop), ctypes.byref(handle)))
retu... | [
"Returns a sliced NDArray that shares memory with the current one.\n This is called through ``x[start:stop]``.\n\n Parameters\n ----------\n start : int\n Starting inclusive index of slice in the first dim.\n stop : int\n Finishing exclusive index of slice in... |
Please provide a description of the function:def _at(self, idx):
handle = NDArrayHandle()
if idx < 0:
length = self.shape[0]
idx += length
if idx < 0:
raise IndexError('index %d is out of bounds for axis 0 with size %d'
... | [
"Returns a view of the array sliced at `idx` in the first dim.\n This is called through ``x[idx]``.\n\n Parameters\n ----------\n idx : int\n index for slicing the `NDArray` in the first dim.\n\n Returns\n -------\n NDArray\n `NDArray` sharing t... |
Please provide a description of the function:def reshape(self, *shape, **kwargs):
if len(shape) == 1 and isinstance(shape[0], (list, tuple)):
shape = shape[0]
elif not shape:
shape = kwargs.get('shape')
assert shape, "Shape must be provided."
if not a... | [
"Returns a **view** of this array with a new shape without altering any data.\n\n Parameters\n ----------\n shape : tuple of int, or n ints\n The new shape should not change the array size, namely\n ``np.prod(new_shape)`` should be equal to ``np.prod(self.shape)``.\n ... |
Please provide a description of the function:def broadcast_to(self, shape):
cur_shape = self.shape
err_str = 'operands could not be broadcast together with remapped shapes' \
'[original->remapped]: {} and requested shape {}'.format(cur_shape, shape)
if len(shape) < len... | [
"Broadcasts the input array to a new shape.\n\n Broadcasting is only allowed on axes with size 1. The new shape cannot change\n the number of dimensions.\n For example, you could broadcast from shape (2, 1) to (2, 3), but not from\n shape (2, 3) to (2, 3, 3).\n\n Parameters\n ... |
Please provide a description of the function:def shape(self):
ndim = mx_int()
pdata = ctypes.POINTER(mx_int)()
check_call(_LIB.MXNDArrayGetShapeEx(
self.handle, ctypes.byref(ndim), ctypes.byref(pdata)))
if ndim.value == -1:
return None
else:
... | [
"Tuple of array dimensions.\n\n Examples\n --------\n >>> x = mx.nd.array([1, 2, 3, 4])\n >>> x.shape\n (4L,)\n >>> y = mx.nd.zeros((2, 3, 4))\n >>> y.shape\n (2L, 3L, 4L)\n "
] |
Please provide a description of the function:def context(self):
dev_typeid = ctypes.c_int()
dev_id = ctypes.c_int()
check_call(_LIB.MXNDArrayGetContext(
self.handle, ctypes.byref(dev_typeid), ctypes.byref(dev_id)))
return Context(Context.devtype2str[dev_typeid.value]... | [
"Device context of the array.\n\n Examples\n --------\n >>> x = mx.nd.array([1, 2, 3, 4])\n >>> x.context\n cpu(0)\n >>> type(x.context)\n <class 'mxnet.context.Context'>\n >>> y = mx.nd.zeros((2,3), mx.gpu(0))\n >>> y.context\n gpu(0)\n "... |
Please provide a description of the function:def dtype(self):
mx_dtype = ctypes.c_int()
check_call(_LIB.MXNDArrayGetDType(
self.handle, ctypes.byref(mx_dtype)))
return _DTYPE_MX_TO_NP[mx_dtype.value] | [
"Data-type of the array's elements.\n\n Returns\n -------\n numpy.dtype\n This NDArray's data type.\n\n Examples\n --------\n >>> x = mx.nd.zeros((2,3))\n >>> x.dtype\n <type 'numpy.float32'>\n >>> y = mx.nd.zeros((2,3), dtype='int32')\n ... |
Please provide a description of the function:def _fresh_grad(self):
out = ctypes.c_int()
check_call(_LIB.MXNDArrayGetGradState(self.handle, ctypes.byref(out)))
return out.value | [
"Whether this array's corresponding gradient array\n (registered via `autograd.mark_variables`) has been\n updated by `autograd.backward` since last reset.\n\n `_fresh_grad` need to be manually set to False\n after consuming gradient (usually after updating this\n array).\n ... |
Please provide a description of the function:def asnumpy(self):
data = np.empty(self.shape, dtype=self.dtype)
check_call(_LIB.MXNDArraySyncCopyToCPU(
self.handle,
data.ctypes.data_as(ctypes.c_void_p),
ctypes.c_size_t(data.size)))
return data | [
"Returns a ``numpy.ndarray`` object with value copied from this array.\n\n Examples\n --------\n >>> x = mx.nd.ones((2,3))\n >>> y = x.asnumpy()\n >>> type(y)\n <type 'numpy.ndarray'>\n >>> y\n array([[ 1., 1., 1.],\n [ 1., 1., 1.]], dtype=fl... |
Please provide a description of the function:def astype(self, dtype, copy=True):
if not copy and np.dtype(dtype) == self.dtype:
return self
res = empty(self.shape, ctx=self.context, dtype=dtype)
self.copyto(res)
return res | [
"Returns a copy of the array after casting to a specified type.\n\n Parameters\n ----------\n dtype : numpy.dtype or str\n The type of the returned array.\n copy : bool\n Default `True`. By default, astype always returns a newly\n allocated ndarray on the... |
Please provide a description of the function:def copyto(self, other):
if isinstance(other, NDArray):
if other.handle is self.handle:
warnings.warn('You are attempting to copy an array to itself', RuntimeWarning)
return False
return _internal._copy... | [
"Copies the value of this array to another array.\n\n If ``other`` is a ``NDArray`` object, then ``other.shape`` and\n ``self.shape`` should be the same. This function copies the value from\n ``self`` to ``other``.\n\n If ``other`` is a context, a new ``NDArray`` will be first created on... |
Please provide a description of the function:def as_in_context(self, context):
if self.context == context:
return self
return self.copyto(context) | [
"Returns an array on the target device with the same value as this array.\n\n If the target context is the same as ``self.context``, then ``self`` is\n returned. Otherwise, a copy is made.\n\n Parameters\n ----------\n context : Context\n The target context.\n\n ... |
Please provide a description of the function:def attach_grad(self, grad_req='write', stype=None):
from . import zeros as _zeros
if stype is not None:
grad = _zeros(self.shape, stype=stype)
else:
grad = op.zeros_like(self) # pylint: disable=undefined-variable
... | [
"Attach a gradient buffer to this NDArray, so that `backward`\n can compute gradient with respect to it.\n\n Parameters\n ----------\n grad_req : {'write', 'add', 'null'}\n How gradient will be accumulated.\n - 'write': gradient will be overwritten on every backward... |
Please provide a description of the function:def grad(self):
from . import _ndarray_cls
hdl = NDArrayHandle()
check_call(_LIB.MXNDArrayGetGrad(self.handle, ctypes.byref(hdl)))
if hdl.value is None:
return None
return _ndarray_cls(hdl) | [
"Returns gradient buffer attached to this NDArray."
] |
Please provide a description of the function:def detach(self):
from . import _ndarray_cls
hdl = NDArrayHandle()
check_call(_LIB.MXNDArrayDetach(self.handle, ctypes.byref(hdl)))
return _ndarray_cls(hdl) | [
"Returns a new NDArray, detached from the current graph."
] |
Please provide a description of the function:def backward(self, out_grad=None, retain_graph=False, train_mode=True):
if out_grad is None:
ograd_handles = [NDArrayHandle(0)]
else:
ograd_handles = [out_grad.handle]
check_call(_LIB.MXAutogradBackwardEx(
... | [
"Compute the gradients of this NDArray w.r.t variables.\n\n Parameters\n ----------\n out_grad : NDArray, optional\n Gradient with respect to head.\n retain_graph : bool, optional\n Whether to retain the computaion graph for another backward\n pass on the... |
Please provide a description of the function:def build(self, align_path):
file = open(align_path, 'r')
lines = file.readlines()
file.close()
# words: list([op, ed, word])
words = []
for line in lines:
_op, _ed, word = line.strip().split(' ')
... | [
"\n Build the align array\n "
] |
Please provide a description of the function:def sentence(self, padding=75):
vec = word_to_vector(self.sentence_str)
vec += [-1] * (padding - self.sentence_length)
return np.array(vec, dtype=np.int32) | [
"\n Get sentence\n "
] |
Please provide a description of the function:def word(self, _id, padding=75):
word = self.words[_id][2]
vec = word_to_vector(word)
vec += [-1] * (padding - len(vec))
return np.array(vec, dtype=np.int32) | [
"\n Get words\n "
] |
Please provide a description of the function:def word_frame_pos(self, _id):
left = int(self.words[_id][0]/1000)
right = max(left+1, int(self.words[_id][1]/1000))
return (left, right) | [
"\n Get the position of words\n "
] |
Please provide a description of the function:def prepare_sparse_params(self, param_rowids):
'''Prepares the module for processing a data batch by pulling row_sparse
parameters from kvstore to all devices based on rowids.
Parameters
----------
param_rowids : dict of str to NDArra... | [] |
Please provide a description of the function:def save_params(self, fname):
arg_params, aux_params = self.get_params_from_kv(self._arg_params, self._aux_params)
save_dict = {('arg:%s' % k) : v.as_in_context(mx.cpu()) for k, v in arg_params.items()}
save_dict.update({('aux:%s' % k) : v.as... | [
"Saves model parameters to file.\n Parameters\n ----------\n fname : str\n Path to output param file.\n Examples\n --------\n >>> # An example of saving module parameters.\n >>> mod.save_params('myfile')\n "
] |
Please provide a description of the function:def get_params_from_kv(self, arg_params, aux_params):
assert(self._kvstore is not None)
for name, block in zip(self._exec_group.param_names, self._exec_group.param_arrays):
assert(isinstance(block, list))
if block[0].stype == ... | [
" Copy data from kvstore to `arg_params` and `aux_params`.\n Parameters\n ----------\n arg_params : list of NDArray\n Target parameter arrays.\n aux_params : list of NDArray\n Target aux arrays.\n Notes\n -----\n - This function will inplace upd... |
Please provide a description of the function:def clip_by_global_norm_per_ctx(self, max_norm=1.0, param_names=None):
assert self.binded and self.params_initialized and self.optimizer_initialized
num_ctx = len(self._exec_group.grad_arrays[0])
grad_array_per_ctx = [[] for i in range(num_ct... | [
"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\n The method is first used in\n `[ICML2013] On the difficulty of training recurrent neural networks`\n\n Note that ... |
Please provide a description of the function:def rescale_grad(self, scale=None, param_name=None):
if scale is None or param_name is None:
return
param_idx = self._exec_group.param_names.index(param_name)
grad_vals = self._exec_group.grad_arrays[param_idx]
for grad in... | [
" Rescale the gradient of provided parameters by a certain scale "
] |
Please provide a description of the function:def factorization_machine_model(factor_size, num_features,
lr_mult_config, wd_mult_config, init_config):
x = mx.symbol.Variable("data", stype='csr')
# factor, linear and bias terms
v = mx.symbol.Variable("v", shape=(num_featur... | [
" builds factorization machine network with proper formulation:\n y = w_0 \\sum(x_i w_i) + 0.5(\\sum\\sum<v_i,v_j>x_ix_j - \\sum<v_iv_i>x_i^2)\n "
] |
Please provide a description of the function:def batchify(data, batch_size):
nbatch = data.shape[0] // batch_size
data = data[:nbatch * batch_size]
data = data.reshape((batch_size, nbatch)).T
return data | [
"Reshape data into (num_example, batch_size)"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.