text
stringlengths
81
112k
Extract numpy array from single column data table def _maybe_dt_array(array): """ Extract numpy array from single column data table """ if not isinstance(array, DataTable) or array is None: return array if array.shape[1] > 1: raise ValueError('DataTable for label or weight cannot have mult...
Initialize data from a CSR matrix. def _init_from_csr(self, csr): """ Initialize data from a CSR matrix. """ if len(csr.indices) != len(csr.data): raise ValueError('length mismatch: {} vs {}'.format(len(csr.indices), len(csr.data))) handle = ctypes.c_void_p() ...
Initialize data from a CSC matrix. def _init_from_csc(self, csc): """ Initialize data from a CSC matrix. """ if len(csc.indices) != len(csc.data): raise ValueError('length mismatch: {} vs {}'.format(len(csc.indices), len(csc.data))) handle = ctypes.c_void_p() ...
Initialize data from a 2-D numpy matrix. If ``mat`` does not have ``order='C'`` (aka row-major) or is not contiguous, a temporary copy will be made. If ``mat`` does not have ``dtype=numpy.float32``, a temporary copy will be made. So there could be as many as two temporary data copies;...
Initialize data from a datatable Frame. def _init_from_dt(self, data, nthread): """ Initialize data from a datatable Frame. """ ptrs = (ctypes.c_void_p * data.ncols)() if hasattr(data, "internal") and hasattr(data.internal, "column"): # datatable>0.8.0 fo...
Set float type property into the DMatrix. Parameters ---------- field: str The field name of the information data: numpy array The array of data to be set def set_float_info(self, field, data): """Set float type property into the DMatrix. Param...
Set float type property into the DMatrix for numpy 2d array input Parameters ---------- field: str The field name of the information data: numpy array The array of data to be set def set_float_info_npy2d(self, field, data): """Set float type ...
Set uint type property into the DMatrix. Parameters ---------- field: str The field name of the information data: numpy array The array of data to be set def set_uint_info(self, field, data): """Set uint type property into the DMatrix. Paramete...
Save DMatrix to an XGBoost buffer. Saved binary can be later loaded by providing the path to :py:func:`xgboost.DMatrix` as input. Parameters ---------- fname : string Name of the output buffer file. silent : bool (optional; default: True) If set, the out...
Set group size of DMatrix (used for ranking). Parameters ---------- group : array like Group size of each group def set_group(self, group): """Set group size of DMatrix (used for ranking). Parameters ---------- group : array like Group s...
Get feature names (column labels). Returns ------- feature_names : list or None def feature_names(self): """Get feature names (column labels). Returns ------- feature_names : list or None """ if self._feature_names is None: self._fea...
Set feature names (column labels). Parameters ---------- feature_names : list or None Labels for features. None will reset existing feature names def feature_names(self, feature_names): """Set feature names (column labels). Parameters ---------- fea...
Set feature types (column types). This is for displaying the results and unrelated to the learning process. Parameters ---------- feature_types : list or None Labels for features. None will reset existing feature names def feature_types(self, feature_types): ...
Initialize the model by load from rabit checkpoint. Returns ------- version: integer The version number of the model. def load_rabit_checkpoint(self): """Initialize the model by load from rabit checkpoint. Returns ------- version: integer ...
Get attribute string from the Booster. Parameters ---------- key : str The key to get attribute from. Returns ------- value : str The attribute value of the key, returns None if attribute do not exist. def attr(self, key): """Get attribu...
Get attributes stored in the Booster as a dictionary. Returns ------- result : dictionary of attribute_name: attribute_value pairs of strings. Returns an empty dict if there's no attributes. def attributes(self): """Get attributes stored in the Booster as a dictionary. ...
Set the attribute of the Booster. Parameters ---------- **kwargs The attributes to set. Setting a value to None deletes an attribute. def set_attr(self, **kwargs): """Set the attribute of the Booster. Parameters ---------- **kwargs The a...
Set parameters into the Booster. Parameters ---------- params: dict/list/str list of key,value pairs, dict of key to value or simply str key value: optional value of the specified parameter, when params is str key def set_param(self, params, value=None): "...
Evaluate the model on mat. Parameters ---------- data : DMatrix The dmatrix storing the input. name : str, optional The name of the dataset. iteration : int, optional The current iteration number. Returns ------- res...
Predict with data. .. note:: This function is not thread safe. For each booster object, predict can only be called from one thread. If you want to run prediction using multiple thread, call ``bst.copy()`` to make copies of model object and then call ``predict()``. .. not...
Save the model to a file. The model is saved in an XGBoost internal binary format which is universal among the various XGBoost interfaces. Auxiliary attributes of the Python Booster object (such as feature_names) will not be saved. To preserve all attributes, pickle the Booster object. ...
Load the model from a file. The model is loaded from an XGBoost internal binary format which is universal among the various XGBoost interfaces. Auxiliary attributes of the Python Booster object (such as feature_names) will not be loaded. To preserve all attributes, pickle the Booster ob...
Dump model into a text or JSON file. Parameters ---------- fout : string Output file name. fmap : string, optional Name of the file containing feature map names. with_stats : bool, optional Controls whether the split statistics are output. ...
Returns the model dump as a list of strings. Parameters ---------- fmap : string, optional Name of the file containing feature map names. with_stats : bool, optional Controls whether the split statistics are output. dump_format : string, optional ...
Get feature importance of each feature. Importance type can be defined as: * 'weight': the number of times a feature is used to split the data across all trees. * 'gain': the average gain across all splits the feature is used in. * 'cover': the average coverage across all splits the fea...
Parse a boosted tree model text dump into a pandas DataFrame structure. This feature is only defined when the decision tree model is chosen as base learner (`booster in {gbtree, dart}`). It is not defined for other base learner types, such as linear learners (`booster=gblinear`). Param...
Validate Booster and data's feature_names are identical. Set feature_names and feature_types from DMatrix def _validate_features(self, data): """ Validate Booster and data's feature_names are identical. Set feature_names and feature_types from DMatrix """ if self.feature...
Get split value histogram of a feature Parameters ---------- feature: str The name of the feature. fmap: str (optional) The name of feature map file. bin: int, default None The maximum number of bins. Number of bins equals number o...
Plot importance based on fitted trees. Parameters ---------- booster : Booster, XGBModel or dict Booster or XGBModel instance, or dict taken by Booster.get_fscore() ax : matplotlib Axes, default None Target axes instance. If None, new figure and axes will be created. grid : bool, Tu...
parse dumped node def _parse_node(graph, text, condition_node_params, leaf_node_params): """parse dumped node""" match = _NODEPAT.match(text) if match is not None: node = match.group(1) graph.node(node, label=match.group(2), **condition_node_params) return node match = _LEAFPAT....
parse dumped edge def _parse_edge(graph, node, text, yes_color='#0000FF', no_color='#FF0000'): """parse dumped edge""" try: match = _EDGEPAT.match(text) if match is not None: yes, no, missing = match.groups() if yes == missing: graph.edge(node, yes, label...
Convert specified tree to graphviz instance. IPython can automatically plot the returned graphiz instance. Otherwise, you should call .render() method of the returned graphiz instance. Parameters ---------- booster : Booster, XGBModel Booster or XGBModel instance fmap: str (optional) ...
Create a new action and assign callbacks, shortcuts, etc. def newAction(parent, text, slot=None, shortcut=None, icon=None, tip=None, checkable=False, enabled=True): """Create a new action and assign callbacks, shortcuts, etc.""" a = QAction(text, parent) if icon is not None: a.setIcon...
Sort the list into natural alphanumeric order. def natural_sort(list, key=lambda s:s): """ Sort the list into natural alphanumeric order. """ def get_alphanum_key_func(key): convert = lambda text: int(text) if text.isdigit() else text return lambda s: [convert(c) for c in re.split('([0-...
Update line with last point and current coordinates. def mouseMoveEvent(self, ev): """Update line with last point and current coordinates.""" pos = self.transformPos(ev.pos()) # Update coordinates in status bar if image is opened window = self.parent().window() if window.filePa...
Select the first shape created which contains this point. def selectShapePoint(self, point): """Select the first shape created which contains this point.""" self.deSelectShape() if self.selectedVertex(): # A vertex is marked for selection. index, shape = self.hVertex, self.hShape ...
Moves a point x,y to within the boundaries of the canvas. :return: (x,y,snapped) where snapped is True if x or y were changed, False if not. def snapPointToCanvas(self, x, y): """ Moves a point x,y to within the boundaries of the canvas. :return: (x,y,snapped) where snapped is True if x...
For each edge formed by `points', yield the intersection with the line segment `(x1,y1) - (x2,y2)`, if it exists. Also return the distance of `(x2,y2)' to the middle of the edge along with its index, so that the one closest can be chosen. def intersectingEdges(self, x1y1, x2y2, points): ...
Standard boilerplate Qt application code. Do everything but app.exec_() -- so that we can test the application in one thread def get_main_app(argv=[]): """ Standard boilerplate Qt application code. Do everything but app.exec_() -- so that we can test the application in one thread """ app = QApp...
Enable/Disable widgets which depend on an opened image. def toggleActions(self, value=True): """Enable/Disable widgets which depend on an opened image.""" for z in self.actions.zoomActions: z.setEnabled(value) for action in self.actions.onLoadActive: action.setEnabled(va...
In the middle of drawing, toggling between modes should be disabled. def toggleDrawingSensitive(self, drawing=True): """In the middle of drawing, toggling between modes should be disabled.""" self.actions.editMode.setEnabled(not drawing) if not drawing and self.beginner(): # Cancel ...
Function to handle difficult examples Update on each object def btnstate(self, item= None): """ Function to handle difficult examples Update on each object """ if not self.canvas.editing(): return item = self.currentItem() if not item: # If not selected Item...
Pop-up and give focus to the label editor. position MUST be in global coordinates. def newShape(self): """Pop-up and give focus to the label editor. position MUST be in global coordinates. """ if not self.useDefaultLabelCheckbox.isChecked() or not self.defaultLabelTextLine.tex...
Load the specified file, or the last opened file if None. def loadFile(self, filePath=None): """Load the specified file, or the last opened file if None.""" self.resetState() self.canvas.setEnabled(False) if filePath is None: filePath = self.settings.get(SETTING_FILENAME) ...
Figure out the size of the pixmap in order to fit the main widget. def scaleFitWindow(self): """Figure out the size of the pixmap in order to fit the main widget.""" e = 2.0 # So that no scrollbars are generated. w1 = self.centralWidget().width() - e h1 = self.centralWidget().height() ...
py2/py3 unicode helper def ustr(x): '''py2/py3 unicode helper''' if sys.version_info < (3, 0, 0): from PyQt4.QtCore import QString if type(x) == str: return x.decode(DEFAULT_ENCODING) if type(x) == QString: #https://blog.csdn.net/friendan/article/details/5108847...
Return a pretty-printed XML string for the Element. def prettify(self, elem): """ Return a pretty-printed XML string for the Element. """ rough_string = ElementTree.tostring(elem, 'utf8') root = etree.fromstring(rough_string) return etree.tostring(root, pretty_print=...
Return XML root def genXML(self): """ Return XML root """ # Check conditions if self.filename is None or \ self.foldername is None or \ self.imgSize is None: return None top = Element('annotation') if self.verified...
Perform a HTTP request and return decoded JSON data async def fetch(self, url, method='GET', headers=None, body=None): """Perform a HTTP request and return decoded JSON data""" request_headers = self.prepare_request_headers(headers) url = self.proxy + url if self.verbose: p...
A better wrapper over request for deferred signing def fetch2(self, path, api='public', method='GET', params={}, headers=None, body=None): """A better wrapper over request for deferred signing""" if self.enableRateLimit: self.throttle() self.lastRestRequestTimestamp = self.milliseco...
Exchange.request is the entry point for all generated methods def request(self, path, api='public', method='GET', params={}, headers=None, body=None): """Exchange.request is the entry point for all generated methods""" return self.fetch2(path, api, method, params, headers, body)
A helper method for matching error strings exactly vs broadly def find_broadly_matched_key(self, broad, string): """A helper method for matching error strings exactly vs broadly""" keys = list(broad.keys()) for i in range(0, len(keys)): key = keys[i] if string.find(key) ...
Perform a HTTP request and return decoded JSON data def fetch(self, url, method='GET', headers=None, body=None): """Perform a HTTP request and return decoded JSON data""" request_headers = self.prepare_request_headers(headers) url = self.proxy + url if self.verbose: print("...
A helper-wrapper for the safe_value_2() family. def safe_either(method, dictionary, key1, key2, default_value=None): """A helper-wrapper for the safe_value_2() family.""" value = method(dictionary, key1) return value if value is not None else method(dictionary, key2, default_value)
Deprecated, use decimal_to_precision instead def truncate(num, precision=0): """Deprecated, use decimal_to_precision instead""" if precision > 0: decimal_precision = math.pow(10, precision) return math.trunc(num * decimal_precision) / decimal_precision return int(Exchang...
Deprecated, todo: remove references from subclasses def truncate_to_string(num, precision=0): """Deprecated, todo: remove references from subclasses""" if precision > 0: parts = ('{0:.%df}' % precision).format(Decimal(num)).split('.') decimal_digits = parts[1][:precision].rstrip...
Checks an address is not the same character repeated or an empty sequence def check_address(self, address): """Checks an address is not the same character repeated or an empty sequence""" if address is None: self.raise_error(InvalidAddress, details='address is None') if all(letter =...
r''' Expects something like /tmp/tmpAjry4Gdsbench/test.weights.e5.XXX.YYY.pb Where XXX is a variation on the model size for example And where YYY is a const related to the training dataset def reduce_filename(f): r''' Expects something like /tmp/tmpAjry4Gdsbench/test.weights.e5.XXX.YYY.pb Where...
r''' local helper to just keep digits def keep_only_digits(s): r''' local helper to just keep digits ''' fs = '' for c in s: if c.isdigit(): fs += c return int(fs)
r""" Parses an STM file at ``stm_file`` into a list of :class:`STMSegment`. def parse_stm_file(stm_file): r""" Parses an STM file at ``stm_file`` into a list of :class:`STMSegment`. """ stm_segments = [] with codecs.open(stm_file, encoding="utf-8") as stm_lines: for stm_line in stm_line...
Reads a .wav file. Takes the path, and returns (PCM audio data, sample rate). def read_wave(path): """Reads a .wav file. Takes the path, and returns (PCM audio data, sample rate). """ with contextlib.closing(wave.open(path, 'rb')) as wf: num_channels = wf.getnchannels() assert num...
Writes a .wav file. Takes path, PCM audio data, and sample rate. def write_wave(path, audio, sample_rate): """Writes a .wav file. Takes path, PCM audio data, and sample rate. """ with contextlib.closing(wave.open(path, 'wb')) as wf: wf.setnchannels(1) wf.setsampwidth(2) wf...
Generates audio frames from PCM audio data. Takes the desired frame duration in milliseconds, the PCM data, and the sample rate. Yields Frames of the requested duration. def frame_generator(frame_duration_ms, audio, sample_rate): """Generates audio frames from PCM audio data. Takes the desired f...
Initialise the runner function with the passed args, kwargs def run(self): ''' Initialise the runner function with the passed args, kwargs ''' # Retrieve args/kwargs here; and fire up the processing using them try: transcript = self.fn(*self.args, **self.kwargs) ...
r''' Helper to exec locally (subprocess) or remotely (paramiko) def exec_command(command, cwd=None): r''' Helper to exec locally (subprocess) or remotely (paramiko) ''' rc = None stdout = stderr = None if ssh_conn is None: ld_library_path = {'LD_LIBRARY_PATH': '.:%s' % os.environ.g...
r''' Check local or remote system arch, to produce TaskCluster proper link. def get_arch_string(): r''' Check local or remote system arch, to produce TaskCluster proper link. ''' rc, stdout, stderr = exec_command('uname -sm') if rc > 0: raise AssertionError('Error checking OS') std...
r''' Download a native_client.tar.xz file from TaskCluster and extract it to dir. def extract_native_client_tarball(dir): r''' Download a native_client.tar.xz file from TaskCluster and extract it to dir. ''' assert_valid_dir(dir) target_tarball = os.path.join(dir, 'native_client.tar.xz') i...
r''' Ensure that a path is a zip file by: - checking length is 1 - checking extension is '.zip' def is_zip_file(models): r''' Ensure that a path is a zip file by: - checking length is 1 - checking extension is '.zip' ''' ext = os.path.splitext(models[0])[1] return (len(model...
r''' Detect if models is a list of protocolbuffer files or a ZIP file. If the latter, then unzip it and return the list of protocolbuffer files that were inside. def maybe_inspect_zip(models): r''' Detect if models is a list of protocolbuffer files or a ZIP file. If the latter, then unzip it an...
r''' Return a list of full path of files matching 'models', sorted in human numerical order (i.e., 0 1 2 ..., 10 11 12, ..., 100, ..., 1000). Files are supposed to be named identically except one variable component e.g. the list, test.weights.e5.lstm1200.ldc93s1.pb test.weights.e5.lstm1000....
r''' Copy models, libs and binary to a directory (new one if dir is None) def setup_tempdir(dir, models, wav, alphabet, lm_binary, trie, binaries): r''' Copy models, libs and binary to a directory (new one if dir is None) ''' if dir is None: dir = tempfile.mkdtemp(suffix='dsbench') sor...
r''' Cleanup temporary directory. def teardown_tempdir(dir): r''' Cleanup temporary directory. ''' if ssh_conn: delete_tree(dir) assert_valid_dir(dir) shutil.rmtree(dir)
r''' Read user's SSH configuration file def get_sshconfig(): r''' Read user's SSH configuration file ''' with open(os.path.expanduser('~/.ssh/config')) as f: cfg = paramiko.SSHConfig() cfg.parse(f) ret_dict = {} for d in cfg._config: _copy = dict(d) ...
r''' Establish a SSH connection to a remote host. It should be able to use SSH's config file Host name declarations. By default, will not automatically add trust for hosts, will use SSH agent and will try to load keys. def establish_ssh(target=None, auto_trust=False, allow_agent=True, look_keys=True): ...
r''' Core of the running of the benchmarks. We will run on all of models, against the WAV file provided as wav, and the provided alphabet. def run_benchmarks(dir, models, wav, alphabet, lm_binary=None, trie=None, iters=-1): r''' Core of the running of the benchmarks. We will run on all of models, again...
r''' Take an input dictionnary and write it to the object-file output. def produce_csv(input, output): r''' Take an input dictionnary and write it to the object-file output. ''' output.write('"model","mean","std"\n') for model_data in input: output.write('"%s",%f,%f\n' % (model_data['na...
r"""Creates a sparse representention of ``sequence``. Returns a tuple with (indices, values, shape) def to_sparse_tuple(sequence): r"""Creates a sparse representention of ``sequence``. Returns a tuple with (indices, values, shape) """ indices = np.asarray(list(zip([0]*len(sequence), range(l...
Generate a function to download a file based on given parameters This works by currying the above given arguments into a closure in the form of the following function. :param voxforge_url: the base voxforge URL :param archive_dir: the location to store the downloaded file :param total: the ...
Generate a function to extract a tar file based on given parameters This works by currying the above given arguments into a closure in the form of the following function. :param data_dir: the target directory to extract into :param number_of_test: the number of files to keep as the test set :...
Increments the counter by the given amount :param amount: the amount to increment by (default 1) :return: the incremented value of the counter def increment(self, amount=1): """Increments the counter by the given amount :param amount: the amount to increment by (default 1) ...
r''' This routine will calculate a WER report. It'll compute the `mean` WER and create ``Sample`` objects of the ``report_count`` top lowest loss items from the provided WER results tuple (only items with WER!=0 and ordered by their WER). def calculate_report(labels, decodings, distances, losses): r'''...
r""" Given a :class:`tf.SparseTensor` ``value``, return an array of Python strings representing its values, converting tokens to strings using ``alphabet``. def sparse_tensor_value_to_texts(value, alphabet): r""" Given a :class:`tf.SparseTensor` ``value``, return an array of Python strings represen...
Parse command line parameters Args: args ([str]): Command line parameters as list of strings Returns: :obj:`argparse.Namespace`: command line parameters namespace def parse_args(args): """Parse command line parameters Args: args ([str]): Command line parameters as list of strings ...
Setup basic logging Args: level (int): minimum log level for emitting messages def setup_logging(level): """Setup basic logging Args: level (int): minimum log level for emitting messages """ format = "[%(asctime)s] %(levelname)s:%(name)s:%(message)s" logging.basicConfig( lev...
Main entry point allowing external calls Args: args ([str]): command line parameter list def main(args): """Main entry point allowing external calls Args: args ([str]): command line parameter list """ args = parse_args(args) setup_logging(args.loglevel) _logger.info("Starting Gr...
Downloads the data associated with this instance Return: mp3_directory (os.path): The directory into which the associated mp3's were downloaded def download(self): """Downloads the data associated with this instance Return: mp3_directory (os.path): The directory into which t...
Converts the mp3's associated with this instance to wav's Return: wav_directory (os.path): The directory into which the associated wav's were downloaded def convert(self): """Converts the mp3's associated with this instance to wav's Return: wav_directory (os.path): The direc...
r""" Given a Python string ``original``, remove unsupported characters, map characters to integers and return a numpy array representing the processed string. def text_to_char_array(original, alphabet): r""" Given a Python string ``original``, remove unsupported characters, map characters to intege...
r""" The WER is defined as the editing/Levenshtein distance on word level divided by the amount of words in the original text. In case of the original having more words (N) than the result and both being totally different (all N words resulting in 1 edit operation each), the WER will always be 1 (N ...
r""" Next we concern ourselves with graph creation. However, before we do so we must introduce a utility function ``variable_on_cpu()`` used to create a variable in CPU memory. def variable_on_cpu(name, shape, initializer): r""" Next we concern ourselves with graph creation. However, before we ...
r''' This routine beam search decodes a mini-batch and calculates the loss and mean edit distance. Next to total and average loss it returns the mean edit distance, the decoded result and the batch's original Y. def calculate_mean_edit_distance_and_loss(iterator, dropout, reuse): r''' This routine ...
r''' With this preliminary step out of the way, we can for each GPU introduce a tower for which's batch we calculate and return the optimization gradients and the average loss across towers. def get_tower_results(iterator, optimizer, dropout_rates): r''' With this preliminary step out of the way, w...
r''' A routine for computing each variable's average of the gradients obtained from the GPUs. Note also that this code acts as a synchronization point as it requires all GPUs to be finished with their mini-batch before it can run to completion. def average_gradients(tower_gradients): r''' A routine...
r''' We introduce a function for logging a tensor variable's current state. It logs scalar values for the mean, standard deviation, minimum and maximum. Furthermore it logs a histogram of its state and (if given) of an optimization gradient. def log_variable(variable, gradient=None): r''' We introd...
r''' Restores the trained variables into a simpler graph that will be exported for serving. def export(): r''' Restores the trained variables into a simpler graph that will be exported for serving. ''' log_info('Exporting the model...') from tensorflow.python.framework.ops import Tensor, Operat...
Wrapper for the CTC Beam Search Decoder. :param probs_seq: 2-D list of probability distributions over each time step, with each element being a list of normalized probabilities over alphabet and blank. :type probs_seq: 2-D list :param alphabet: alphabet list. ...
Wrapper for the batched CTC beam search decoder. :param probs_seq: 3-D list with each element as an instance of 2-D list of probabilities used by ctc_beam_search_decoder(). :type probs_seq: 3-D list :param alphabet: alphabet list. :alphabet: Alphabet :param beam_size: Width fo...
Microphone may not support our native processing sampling rate, so resample from input_rate to RATE_PROCESS here for webrtcvad and deepspeech Args: data (binary): Input audio stream input_rate (int): Input audio rate to resample from def resample(self, data, input_rate)...
Return a block of audio data resampled to 16000hz, blocking if necessary. def read_resampled(self): """Return a block of audio data resampled to 16000hz, blocking if necessary.""" return self.resample(data=self.buffer_queue.get(), input_rate=self.input_rate)
Generator that yields all audio frames from microphone. def frame_generator(self): """Generator that yields all audio frames from microphone.""" if self.input_rate == self.RATE_PROCESS: while True: yield self.read() else: while True: yield...