text
stringlengths
81
112k
Prints the C representation of this AF. def print(self): """Prints the C representation of this AF.""" cond_var = None if self.supported: cond_var = conditional_var('{}{}'.format(self.func, self.fn_num)) print_conditional_if(cond_var) print(' AF', end='') ...
Parses a string and returns a (port, gpio_bit) tuple. def parse_port_pin(name_str): """Parses a string and returns a (port, gpio_bit) tuple.""" if len(name_str) < 3: raise ValueError("Expecting pin name to be at least 3 characters") if name_str[:2] != 'GP': raise ValueError("Expecting pin n...
Simple run one operator and return the results. Args: outputs_info: a list of tuples, which contains the element type and shape of each output. First element of the tuple is the dtype, and the second element is the shape. More use case can be found in https://gith...
Load data from an external file for tensor. @params tensor: a TensorProto object. base_dir: directory that contains the external data. def load_external_data_for_tensor(tensor, base_dir): # type: (TensorProto, Text) -> None """ Load data from an external file for tensor. @params tensor: ...
Loads external tensors into model @params model: ModelProto to load external data to base_dir: directory that contains external data def load_external_data_for_model(model, base_dir): # type: (ModelProto, Text) -> None """ Loads external tensors into model @params model: ModelProto to lo...
call to set all tensors as external data. save_model saves all the tensors data as external data after calling this function. @params model: ModelProto to be converted. all_tensors_to_one_file: If true, save all tensors to one external file specified by location. If false, save ...
call to set all tensors data as embedded data. save_model saves all the tensors data as embedded data after calling this function. @params model: ModelProto to be converted. def convert_model_from_external_data(model): # type: (ModelProto) -> None """ call to set all tensors data as embedded data. sav...
Write tensor data to an external file according to information in the `external_data` field. @params tensor: Tensor object to be serialized base_path: System path of a folder where tensor data is to be stored def save_external_data(tensor, base_path): # type: (TensorProto, Text) -> None """ Write...
Create an iterator of tensors from node attributes of an ONNX model. def _get_attribute_tensors(onnx_model_proto): # type: (ModelProto) -> Iterable[TensorProto] """Create an iterator of tensors from node attributes of an ONNX model.""" for node in onnx_model_proto.graph.node: for attribute in node.att...
Remove a field from a Tensor's external_data key-value store. Modifies tensor object in place. @params tensor: Tensor object from which value will be removed field_key: The key of the field to be removed def remove_external_data_field(tensor, field_key): # type: (TensorProto, Text) -> None """ ...
Write external data of all tensors to files on disk. Note: This function also strips basepath information from all tensors' external_data fields. @params model: Model object which is the source of tensors to serialize. filepath: System path to the directory which should be treated as base path for ext...
Imports a stdlib path and returns a handle to it eg. self._import("typing", "Optional") -> "Optional" def _import(self, path, name): # type: (Text, Text) -> Text """Imports a stdlib path and returns a handle to it eg. self._import("typing", "Optional") -> "Optional" """ ...
Import a referenced message and return a handle def _import_message(self, type_name): # type: (d.FieldDescriptorProto) -> Text """Import a referenced message and return a handle""" name = cast(Text, type_name) if name[0] == '.' and name[1].isupper() and name[2].islower(): #...
Run command. def run(self): """Run command.""" onnx_script = os.path.realpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), "tools/mypy-onnx.py")) returncode = subprocess.call([sys.executable, onnx_script]) sys.exit(returncode)
Construct a NodeProto. Arguments: op_type (string): The name of the operator to construct inputs (list of string): list of input names outputs (list of string): list of output names name (string, default None): optional unique identifier for NodeProto doc_string (string, def...
Construct an OperatorSetIdProto. Arguments: domain (string): The domain of the operator set id version (integer): Version of operator set id def make_operatorsetid( domain, # type: Text version, # type: int ): # type: (...) -> OperatorSetIdProto """Construct an OperatorSetId...
An internal graph to convert the input to a bytes or to False. The criteria for conversion is as follows and should be python 2 and 3 compatible: - If val is py2 str or py3 bytes: return bytes - If val is py2 unicode or py3 str: return val.decode('utf-8') - Otherwise, return False def _to_bytes_or...
Makes an AttributeProto based on the value type. def make_attribute( key, # type: Text value, # type: Any doc_string=None # type: Optional[Text] ): # type: (...) -> AttributeProto """Makes an AttributeProto based on the value type.""" attr = AttributeProto() attr.name = key ...
Makes a ValueInfoProto based on the data type and shape. def make_tensor_value_info( name, # type: Text elem_type, # type: int shape, # type: Optional[Sequence[Union[Text, int]]] doc_string="", # type: Text shape_denotation=None, # type: Optional[List[Text]] ): # type: (.....
Empties `doc_string` field on any nested protobuf messages def strip_doc_string(proto): # type: (google.protobuf.message.Message) -> None """ Empties `doc_string` field on any nested protobuf messages """ assert isinstance(proto, google.protobuf.message.Message) for descriptor in proto.DESCRIPTOR....
Converts a tensor def object to a numpy array. Inputs: tensor: a TensorProto object. Returns: arr: the converted array. def to_array(tensor): # type: (TensorProto) -> np.ndarray[Any] """Converts a tensor def object to a numpy array. Inputs: tensor: a TensorProto object. R...
Converts a numpy array to a tensor def. Inputs: arr: a numpy array. name: (optional) the name of the tensor. Returns: tensor_def: the converted tensor def. def from_array(arr, name=None): # type: (np.ndarray[Any], Optional[Text]) -> TensorProto """Converts a numpy array to a tenso...
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 def _serialize(proto): # type: (Union[bytes, google.protobuf.message.Message]) -> bytes ''' Serialize a in-memory proto to bytes @params ...
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 def _deserialize(s, proto): # type: (bytes, _Proto) -> _Proto ''' Parse bytes into a in-memory proto @params s is bytes c...
Loads a serialized ModelProto into memory @params f can be a file-like object (has "read" function) or a string containing a file name format is for future use @return Loaded in-memory ModelProto def load_model(f, format=None, load_external_data=True): # type: (Union[IO[bytes], Text], Optional[A...
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 future use @return Loaded in-memory TensorProto def load_tensor(f, format=None): # type: (Union[IO[bytes], Text], Optional[Any]) -> TensorProto ...
Saves the ModelProto to the specified path. @params proto should be a in-memory ModelProto f can be a file-like object (has "write" function) or a string containing a file name format is for future use def save_model(proto, f, format=None): # type: (Union[ModelProto, bytes], Union[IO[bytes], Text], O...
This function combines several useful utility functions together. 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_inf...
Unrolls an RNN cell across time steps. Currently, 'TNC' is a preferred layout. unroll on the input of this layout runs much faster. Parameters ---------- cell : an object whose base class is RNNCell. The RNN cell to run on the input sequence. inputs : Symbol It should have shap...
Unrolls an RNN cell across time steps. Parameters ---------- length : int Number of steps to unroll. inputs : Symbol, list of Symbol, or None If `inputs` is a single Symbol (usually the output of Embedding symbol), it should have shape (ba...
Change attribute names as per values in change_map dictionary. Parameters ---------- :param attrs : dict Dict of operator attributes :param change_map : dict Dict of onnx attribute name to mxnet attribute names. Returns ------- :return new_attr : dict Converted dict of operator attributes. ...
Removes attributes in the remove list from the input attribute dict :param attrs : Dict of operator attributes :param remove_list : list of attributes to be removed :return new_attr : Dict of operator attributes without the listed attributes. def _remove_attributes(attrs, remove_list): """ Removes...
:param attrs: Current Attribute list :param extraAttrMap: Additional attributes to be added :return: new_attr def _add_extra_attributes(attrs, extra_attr_map): """ :param attrs: Current Attribute list :param extraAttrMap: Additional attributes to be added :return: new_attr """ for a...
Changing onnx's pads sequence to match with mxnet's pad_width mxnet: (x1_begin, x1_end, ... , xn_begin, xn_end) onnx: (x1_begin, x2_begin, ... , xn_end, xn_end) def _pad_sequence_fix(attr, kernel_dim=None): """Changing onnx's pads sequence to match with mxnet's pad_width mxnet: (x1_begin, x1_end, ... ,...
onnx pooling operator supports asymmetrical padding Adding pad operator before pooling in mxnet to work with onnx def _fix_pooling(pool_type, inputs, new_attr): """onnx pooling operator supports asymmetrical padding Adding pad operator before pooling in mxnet to work with onnx""" stride = new_attr.get(...
A workaround for 'use_bias' attribute since onnx don't provide this attribute, we have to check the number of inputs to decide it. def _fix_bias(op_name, attrs, num_inputs): """A workaround for 'use_bias' attribute since onnx don't provide this attribute, we have to check the number of inputs to decide it....
A workaround to reshape bias term to (1, num_channel). def _fix_broadcast(op_name, inputs, broadcast_axis, proto_obj): """A workaround to reshape bias term to (1, num_channel).""" if int(len(proto_obj._params)) > 0: assert len(list(inputs)) == 2 input0_shape = get_input_shape(inputs[0], proto_...
A workaround for getting 'channels' or 'units' since onnx don't provide these attributes. We check the shape of weights provided to get the number. def _fix_channels(op_name, attrs, inputs, proto_obj): """A workaround for getting 'channels' or 'units' since onnx don't provide these attributes. We check the...
Using FullyConnected operator in place of linalg_gemm to perform same operation def _fix_gemm(op_name, inputs, old_attr, proto_obj): """Using FullyConnected operator in place of linalg_gemm to perform same operation""" op_sym = getattr(symbol, op_name, None) alpha = float(old_attr.get('alpha', 1.0)) be...
Helper function to obtain the shape of an array def get_input_shape(sym, proto_obj): """Helper function to obtain the shape of an array""" 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')] da...
r"""Resize image with OpenCV. .. note:: `imresize` uses OpenCV (not the CV2 Python library). MXNet must have been built with USE_OPENCV=1 for `imresize` to work. Parameters ---------- src : NDArray source image w : int, required Width of resized image. h : int, required ...
Decode an image to an NDArray. .. note:: `imdecode` uses OpenCV (not the CV2 Python library). MXNet must have been built with USE_OPENCV=1 for `imdecode` to work. Parameters ---------- buf : str/bytes/bytearray or numpy.ndarray Binary image data as string or numpy ndarray. flag : in...
Scales down crop size if it's larger than image size. If width/height of the crop is larger than the width/height of the image, sets the width/height to the width/height of the image. Parameters ---------- src_size : tuple of int Size of the image in (width, height) format. size : tupl...
Pad image border with OpenCV. Parameters ---------- src : NDArray source image top : int, required Top margin. bot : int, required Bottom margin. left : int, required Left margin. right : int, required Right margin. type : int, optional, default='...
Get the interpolation method for resize functions. The major purpose of this function is to wrap a random interp method selection and a auto-estimation method. Parameters ---------- interp : int interpolation method for all resizing operations Possible values: 0: Nearest Ne...
Resizes shorter edge to size. .. note:: `resize_short` uses OpenCV (not the CV2 Python library). MXNet must have been built with OpenCV for `resize_short` to work. Resizes the original image by setting the shorter edge to size and setting the longer edge accordingly. Resizing function is called...
Crop src at fixed location, and (optionally) resize it to size. Parameters ---------- src : NDArray Input image x0 : int Left boundary of the cropping area y0 : int Top boundary of the cropping area w : int Width of the cropping area h : int Height of...
Crops the image `src` to the given `size` by trimming on all four sides and preserving the center of the image. Upsamples if `src` is smaller than `size`. .. note:: This requires MXNet to be compiled with USE_OPENCV. Parameters ---------- src : NDArray Binary source image data. siz...
Normalize src with mean and std. Parameters ---------- src : NDArray Input image mean : NDArray RGB mean to be subtracted std : NDArray RGB standard deviation to be divided Returns ------- NDArray An `NDArray` containing the normalized image. def color_...
Randomly crop src with size. Randomize area and aspect ratio. Parameters ---------- src : NDArray Input image size : tuple of (int, int) Size of the crop formatted as (width, height). area : float in (0, 1] or tuple of (float, float) If tuple, minimum area and maximum area t...
Creates an augmenter list. Parameters ---------- data_shape : tuple of int Shape for output data resize : int Resize shorter edge if larger than 0 at the begining rand_crop : bool Whether to enable random cropping other than center crop rand_resize : bool Whether...
Saves the Augmenter to string Returns ------- str JSON formatted string that describes the Augmenter. def dumps(self): """Saves the Augmenter to string Returns ------- str JSON formatted string that describes the Augmenter. """ ...
Override the default to avoid duplicate dump. def dumps(self): """Override the default to avoid duplicate dump.""" return [self.__class__.__name__.lower(), [x.dumps() for x in self.ts]]
Resets the iterator to the beginning of the data. def reset(self): """Resets the iterator to the beginning of the data.""" 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: ...
Resets the iterator and ignore roll over data def hard_reset(self): """Resets the iterator and ignore roll over data""" 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._a...
Helper function for reading in next sample. def next_sample(self): """Helper function for reading in next sample.""" 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] ...
Helper function for batchifying data def _batchify(self, batch_data, batch_label, start=0): """Helper function for batchifying data""" i = start batch_size = self.batch_size try: while i < batch_size: label, s = self.next_sample() data = self....
Decodes a string or byte string to an NDArray. See mx.img.imdecode for more details. def imdecode(self, s): """Decodes a string or byte string to an NDArray. See mx.img.imdecode for more details.""" def locate(): """Locate the image file/index if decode fails.""" ...
Reads an input image `fname` and returns the decoded raw bytes. Examples -------- >>> dataIter.read_image('Face.jpg') # returns decoded raw bytes. def read_image(self, fname): """Reads an input image `fname` and returns the decoded raw bytes. Examples -------- >>...
evaluate accuracy def facc(label, pred): """ evaluate accuracy """ pred = pred.ravel() label = label.ravel() return ((pred > 0.5) == label).mean()
Convert character vectors to integer vectors. def word_to_vector(word): """ Convert character vectors to integer vectors. """ vector = [] for char in list(word): vector.append(char2int(char)) return vector
Convert integer vectors to character vectors. def vector_to_word(vector): """ Convert integer vectors to character vectors. """ word = "" for vec in vector: word = word + int2char(vec) return word
Convert integer vectors to character vectors for batch. def char_conv(out): """ Convert integer vectors to character vectors for batch. """ 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: ...
Add a pooling layer to the model. This is our own implementation of add_pooling since current CoreML's version (0.5.0) of builder doesn't provide support for padding types apart from valid. This support will be added in the next release of coremltools. When that happens, this can be removed. Par...
Get path to all the frame in view SAX and contain complete frames def get_frames(root_path): """Get path to all the frame in view SAX and contain complete frames""" ret = [] for root, _, files in os.walk(root_path): root=root.replace('\\','/') files=[s for s in files if ".dcm" in s] if le...
Write data to csv file def write_data_csv(fname, frames, preproc): """Write data to csv file""" 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...
crop center and resize def crop_resize(img, size): """crop center and resize""" 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 ...
construct and return generator def get_generator(): """ construct and return 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...
construct and return descriptor def get_descriptor(ctx): """ construct and return descriptor """ 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)) ...
spectral normalization def _spectral_norm(self): """ spectral normalization """ 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.L2Normalizatio...
Compute the length of the output sequence after 1D convolution along time. Note that this function is in line with the function used in Convolution1D class from Keras. Params: input_length (int): Length of the input sequence. filter_size (int): Width of the convolution kernel. ...
Compute the spectrogram for a real signal. The parameters follow the naming convention of matplotlib.mlab.specgram Args: samples (1D array): input audio signal fft_length (int): number of elements in fft window sample_rate (scalar): sample rate hop_length (int): hop length (r...
Calculate the log of linear spectrogram from FFT energy Params: filename (str): Path to the audio file step (int): Step size in milliseconds between windows window (int): FFT window size in milliseconds max_freq (int): Only FFT bins corresponding to frequencies between [0...
generate random cropping boxes according to parameters if satifactory crops generated, apply to ground-truth as well Parameters: ---------- label : numpy.array (n x 5 matrix) ground-truths Returns: ---------- list of (crop_box, label) tuples, if fail...
check if overlap with any gt box is larger than threshold def _check_satisfy(self, rand_box, gt_boxes): """ check if overlap with any gt box is larger than threshold """ l, t, r, b = rand_box num_gt = gt_boxes.shape[0] ls = np.ones(num_gt) * l ts = np.ones(num_gt...
generate random padding boxes according to parameters if satifactory padding generated, apply to ground-truth as well Parameters: ---------- label : numpy.array (n x 5 matrix) ground-truths Returns: ---------- list of (crop_box, label) tuples, if fai...
Measure time cost of running a function def measure_cost(repeat, scipy_trans_lhs, scipy_dns_lhs, func_name, *args, **kwargs): """Measure time cost of running a function """ mx.nd.waitall() args_list = [] for arg in args: args_list.append(arg) start = time.time() if scipy_trans_lhs: ...
Print information about the annotation file. :return: def info(self): """ Print information about the annotation file. :return: """ for key, value in self.dataset['info'].items(): print('{}: {}'.format(key, value))
filtering parameters. default skips that filter. :param catNms (str array) : get cats for given cat names :param supNms (str array) : get cats for given supercategory names :param catIds (int array) : get cats for given cat ids :return: ids (int array) : integer array of cat ids de...
Load anns with the specified ids. :param ids (int array) : integer ids specifying anns :return: anns (object array) : loaded ann objects def loadAnns(self, ids=[]): """ Load anns with the specified ids. :param ids (int array) : integer ids specifying anns :re...
Load cats with the specified ids. :param ids (int array) : integer ids specifying cats :return: cats (object array) : loaded cat objects def loadCats(self, ids=[]): """ Load cats with the specified ids. :param ids (int array) : integer ids specifying cats :re...
Load anns with the specified ids. :param ids (int array) : integer ids specifying img :return: imgs (object array) : loaded img objects def loadImgs(self, ids=[]): """ Load anns with the specified ids. :param ids (int array) : integer ids specifying img :retu...
Display the specified annotations. :param anns (array of object): annotations to display :return: None def showAnns(self, anns): """ Display the specified annotations. :param anns (array of object): annotations to display :return: None """ if len(anns) ==...
Download COCO images from mscoco.org server. :param tarDir (str): COCO results directory name imgIds (list): images to be downloaded :return: def download(self, tarDir = None, imgIds = [] ): ''' Download COCO images from mscoco.org server. :param tarDir (str): COC...
Convert result data from a numpy array [Nx7] where each row contains {imageID,x1,y1,w,h,score,class} :param data (numpy.ndarray) :return: annotations (python nested list) def loadNumpyAnnotations(self, data): """ Convert result data from a numpy array [Nx7] where each row contains {ima...
Convert annotation which can be polygons, uncompressed RLE to RLE. :return: binary mask (numpy 2D array) def annToRLE(self, ann): """ Convert annotation which can be polygons, uncompressed RLE to RLE. :return: binary mask (numpy 2D array) """ t = self.imgs[ann['image_id'...
Save cnn model Returns ---------- callback: A callback function that can be passed as epoch_end_callback to fit def save_model(): """Save cnn model Returns ---------- callback: A callback function that can be passed as epoch_end_callback to fit """ if not os.path.exists("checkpoint"...
Construct highway net Parameters ---------- data: Returns ---------- Highway Networks def highway(data): """Construct highway net Parameters ---------- data: Returns ---------- Highway Networks """ _data = data high_weight = mx.sym.Variable('high_weight')...
Train cnn model Parameters ---------- symbol_data: symbol train_iterator: DataIter Train DataIter valid_iterator: DataIter Valid DataIter data_column_names: list of str Defaults to ('data') for a typical model used in image classific...
Collate data into batch. def default_batchify_fn(data): """Collate data into batch.""" 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...
Collate data into batch. Use shared memory for stacking. def default_mp_batchify_fn(data): """Collate data into batch. Use shared memory for stacking.""" if isinstance(data[0], nd.NDArray): out = nd.empty((len(data),) + data[0].shape, dtype=data[0].dtype, ctx=context.Context('cpu...
Move data into new context. def _as_in_context(data, ctx): """Move data into new context.""" 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
Worker loop for multiprocessing DataLoader. def worker_loop_v1(dataset, key_queue, data_queue, batchify_fn): """Worker loop for multiprocessing DataLoader.""" while True: idx, samples = key_queue.get() if idx is None: break batch = batchify_fn([dataset[i] for i in samples]) ...
Fetcher loop for fetching data from queue and put in reorder dict. def fetcher_loop_v1(data_queue, data_buffer, pin_memory=False, pin_device_id=0, data_buffer_lock=None): """Fetcher loop for fetching data from queue and put in reorder dict.""" while True: idx, batch = data_queue.get...
Function for processing data in worker process. def _worker_fn(samples, batchify_fn, dataset=None): """Function for processing data in worker process.""" # pylint: disable=unused-argument # it is required that each worker process has to fork a new MXIndexedRecordIO handle # preserving dataset as global...
Send object def send(self, obj): """Send object""" buf = io.BytesIO() ForkingPickler(buf, pickle.HIGHEST_PROTOCOL).dump(obj) self.send_bytes(buf.getvalue())
Assign next batch workload to workers. def _push_next(self): """Assign next batch workload to workers.""" r = next(self._iter, None) if r is None: return self._key_queue.put((self._sent_idx, r)) self._sent_idx += 1
Shutdown internal workers by pushing terminate signals. def shutdown(self): """Shutdown internal workers by pushing terminate signals.""" if not self._shutdown: # send shutdown signal to the fetcher and join data queue first # Remark: loop_fetcher need to be joined prior to th...
Assign next batch workload to workers. def _push_next(self): """Assign next batch workload to workers.""" 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)) se...
Returns ctype arrays for the key-value args, and the whether string keys are used. For internal use only. def _ctype_key_value(keys, vals): """ Returns ctype arrays for the key-value args, and the whether string keys are used. For internal use only. """ if isinstance(keys, (tuple, list)): ...