Code stringlengths 103 85.9k | Summary listlengths 0 94 |
|---|---|
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\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... |
Please provide a description of the function:def convert_mat_to_images(args):
'''convert the caltech101 mat file to images
Examples
--------
python convert_data.py --dataset /home/ubuntu/datasets/caltech101/data/caltech101_silhouettes_28.mat --save_path /home/ubuntu/datasets/caltech101/data/ --invert --... | [] |
Please provide a description of the function:def build(args) -> None:
venv_exe = shutil.which('virtualenv')
pyexe = shutil.which(args.pyexe)
if not venv_exe:
logging.warn("virtualenv wasn't found in path, it's recommended to install virtualenv to manage python environments")
if not pyexe:
... | [
"Build using CMake"
] |
Please provide a description of the function:def create_network(batch_size, update_freq):
import logging
head = '%(asctime)-15s %(message)s'
logging.basicConfig(level=logging.INFO, format=head)
train_data = np.random.randint(1, 5, [1000, 2])
weights = np.array([1.0, 2.0])
train_label = tra... | [
"Create a linear regression network for performing SVRG optimization.\n Parameters\n ----------\n batch_size: int\n Size of data split\n update_freq: int\n Update Frequency for calculating full gradients\n\n Returns\n ----------\n di: mx.io.NDArrayIter\n Data iterator\n ... |
Please provide a description of the function:def get_squeezenet(version, pretrained=False, ctx=cpu(),
root=os.path.join(base.data_dir(), 'models'), **kwargs):
r
net = SqueezeNet(version, **kwargs)
if pretrained:
from ..model_store import get_model_file
net.load_parameters(... | [
"SqueezeNet model from the `\"SqueezeNet: AlexNet-level accuracy with 50x fewer parameters\n and <0.5MB model size\" <https://arxiv.org/abs/1602.07360>`_ paper.\n SqueezeNet 1.1 model from the `official SqueezeNet repo\n <https://github.com/DeepScale/SqueezeNet/tree/master/SqueezeNet_v1.1>`_.\n SqueezeN... |
Please provide a description of the function:def parse_helper(attrs, attrs_name, alt_value=None):
tuple_re = re.compile('\([0-9L|,| ]+\)')
if not attrs:
return alt_value
attrs_str = None if attrs.get(attrs_name) is None else str(attrs.get(attrs_name))
if attrs_str is None:
return al... | [
"Helper function to parse operator attributes in required format."
] |
Please provide a description of the function:def transform_padding(pad_width):
num_pad_values = len(pad_width)
onnx_pad_width = [0]*num_pad_values
start_index = 0
# num_pad_values will always be multiple of 2
end_index = int(num_pad_values/2)
for idx in range(0, num_pad_values):
if... | [
"Helper function to convert padding format for pad operator.\n "
] |
Please provide a description of the function:def convert_string_to_list(string_val):
result_list = []
list_string = string_val.split(',')
for val in list_string:
val = str(val.strip())
val = val.replace("(", "")
val = val.replace(")", "")
val = val.replace("L", "")
... | [
"Helper function to convert string to list.\n Used to convert shape attribute string to list format.\n "
] |
Please provide a description of the function:def get_inputs(node, kwargs):
name = node["name"]
proc_nodes = kwargs["proc_nodes"]
index_lookup = kwargs["index_lookup"]
inputs = node["inputs"]
attrs = node.get("attrs", {})
input_nodes = []
for ip in inputs:
input_node_id = index_... | [
"Helper function to get inputs"
] |
Please provide a description of the function:def create_basic_op_node(op_name, node, kwargs):
name, input_nodes, _ = get_inputs(node, kwargs)
node = onnx.helper.make_node(
op_name,
input_nodes,
[name],
name=name
)
return [node] | [
"Helper function to create a basic operator\n node that doesn't contain op specific attrs"
] |
Please provide a description of the function:def convert_weights_and_inputs(node, **kwargs):
name, _, _ = get_inputs(node, kwargs)
if kwargs["is_input"] is False:
weights = kwargs["weights"]
initializer = kwargs["initializer"]
np_arr = weights[name]
data_type = onnx.mapping... | [
"Helper function to convert weights and inputs.\n "
] |
Please provide a description of the function:def convert_convolution(node, **kwargs):
name, input_nodes, attrs = get_inputs(node, kwargs)
kernel_dims = list(parse_helper(attrs, "kernel"))
stride_dims = list(parse_helper(attrs, "stride", [1, 1]))
pad_dims = list(parse_helper(attrs, "pad", [0, 0]))
... | [
"Map MXNet's convolution operator attributes to onnx's Conv operator\n and return the created node.\n "
] |
Please provide a description of the function:def convert_deconvolution(node, **kwargs):
name, inputs, attrs = get_inputs(node, kwargs)
kernel_dims = list(parse_helper(attrs, "kernel"))
stride_dims = list(parse_helper(attrs, "stride", [1, 1]))
pad_dims = list(parse_helper(attrs, "pad", [0, 0]))
... | [
"Map MXNet's deconvolution operator attributes to onnx's ConvTranspose operator\n and return the created node.\n "
] |
Please provide a description of the function:def convert_crop(node, **kwargs):
name, inputs, attrs = get_inputs(node, kwargs)
num_inputs = len(inputs)
y, x = list(parse_helper(attrs, "offset", [0, 0]))
h, w = list(parse_helper(attrs, "h_w", [0, 0]))
if num_inputs > 1:
h, w = kwargs["ou... | [
"Map MXNet's crop operator attributes to onnx's Crop operator\n and return the created node.\n "
] |
Please provide a description of the function:def convert_fully_connected(node, **kwargs):
name, input_nodes, attrs = get_inputs(node, kwargs)
initializer = kwargs["initializer"]
no_bias = get_boolean_attribute_value(attrs, "no_bias")
fcnode = []
op_name = "flatten_" + str(kwargs["idx"])
... | [
"Map MXNet's FullyConnected operator attributes to onnx's Gemm operator\n and return the created node.\n "
] |
Please provide a description of the function:def convert_batchnorm(node, **kwargs):
name, input_nodes, attrs = get_inputs(node, kwargs)
momentum = float(attrs.get("momentum", 0.9))
eps = float(attrs.get("eps", 0.001))
bn_node = onnx.helper.make_node(
"BatchNormalization",
input_no... | [
"Map MXNet's BatchNorm operator attributes to onnx's BatchNormalization operator\n and return the created node.\n "
] |
Please provide a description of the function:def convert_activation(node, **kwargs):
name, input_nodes, attrs = get_inputs(node, kwargs)
act_type = attrs["act_type"]
# Creating a dictionary here, but if this titlecase pattern
# mxnet_name.title()
act_types = {
"tanh": "Tanh",
... | [
"Map MXNet's Activation operator attributes to onnx's Tanh/Relu operator\n and return the created node.\n "
] |
Please provide a description of the function:def convert_pad(node, **kwargs):
name, input_nodes, attrs = get_inputs(node, kwargs)
mxnet_pad_width = convert_string_to_list(attrs.get("pad_width"))
onnx_pad_width = transform_padding(mxnet_pad_width)
pad_mode = attrs.get("mode")
if pad_mode == "... | [
"Map MXNet's pad operator attributes to onnx's Pad operator\n and return the created node.\n "
] |
Please provide a description of the function:def create_helper_trans_node(op_name, input_node, node_name):
node_name = op_name + "_" + node_name
trans_node = onnx.helper.make_node(
'Transpose',
inputs=[input_node],
outputs=[node_name],
name=node_name
)
return trans_n... | [
"create extra transpose node for dot operator"
] |
Please provide a description of the function:def convert_dot(node, **kwargs):
name, input_nodes, attrs = get_inputs(node, kwargs)
input_node_a = input_nodes[0]
input_node_b = input_nodes[1]
trans_a_node = None
trans_b_node = None
trans_a = get_boolean_attribute_value(attrs, "transpose_a")... | [
"Map MXNet's dot operator attributes to onnx's\n MatMul and Transpose operators based on the values set for\n transpose_a, transpose_b attributes."
] |
Please provide a description of the function:def convert_linalg_gemm2(node, **kwargs):
name, input_nodes, attrs = get_inputs(node, kwargs)
# Getting the attributes and assigning default values.
alpha = float(attrs.get("alpha", 1.0))
trans_a = get_boolean_attribute_value(attrs, "transpose_a")
t... | [
"Map MXNet's _linalg_gemm2 operator attributes to onnx's\n MatMul and Transpose operators based on the values set for\n transpose_a, transpose_b attributes.\n Return multiple nodes created.\n "
] |
Please provide a description of the function:def convert_pooling(node, **kwargs):
name, input_nodes, attrs = get_inputs(node, kwargs)
kernel = eval(attrs["kernel"])
pool_type = attrs["pool_type"] if attrs.get("pool_type") else "max"
stride = eval(attrs["stride"]) if attrs.get("stride") else (1, 1)... | [
"Map MXNet's Pooling operator attributes to onnx's\n MaxPool/AveragePool/GlobalMaxPool/GlobalAveragePool operators\n based on the input node's attributes and return the created node.\n "
] |
Please provide a description of the function:def convert_instancenorm(node, **kwargs):
name, input_nodes, attrs = get_inputs(node, kwargs)
eps = float(attrs.get("eps", 0.001))
node = onnx.helper.make_node(
'InstanceNormalization',
inputs=input_nodes,
outputs=[name],
na... | [
"Map MXNet's InstanceNorm operator attributes to onnx's InstanceNormalization operator\n based on the input node's attributes and return the created node.\n "
] |
Please provide a description of the function:def convert_leakyrelu(node, **kwargs):
name, input_nodes, attrs = get_inputs(node, kwargs)
act_type = attrs.get("act_type", "leaky")
alpha = float(attrs.get("slope", 0.25))
act_name = {"elu": "Elu", "leaky": "LeakyRelu", "prelu": "PRelu",
... | [
"Map MXNet's LeakyReLU operator attributes to onnx's Elu/LeakyRelu/PRelu operators\n based on the input node's attributes and return the created node.\n "
] |
Please provide a description of the function:def convert_softmax(node, **kwargs):
name, input_nodes, attrs = get_inputs(node, kwargs)
axis = int(attrs.get("axis", -1))
softmax_node = onnx.helper.make_node(
"Softmax",
input_nodes,
[name],
axis=axis,
name=name
... | [
"Map MXNet's softmax operator attributes to onnx's Softmax operator\n and return the created node.\n "
] |
Please provide a description of the function:def convert_softmax_output(node, **kwargs):
name = node["name"]
input1_idx = kwargs["index_lookup"][node["inputs"][0][0]]
input1 = kwargs["proc_nodes"][input1_idx]
softmax_node = onnx.helper.make_node(
"Softmax",
[input1.name],
... | [
"Map MXNet's SoftmaxOutput operator attributes to onnx's Softmax operator\n and return the created node.\n "
] |
Please provide a description of the function:def convert_logistic_regression_output(node, **kwargs):
name = node["name"]
input1_idx = kwargs["index_lookup"][node["inputs"][0][0]]
input1 = kwargs["proc_nodes"][input1_idx]
sigmoid_node = onnx.helper.make_node(
"Sigmoid",
[input1.name]... | [
"Map MXNet's SoftmaxOutput operator attributes to onnx's Softmax operator\n and return the created node.\n "
] |
Please provide a description of the function:def convert_concat(node, **kwargs):
name, input_nodes, attrs = get_inputs(node, kwargs)
axis = int(attrs.get("dim", 1))
concat_node = onnx.helper.make_node(
"Concat",
input_nodes,
[name],
axis=axis,
name=name
)
... | [
"Map MXNet's Concat operator attributes to onnx's Concat operator\n and return the created node.\n "
] |
Please provide a description of the function:def convert_transpose(node, **kwargs):
name, input_nodes, attrs = get_inputs(node, kwargs)
axes = attrs.get("axes", ())
if axes:
axes = tuple(map(int, re.findall(r'\d+', axes)))
transpose_node = onnx.helper.make_node(
"Transpose... | [
"Map MXNet's transpose operator attributes to onnx's Transpose operator\n and return the created node.\n "
] |
Please provide a description of the function:def convert_lrn(node, **kwargs):
name, input_nodes, attrs = get_inputs(node, kwargs)
alpha = float(attrs.get("alpha", 0.0001))
beta = float(attrs.get("beta", 0.75))
bias = float(attrs.get("knorm", 1.0))
size = int(attrs.get("nsize"))
lrn_node =... | [
"Map MXNet's LRN operator attributes to onnx's LRN operator\n and return the created node.\n "
] |
Please provide a description of the function:def convert_l2normalization(node, **kwargs):
name, input_nodes, attrs = get_inputs(node, kwargs)
mode = attrs.get("mode", "instance")
if mode != "channel":
raise AttributeError("L2Normalization: ONNX currently supports channel mode only")
l2no... | [
"Map MXNet's L2Normalization operator attributes to onnx's LpNormalization operator\n and return the created node.\n "
] |
Please provide a description of the function:def convert_dropout(node, **kwargs):
name, input_nodes, attrs = get_inputs(node, kwargs)
probability = float(attrs.get("p", 0.5))
dropout_node = onnx.helper.make_node(
"Dropout",
input_nodes,
[name],
ratio=probability,
... | [
"Map MXNet's Dropout operator attributes to onnx's Dropout operator\n and return the created node.\n "
] |
Please provide a description of the function:def convert_clip(node, **kwargs):
name, input_nodes, attrs = get_inputs(node, kwargs)
a_min = np.float(attrs.get('a_min', -np.inf))
a_max = np.float(attrs.get('a_max', np.inf))
clip_node = onnx.helper.make_node(
"Clip",
input_nodes,
... | [
"Map MXNet's Clip operator attributes to onnx's Clip operator\n and return the created node.\n "
] |
Please provide a description of the function:def scalar_op_helper(node, op_name, **kwargs):
name, input_nodes, attrs = get_inputs(node, kwargs)
from onnx import numpy_helper
input_type = kwargs["in_type"]
scalar_value = np.array([attrs.get("scalar", 1)],
dtype=onnx.mappi... | [
"Helper function for scalar arithmetic operations"
] |
Please provide a description of the function:def convert_argmax(node, **kwargs):
name, input_nodes, attrs = get_inputs(node, kwargs)
axis = int(attrs.get("axis"))
keepdims = get_boolean_attribute_value(attrs, "keepdims")
node = onnx.helper.make_node(
'ArgMax',
inputs=input_nodes,
... | [
"Map MXNet's argmax operator attributes to onnx's ArgMax operator\n and return the created node.\n "
] |
Please provide a description of the function:def convert_reshape(node, **kwargs):
name, input_nodes, attrs = get_inputs(node, kwargs)
output_shape_list = convert_string_to_list(attrs["shape"])
initializer = kwargs["initializer"]
output_shape_np = np.array(output_shape_list, dtype='int64')
dat... | [
"Map MXNet's Reshape operator attributes to onnx's Reshape operator.\n Converts output shape attribute to output shape tensor\n and return multiple created nodes.\n "
] |
Please provide a description of the function:def convert_cast(node, **kwargs):
name, input_nodes, attrs = get_inputs(node, kwargs)
dtype = attrs["dtype"]
# dtype can be mapped only with types from TensorProto
# float32 is mapped to float and float64 to double in onnx
# following tensorproto m... | [
"Map MXNet's Cast operator attributes to onnx's Cast operator\n and return the created node.\n "
] |
Please provide a description of the function:def convert_slice_axis(node, **kwargs):
name, input_nodes, attrs = get_inputs(node, kwargs)
axes = int(attrs.get("axis"))
starts = int(attrs.get("begin"))
ends = int(attrs.get("end", None))
if not ends:
raise ValueError("Slice: ONNX doesnt't... | [
"Map MXNet's slice_axis operator attributes to onnx's Slice operator\n and return the created node.\n "
] |
Please provide a description of the function:def convert_slice_channel(node, **kwargs):
name, input_nodes, attrs = get_inputs(node, kwargs)
num_outputs = int(attrs.get("num_outputs"))
axis = int(attrs.get("axis", 1))
squeeze_axis = int(attrs.get("squeeze_axis", 0))
if squeeze_axis == 1 and nu... | [
"Map MXNet's SliceChannel operator attributes to onnx's Squeeze or Split\n operator based on squeeze_axis attribute\n and return the created node.\n "
] |
Please provide a description of the function:def convert_expand_dims(node, **kwargs):
name, input_nodes, attrs = get_inputs(node, kwargs)
axis = int(attrs.get("axis"))
node = onnx.helper.make_node(
"Unsqueeze",
input_nodes,
[name],
axes=[axis],
name=name,
)... | [
"Map MXNet's expand_dims operator attributes to onnx's Unsqueeze operator\n and return the created node.\n "
] |
Please provide a description of the function:def convert_squeeze(node, **kwargs):
name, input_nodes, attrs = get_inputs(node, kwargs)
axis = attrs.get("axis", None)
if not axis:
raise AttributeError("Squeeze: Missing axis attribute: ONNX currently requires axis to "
... | [
"Map MXNet's squeeze operator attributes to onnx's squeeze operator\n and return the created node.\n "
] |
Please provide a description of the function:def convert_depthtospace(node, **kwargs):
name, input_nodes, attrs = get_inputs(node, kwargs)
blksize = int(attrs.get("block_size", 0))
node = onnx.helper.make_node(
"DepthToSpace",
input_nodes,
[name],
blocksize=blksize,
... | [
"Map MXNet's depth_to_space operator attributes to onnx's\n DepthToSpace operator and return the created node.\n "
] |
Please provide a description of the function:def convert_square(node, **kwargs):
name, input_nodes, _ = get_inputs(node, kwargs)
initializer = kwargs["initializer"]
data_type = onnx.mapping.NP_TYPE_TO_TENSOR_TYPE[np.dtype('int64')]
power2_name = "square_tensor" + str(kwargs["idx"])
tensor_nod... | [
"Map MXNet's square operator attributes to onnx's Pow operator\n and return the created node.\n "
] |
Please provide a description of the function:def convert_sum(node, **kwargs):
name, input_nodes, attrs = get_inputs(node, kwargs)
mx_axis = attrs.get("axis", None)
axes = convert_string_to_list(str(mx_axis)) if mx_axis is not None else None
keepdims = get_boolean_attribute_value(attrs, "keepdims"... | [
"Map MXNet's sum operator attributes to onnx's ReduceSum operator\n and return the created node.\n "
] |
Please provide a description of the function:def convert_hardsigmoid(node, **kwargs):
name, input_nodes, attrs = get_inputs(node, kwargs)
# Converting to float32
alpha = float(attrs.get("alpha", 0.2))
beta = float(attrs.get("beta", 0.5))
node = onnx.helper.make_node(
'HardSigmoid',
... | [
"Map MXNet's hard_sigmoid operator attributes to onnx's HardSigmoid operator\n and return the created node.\n "
] |
Please provide a description of the function:def convert_logsoftmax(node, **kwargs):
name, input_nodes, attrs = get_inputs(node, kwargs)
# Converting to int
axis = int(attrs.get("axis", -1))
temp = attrs.get("temperature", 'None')
if temp != 'None':
raise AttributeError("LogSoftMax: ON... | [
"Map MXNet's log_softmax operator attributes to onnx's LogSoftMax operator\n and return the created node.\n "
] |
Please provide a description of the function:def convert_norm(node, **kwargs):
name, input_nodes, attrs = get_inputs(node, kwargs)
mx_axis = attrs.get("axis", None)
axes = convert_string_to_list(str(mx_axis)) if mx_axis else None
keepdims = get_boolean_attribute_value(attrs, "keepdims")
ord =... | [
"Map MXNet's norm operator attributes to onnx's ReduceL1 and ReduceL2 operators\n and return the created node.\n "
] |
Please provide a description of the function:def convert_multinomial(node, **kwargs):
name, input_nodes, attrs = get_inputs(node, kwargs)
dtype = onnx.mapping.NP_TYPE_TO_TENSOR_TYPE[np.dtype(attrs.get("dtype", 'int32'))]
sample_size = convert_string_to_list(attrs.get("shape", '1'))
if len(sample_si... | [
"Map MXNet's multinomial operator attributes to onnx's\n Multinomial operator and return the created node.\n "
] |
Please provide a description of the function:def convert_random_uniform(node, **kwargs):
name, input_nodes, attrs = get_inputs(node, kwargs)
# Converting to float32
low = float(attrs.get("low", 0))
high = float(attrs.get("high", 1.0))
shape = convert_string_to_list(attrs.get('shape', '[]'))
... | [
"Map MXNet's random_uniform operator attributes to onnx's RandomUniform\n operator and return the created node.\n "
] |
Please provide a description of the function:def convert_random_normal(node, **kwargs):
name, input_nodes, attrs = get_inputs(node, kwargs)
# Converting to float32
mean = float(attrs.get("loc", 0))
scale = float(attrs.get("scale", 1.0))
shape = convert_string_to_list(attrs.get('shape', '[]'))
... | [
"Map MXNet's random_normal operator attributes to onnx's RandomNormal\n operator and return the created node.\n "
] |
Please provide a description of the function:def convert_roipooling(node, **kwargs):
name, input_nodes, attrs = get_inputs(node, kwargs)
pooled_shape = convert_string_to_list(attrs.get('pooled_size'))
scale = float(attrs.get("spatial_scale"))
node = onnx.helper.make_node(
'MaxRoiPool',
... | [
"Map MXNet's ROIPooling operator attributes to onnx's MaxRoiPool\n operator and return the created node.\n "
] |
Please provide a description of the function:def convert_tile(node, **kwargs):
name, input_nodes, attrs = get_inputs(node, kwargs)
reps_list = convert_string_to_list(attrs["reps"])
initializer = kwargs["initializer"]
reps_shape_np = np.array(reps_list, dtype='int64')
data_type = onnx.mapping.... | [
"Map MXNet's Tile operator attributes to onnx's Tile\n operator and return the created node.\n "
] |
Please provide a description of the function:def convert_broadcast_to(node, **kwargs):
name, input_nodes, attrs = get_inputs(node, kwargs)
shape_list = convert_string_to_list(attrs["shape"])
initializer = kwargs["initializer"]
output_shape_np = np.array(shape_list, dtype='int64')
data_type = ... | [
"Map MXNet's broadcast_to operator attributes to onnx's Expand\n operator and return the created node.\n "
] |
Please provide a description of the function:def exe(self):
return self._buckets[self.curr_bucket_key]['exe'][tuple(self.data_shapes.items())] | [
"Get the current executor\n\n Returns\n -------\n exe : mxnet.executor.Executor\n "
] |
Please provide a description of the function:def compute_internal(self, sym_name, bucket_kwargs=None, **arg_dict):
data_shapes = {k: v.shape for k, v in arg_dict.items()}
self.switch_bucket(bucket_kwargs=bucket_kwargs,
data_shapes=data_shapes)
internal_sym = s... | [
"\n View the internal symbols using the forward function.\n\n :param sym_name:\n :param bucket_kwargs:\n :param input_dict:\n :return:\n "
] |
Please provide a description of the function:def init_from_fcnxs(ctx, fcnxs_symbol, fcnxs_args_from, fcnxs_auxs_from):
fcnxs_args = fcnxs_args_from.copy()
fcnxs_auxs = fcnxs_auxs_from.copy()
for k,v in fcnxs_args.items():
if(v.context != ctx):
fcnxs_args[k] = mx.nd.zeros(v.shape, ct... | [
" use zero initialization for better convergence, because it tends to oputut 0,\n and the label 0 stands for background, which may occupy most size of one image.\n "
] |
Please provide a description of the function:def residual_unit(data, num_filter, stride, dim_match, name, bottle_neck=True, num_group=32, bn_mom=0.9, workspace=256, memonger=False):
if bottle_neck:
# the same as https://github.com/facebook/fb.resnet.torch#notes, a bit difference with origin paper
... | [
"Return ResNet Unit symbol for building ResNet\n Parameters\n ----------\n data : str\n Input data\n num_filter : int\n Number of output channels\n bnf : int\n Bottle neck channels factor with regard to num_filter\n stride : tuple\n Stride used in convolution\n dim_m... |
Please provide a description of the function:def resnext(units, num_stages, filter_list, num_classes, num_group, image_shape, bottle_neck=True, bn_mom=0.9, workspace=256, dtype='float32', memonger=False):
num_unit = len(units)
assert(num_unit == num_stages)
data = mx.sym.Variable(name='data')
if dt... | [
"Return ResNeXt symbol of\n Parameters\n ----------\n units : list\n Number of units in each stage\n num_stages : int\n Number of stage\n filter_list : list\n Channel size of each stage\n num_classes : int\n Ouput size of symbol\n num_groupes: int\n Number of conv... |
Please provide a description of the function:def get_symbol(num_classes, num_layers, image_shape, num_group=32, conv_workspace=256, dtype='float32', **kwargs):
image_shape = [int(l) for l in image_shape.split(',')]
(nchannel, height, width) = image_shape
if height <= 32:
num_stages = 3
... | [
"\n Adapted from https://github.com/tornadomeet/ResNet/blob/master/train_resnet.py\n Original author Wei Wu\n "
] |
Please provide a description of the function:def var(name, attr=None, shape=None, lr_mult=None, wd_mult=None, dtype=None,
init=None, stype=None, **kwargs):
if not isinstance(name, string_types):
raise TypeError('Expect a string for variable `name`')
handle = SymbolHandle()
check_call(_L... | [
"Creates a symbolic variable with specified name.\n\n Example\n -------\n >>> data = mx.sym.Variable('data', attr={'a': 'b'})\n >>> data\n <Symbol data>\n >>> csr_data = mx.sym.Variable('csr_data', stype='csr')\n >>> csr_data\n <Symbol csr_data>\n >>> row_sparse_weight = mx.sym.Variable('... |
Please provide a description of the function:def Group(symbols):
if not symbols or any(not isinstance(sym, Symbol) for sym in symbols):
raise TypeError('Expected a list of symbols as input')
handle = SymbolHandle()
check_call(_LIB.MXSymbolCreateGroup(
mx_uint(len(symbols)),
c_ha... | [
"Creates a symbol that contains a collection of other symbols, grouped together.\n\n Example\n -------\n >>> a = mx.sym.Variable('a')\n >>> b = mx.sym.Variable('b')\n >>> mx.sym.Group([a,b])\n <Symbol Grouped>\n\n Parameters\n ----------\n symbols : list\n List of symbols to be gro... |
Please provide a description of the function:def load(fname):
if not isinstance(fname, string_types):
raise TypeError('fname need to be string')
handle = SymbolHandle()
check_call(_LIB.MXSymbolCreateFromFile(c_str(fname), ctypes.byref(handle)))
return Symbol(handle) | [
"Loads symbol from a JSON file.\n\n You can also use pickle to do the job if you only work on python.\n The advantage of load/save is the file is language agnostic.\n This means the file saved using save can be loaded by other language binding of mxnet.\n You also get the benefit being able to directly ... |
Please provide a description of the function:def load_json(json_str):
if not isinstance(json_str, string_types):
raise TypeError('fname required to be string')
handle = SymbolHandle()
check_call(_LIB.MXSymbolCreateFromJSON(c_str(json_str), ctypes.byref(handle)))
return Symbol(handle) | [
"Loads symbol from json string.\n\n Parameters\n ----------\n json_str : str\n A JSON string.\n\n Returns\n -------\n sym : Symbol\n The loaded symbol.\n\n See Also\n --------\n Symbol.tojson : Used to save symbol into json string.\n "
] |
Please provide a description of the function:def pow(base, exp):
if isinstance(base, Symbol) and isinstance(exp, Symbol):
return _internal._Power(base, exp)
if isinstance(base, Symbol) and isinstance(exp, Number):
return _internal._PowerScalar(base, scalar=exp)
if isinstance(base, Numbe... | [
"Returns element-wise result of base element raised to powers from exp element.\n\n Both inputs can be Symbol or scalar number.\n Broadcasting is not supported. Use `broadcast_pow` instead.\n\n `sym.pow` is being deprecated, please use `sym.power` instead.\n\n Parameters\n ---------\n base : Symbo... |
Please provide a description of the function:def maximum(left, right):
if isinstance(left, Symbol) and isinstance(right, Symbol):
return _internal._Maximum(left, right)
if isinstance(left, Symbol) and isinstance(right, Number):
return _internal._MaximumScalar(left, scalar=right)
if isin... | [
"Returns element-wise maximum of the input elements.\n\n Both inputs can be Symbol or scalar number. Broadcasting is not supported.\n\n Parameters\n ---------\n left : Symbol or scalar\n First symbol to be compared.\n right : Symbol or scalar\n Second symbol to be compared.\n\n Retur... |
Please provide a description of the function:def minimum(left, right):
if isinstance(left, Symbol) and isinstance(right, Symbol):
return _internal._Minimum(left, right)
if isinstance(left, Symbol) and isinstance(right, Number):
return _internal._MinimumScalar(left, scalar=right)
if isin... | [
"Returns element-wise minimum of the input elements.\n\n Both inputs can be Symbol or scalar number. Broadcasting is not supported.\n\n Parameters\n ---------\n left : Symbol or scalar\n First symbol to be compared.\n right : Symbol or scalar\n Second symbol to be compared.\n\n Retur... |
Please provide a description of the function:def hypot(left, right):
if isinstance(left, Symbol) and isinstance(right, Symbol):
return _internal._Hypot(left, right)
if isinstance(left, Symbol) and isinstance(right, Number):
return _internal._HypotScalar(left, scalar=right)
if isinstance... | [
"Given the \"legs\" of a right triangle, returns its hypotenuse.\n\n Equivalent to :math:`\\\\sqrt(left^2 + right^2)`, element-wise.\n Both inputs can be Symbol or scalar number. Broadcasting is not supported.\n\n Parameters\n ---------\n left : Symbol or scalar\n First leg of the triangle(s).... |
Please provide a description of the function:def eye(N, M=0, k=0, dtype=None, **kwargs):
if dtype is None:
dtype = _numpy.float32
return _internal._eye(N, M, k, dtype=dtype, **kwargs) | [
"Returns a new symbol of 2-D shpae, filled 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 ... |
Please provide a description of the function:def zeros(shape, dtype=None, **kwargs):
if dtype is None:
dtype = _numpy.float32
return _internal._zeros(shape=shape, dtype=dtype, **kwargs) | [
"Returns a new symbol of given shape and type, filled with zeros.\n\n Parameters\n ----------\n shape : int or sequence of ints\n Shape of the new array.\n dtype : str or numpy.dtype, optional\n The value type of the inner value, default to ``np.float32``.\n\n Returns\n -------\n ... |
Please provide a description of the function:def ones(shape, dtype=None, **kwargs):
if dtype is None:
dtype = _numpy.float32
return _internal._ones(shape=shape, dtype=dtype, **kwargs) | [
"Returns a new symbol of given shape and type, filled with ones.\n\n Parameters\n ----------\n shape : int or sequence of ints\n Shape of the new array.\n dtype : str or numpy.dtype, optional\n The value type of the inner value, default to ``np.float32``.\n\n Returns\n -------\n ... |
Please provide a description of the function:def full(shape, val, dtype=None, **kwargs):
if dtype is None:
dtype = _numpy.float32
return _internal._full(shape=shape, dtype=dtype, value=float(val), **kwargs) | [
"Returns a new array of given shape and type, filled with the given value `val`.\n\n Parameters\n ----------\n shape : int or sequence of ints\n Shape of the new array.\n val : scalar\n Fill value.\n dtype : str or numpy.dtype, optional\n The value type of the inner value, defau... |
Please provide a description of the function:def arange(start, stop=None, step=1.0, repeat=1, infer_range=False, name=None, dtype=None):
if dtype is None:
dtype = _numpy.float32
return _internal._arange(start=start, stop=stop, step=step, repeat=repeat,
infer_range=infer... | [
"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 a `... |
Please provide a description of the function:def histogram(a, bins=10, range=None, **kwargs):
if isinstance(bins, Symbol):
return _internal._histogram(data=a, bins=bins, **kwargs)
elif isinstance(bins, integer_types):
if range is None:
raise ValueError("null range is not support... | [
"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 = []
sections = 0
if isinstance(indices_or_sections, int):
sections = indices_or_sections
elif isinstance(indices_or_sections, tuple):
indices = [0] + list(indice... | [
"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 name(self):
ret = ctypes.c_char_p()
success = ctypes.c_int()
check_call(_LIB.MXSymbolGetName(
self.handle, ctypes.byref(ret), ctypes.byref(success)))
if success.value != 0:
return py_str(ret.value)
... | [
"Gets name string from the symbol, this function only works for non-grouped symbol.\n\n Returns\n -------\n value : str\n The name of this symbol, returns ``None`` for grouped symbol.\n "
] |
Please provide a description of the function:def attr(self, key):
ret = ctypes.c_char_p()
success = ctypes.c_int()
check_call(_LIB.MXSymbolGetAttr(
self.handle, c_str(key), ctypes.byref(ret), ctypes.byref(success)))
if success.value != 0:
return py_str(re... | [
"Returns the attribute string for corresponding input key from the symbol.\n\n This function only works for non-grouped symbols.\n\n Example\n -------\n >>> data = mx.sym.Variable('data', attr={'mood': 'angry'})\n >>> data.attr('mood')\n 'angry'\n\n Parameters\n ... |
Please provide a description of the function:def list_attr(self, recursive=False):
if recursive:
raise DeprecationWarning("Symbol.list_attr with recursive=True has been deprecated. "
"Please use attr_dict instead.")
size = mx_uint()
pairs... | [
"Gets all attributes from the symbol.\n\n Example\n -------\n >>> data = mx.sym.Variable('data', attr={'mood': 'angry'})\n >>> data.list_attr()\n {'mood': 'angry'}\n\n Returns\n -------\n ret : Dict of str to str\n A dictionary mapping attribute key... |
Please provide a description of the function:def attr_dict(self):
size = mx_uint()
pairs = ctypes.POINTER(ctypes.c_char_p)()
f_handle = _LIB.MXSymbolListAttr
check_call(f_handle(self.handle, ctypes.byref(size), ctypes.byref(pairs)))
ret = {}
for i in range(size.v... | [
"Recursively gets all attributes from the symbol and its children.\n\n Example\n -------\n >>> a = mx.sym.Variable('a', attr={'a1':'a2'})\n >>> b = mx.sym.Variable('b', attr={'b1':'b2'})\n >>> c = a+b\n >>> c.attr_dict()\n {'a': {'a1': 'a2'}, 'b': {'b1': 'b2'}}\n\n ... |
Please provide a description of the function:def _set_attr(self, **kwargs):
for key, value in kwargs.items():
if not isinstance(value, string_types):
raise ValueError("Set Attr only accepts string values")
check_call(_LIB.MXSymbolSetAttr(
self.han... | [
"Sets an attribute of the symbol.\n\n For example. A._set_attr(foo=\"bar\") adds the mapping ``\"{foo: bar}\"``\n to the symbol's attribute dictionary.\n\n Parameters\n ----------\n **kwargs\n The attributes to set\n "
] |
Please provide a description of the function:def get_internals(self):
handle = SymbolHandle()
check_call(_LIB.MXSymbolGetInternals(
self.handle, ctypes.byref(handle)))
return Symbol(handle=handle) | [
"Gets a new grouped symbol `sgroup`. The output of `sgroup` is a list of\n outputs of all of the internal nodes.\n\n Consider the following code:\n\n Example\n -------\n >>> a = mx.sym.var('a')\n >>> b = mx.sym.var('b')\n >>> c = a + b\n >>> d = c.get_internal... |
Please provide a description of the function:def get_children(self):
handle = SymbolHandle()
check_call(_LIB.MXSymbolGetChildren(
self.handle, ctypes.byref(handle)))
ret = Symbol(handle=handle)
if len(ret.list_outputs()) == 0:
return None
return r... | [
"Gets a new grouped symbol whose output contains\n inputs to output nodes of the original symbol.\n\n Example\n -------\n >>> x = mx.sym.Variable('x')\n >>> y = mx.sym.Variable('y')\n >>> z = mx.sym.Variable('z')\n >>> a = y+z\n >>> b = x+a\n >>> b.get_... |
Please provide a description of the function:def list_arguments(self):
size = ctypes.c_uint()
sarr = ctypes.POINTER(ctypes.c_char_p)()
check_call(_LIB.MXSymbolListArguments(
self.handle, ctypes.byref(size), ctypes.byref(sarr)))
return [py_str(sarr[i]) for i in range(... | [
"Lists all the arguments in the symbol.\n\n Example\n -------\n >>> a = mx.sym.var('a')\n >>> b = mx.sym.var('b')\n >>> c = a + b\n >>> c.list_arguments\n ['a', 'b']\n\n Returns\n -------\n args : list of string\n List containing the n... |
Please provide a description of the function:def list_outputs(self):
size = ctypes.c_uint()
sarr = ctypes.POINTER(ctypes.c_char_p)()
check_call(_LIB.MXSymbolListOutputs(
self.handle, ctypes.byref(size), ctypes.byref(sarr)))
return [py_str(sarr[i]) for i in range(size... | [
"Lists all the outputs in the symbol.\n\n Example\n -------\n >>> a = mx.sym.var('a')\n >>> b = mx.sym.var('b')\n >>> c = a + b\n >>> c.list_outputs()\n ['_plus12_output']\n\n Returns\n -------\n list of str\n List of all the outputs.\... |
Please provide a description of the function:def list_auxiliary_states(self):
size = ctypes.c_uint()
sarr = ctypes.POINTER(ctypes.c_char_p)()
check_call(_LIB.MXSymbolListAuxiliaryStates(
self.handle, ctypes.byref(size), ctypes.byref(sarr)))
return [py_str(sarr[i]) fo... | [
"Lists all the auxiliary states in the symbol.\n\n Example\n -------\n >>> a = mx.sym.var('a')\n >>> b = mx.sym.var('b')\n >>> c = a + b\n >>> c.list_auxiliary_states()\n []\n\n Example of auxiliary states in `BatchNorm`.\n\n >>> data = mx.symbol.Variab... |
Please provide a description of the function:def list_inputs(self):
size = ctypes.c_uint()
sarr = ctypes.POINTER(ctypes.c_char_p)()
check_call(_LIB.NNSymbolListInputNames(
self.handle, 0, ctypes.byref(size), ctypes.byref(sarr)))
return [py_str(sarr[i]) for i in range... | [
"Lists all arguments and auxiliary states of this Symbol.\n\n Returns\n -------\n inputs : list of str\n List of all inputs.\n\n Examples\n --------\n >>> bn = mx.sym.BatchNorm(name='bn')\n >>> bn.list_arguments()\n ['bn_data', 'bn_gamma', 'bn_beta'... |
Please provide a description of the function:def infer_type(self, *args, **kwargs):
try:
res = self._infer_type_impl(False, *args, **kwargs)
if res[1] is None:
arg_shapes, _, _ = self._infer_type_impl(True, *args, **kwargs)
arg_names = self.list_a... | [
"Infers the type of all arguments and all outputs, given the known types\n for some arguments.\n\n This function takes the known types of some arguments in either positional way\n or keyword argument way as input. It returns a tuple of `None` values\n if there is not enough information t... |
Please provide a description of the function:def _infer_type_impl(self, partial, *args, **kwargs):
# pylint: disable=too-many-locals
if len(args) != 0 and len(kwargs) != 0:
raise ValueError('Can only specify known argument \
types either by positional or kwargs w... | [
"The actual implementation for calling type inference API."
] |
Please provide a description of the function:def infer_shape(self, *args, **kwargs):
try:
res = self._infer_shape_impl(False, *args, **kwargs)
if res[1] is None:
arg_shapes, _, _ = self._infer_shape_impl(True, *args, **kwargs)
arg_names = self.lis... | [
"Infers the shapes of all arguments and all outputs given the known shapes of\n some arguments.\n\n This function takes the known shapes of some arguments in either positional way\n or keyword argument way as input. It returns a tuple of `None` values\n if there is not enough information... |
Please provide a description of the function:def _infer_shape_impl(self, partial, *args, **kwargs):
# pylint: disable=too-many-locals
if len(args) != 0 and len(kwargs) != 0:
raise ValueError('Can only specify known argument \
shapes either by positional or kwargs... | [
"The actual implementation for calling shape inference API."
] |
Please provide a description of the function:def save(self, fname):
if not isinstance(fname, string_types):
raise TypeError('fname need to be string')
check_call(_LIB.MXSymbolSaveToFile(self.handle, c_str(fname))) | [
"Saves symbol to a file.\n\n You can also use pickle to do the job if you only work on python.\n The advantage of `load`/`save` functions is that the file contents are language agnostic.\n This means the model saved by one language binding can be loaded by a different\n language binding ... |
Please provide a description of the function:def tojson(self):
json_str = ctypes.c_char_p()
check_call(_LIB.MXSymbolSaveToJSON(self.handle, ctypes.byref(json_str)))
return py_str(json_str.value) | [
"Saves symbol to a JSON string.\n\n See Also\n --------\n symbol.load_json : Used to load symbol from JSON string.\n "
] |
Please provide a description of the function:def _get_ndarray_inputs(arg_key, args, arg_names, allow_missing):
# setup args
arg_handles = []
arg_arrays = []
if isinstance(args, list):
if len(args) != len(arg_names):
raise ValueError('Length of %s does... | [
"Helper function to get NDArray lists handles from various inputs.\n\n Parameters\n ----------\n arg_key : str\n The name of argument, used for error message.\n\n args : list of NDArray or dict of str to NDArray\n Input arguments to the symbols.\n If type... |
Please provide a description of the function:def simple_bind(self, ctx, grad_req='write', type_dict=None, stype_dict=None,
group2ctx=None, shared_arg_names=None, shared_exec=None,
shared_buffer=None, **kwargs):
# data types
num_provided_arg_types = 0
... | [
"Bind current symbol to get an executor, allocate all the arguments needed.\n Allows specifying data types.\n\n This function simplifies the binding procedure. You need to specify only input data shapes.\n Before binding the executor, the function allocates arguments and auxiliary states\n ... |
Please provide a description of the function:def bind(self, ctx, args, args_grad=None, grad_req='write',
aux_states=None, group2ctx=None, shared_exec=None):
# pylint: disable=too-many-locals, too-many-branches
if not isinstance(ctx, Context):
raise TypeError("Context ty... | [
"Binds the current symbol to an executor and returns it.\n\n We first declare the computation and then bind to the data to run.\n This function returns an executor which provides method `forward()` method for evaluation\n and a `outputs()` method to get all the results.\n\n Example\n ... |
Please provide a description of the function:def gradient(self, wrt):
handle = SymbolHandle()
c_wrt = c_str_array(wrt)
check_call(_LIB.MXSymbolGrad(self.handle,
mx_uint(len(wrt)),
c_wrt,
... | [
"Gets the autodiff of current symbol.\n\n This function can only be used if current symbol is a loss function.\n\n .. note:: This function is currently not implemented.\n\n Parameters\n ----------\n wrt : Array of String\n keyword arguments of the symbol that the gradie... |
Please provide a description of the function:def eval(self, ctx=None, **kwargs):
if ctx is None:
ctx = current_context()
return self.bind(ctx, kwargs).forward() | [
"Evaluates a symbol given arguments.\n\n The `eval` method combines a call to `bind` (which returns an executor)\n with a call to `forward` (executor method).\n For the common use case, where you might repeatedly evaluate with same arguments,\n eval is slow.\n In that case, you sh... |
Please provide a description of the function:def get_backend_symbol(self, backend):
out = SymbolHandle()
check_call(_LIB.MXGenBackendSubgraph(self.handle, c_str(backend), ctypes.byref(out)))
return Symbol(out) | [
"Return symbol for target backend.\n\n Parameters\n ----------\n backend : str\n The backend names.\n\n Returns\n -------\n out : Symbol\n The created Symbol for target backend.\n "
] |
Please provide a description of the function:def hybrid_forward(self, F, x):
f = self._factor
# (N, C*f, W)
x = F.reshape(x, (0, -4, -1, f, 0)) # (N, C, f, W)
x = F.transpose(x, (0, 1, 3, 2)) # (N, C, W, f)
x = F.reshape(x, (0, 0... | [
"Perform pixel-shuffling on the input."
] |
Please provide a description of the function:def hybrid_forward(self, F, x):
f1, f2 = self._factors
# (N, f1*f2*C, H, W)
x = F.reshape(x, (0, -4, -1, f1 * f2, 0, 0)) # (N, C, f1*f2, H, W)
x = F.reshape(x, (0, 0, -4, f1, f2, 0, 0)) ... | [
"Perform pixel-shuffling on the input."
] |
Please provide a description of the function:def hybrid_forward(self, F, x):
# `transpose` doesn't support 8D, need other implementation
f1, f2, f3 = self._factors
# (N, C*f1*f2*f3, D, H, W)
x = F.reshape(x, (0, -4, -1, f1 * ... | [
"Perform pixel-shuffling on the input."
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.