INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
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 ...
def get_dump(self, fmap='', with_stats=False, dump_format="text"): """ 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 w...
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...
def get_score(self, fmap='', importance_type='weight'): """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...
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...
def trees_to_dataframe(self, fmap=''): """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 li...
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_names is None: self.feature_names = data.feature_names self.feature_types = data.feature_t...
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...
def get_split_value_histogram(self, feature, fmap='', bins=None, as_pandas=True): """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, de...
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...
def plot_importance(booster, ax=None, height=0.2, xlim=None, ylim=None, title='Feature importance', xlabel='F score', ylabel='Features', importance_type='weight', max_num_features=None, grid=True, show_values=True, **kwargs): """Plot im...
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.match(text) if ...
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='yes, missing', co...
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) ...
def to_graphviz(booster, fmap='', num_trees=0, rankdir='UT', yes_color='#0000FF', no_color='#FF0000', condition_node_params=None, leaf_node_params=None, **kwargs): """Convert specified tree to graphviz instance. IPython can automatically plot the returned graphiz instance. Otherw...
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(newIcon(icon)) if shortcut is not None: if isi...
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-9]+)', key(s))] sort_key = get_alphanum_key_...
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 shape.highlightVertex(index, shape.MOVE_VERTEX) ...
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.filePath is not None: self.parent().window().lab...
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 or y were changed, False if not. """ if x < 0 or x > self.pixmap.width() or y < 0 or y > self.pixmap.height(): x = max(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): """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 chose...
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 = QApplication(argv) app.setApplicationName(__appname__) app.setWindowIcon(newIcon("app")) # Tzutalin 201705+: Accept extra ...
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(value)
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 creation. print('Cancel creation.') self.canva...
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, take the first one item = self.labelList.item(self.labe...
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.text(): if len(self.labelHist) > 0: self.labelDialog = LabelDialog( ...
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) # Make sure that filePath is a regular python string...
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/51088476 #https://b...
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() - e a1 = w1 / h1 # Calculate a new scale value based...
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=True, encoding=ENCODE_METHOD).replace(" ".encode(), ...
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: top...
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: print("\nRequest:", method, url, headers, body) ...
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.milliseconds() request = self.sign(path, api, method,...
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) >= 0: return key return None
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("\nRequest:", method, url, request_headers, body) ...
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(Exchange.truncate_to_string(num, precision))
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('0') decimal_digits = decimal_digits if ...
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 == address[0] for letter in address) or len(address) < self.minFundingAddres...
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 XXX is a variation on the model size for example And where YYY is a const related to the training dataset ''' f = os.path.basename(f).split('.') return keep_only_digits(f[-3])
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_lines: stmSegment = STMSegment(stm_line) if not "ignore_time_...
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_channels == 1 sample_width = wf.getsampwidth() assert sample_width ...
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.setframerate(sample_rate) wf.writeframes(audio)
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 frame duration in milliseconds, the PCM data, and the sample rate. Yields Frames of the requested duration. """ n = int(sample_rate * (frame_duration_ms / 1000.0) * 2) ...
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) except: traceback.print_exc() ex...
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.get('LD_LIBRARY_PATH', '')} p = subprocess.Popen(command, stdo...
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') stdout = stdout.lower().strip() if not 'linux' in stdout: raise Assertio...
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') if os.path.isfile(target_tarball) and os.stat(target_tarball).st_size == 0: retu...
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(models) == 1) and (ext == '.zip')
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 and return the list of protocolbuffer files that were inside. ''' if not(is_zip_file(models)): return models if len(models) > 1: return models ...
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') sorted_models = all_files(models=models) if binaries is None: maybe_do...
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....
def all_files(models=[]): 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 ...
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) # Avoid buggy behavior with strange h...
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''' 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. ...
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, against the WAV file provided as wav, and the provided alphabet. ''' assert_valid_dir(dir) inference_times = [ ] for model in mode...
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['name'], model_data['mean'], model_data['stddev'])) output.flush() outp...
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(len(sequence)))), dtype=np.int64) shape = np.asarray([1, len(sequence)], dtype=np.int64) return indice...
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 ...
def _parallel_downloader(voxforge_url, archive_dir, total, counter): """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_d...
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 :...
def _parallel_extracter(data_dir, number_of_test, number_of_dev, total, counter): """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 ...
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) :return: the incremented value of the counter """ self.__lock.acquire() self.__count += amount v = self.value() self.__...
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 representing its values, converting tokens to strings using ``alphabet``. """ return sparse_tuple_to_texts((value.indices, value.values, value.dense_shape), alphabet)
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 Returns: :obj:`argparse.Namespace`: command line parameters namespace """ parser = argparse.ArgumentParser( description="Imports GramVaani data for Deep Speech" ...
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( level=level, stream=sys.stdout, format=format, datefmt="%Y-%m-%d %H:%M:%S" )
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 GramVaani importer...") _logger.info("Starting loading GramVaani csv...") csv = GramVaaniCSV(a...
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 the associated mp3's were downloaded """ mp3_directory = self._pre_download() self.data.swifter.apply(func=lambda arg: self._download(*arg, ...
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 directory into which the associated wav's were downloaded """ wav_directory = self._pre_convert() for mp3_filename in self.mp3_directory.glob('**/*.mp3')...
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 integers and return a numpy array representing the processed string. """ return np.asarray([alphabet.label_from_string(c) for c in original])
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 ...
def wer_cer_batch(originals, results): 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 operat...
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 do so we must introduce a utility function ``variable_on_cpu()`` used to create a variable in CPU memory. """ # Use the /cpu:0 device for scoped operations with tf.device(Con...
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 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. ''' # Obtain th...
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, 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. ''' # To calculate the mean of the losses ...
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 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. ''' # List ...
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 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. ''' name = ...
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, Operation inputs, outputs, _ = create_inference_graph(batch_size=FLAGS.export_batch_size, n_steps=...
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. ...
def ctc_beam_search_decoder(probs_seq, alphabet, beam_size, cutoff_prob=1.0, cutoff_top_n=40, scorer=None): """Wrapper for the CTC Beam Search Decoder. :param probs_seq: 2...
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...
def ctc_beam_search_decoder_batch(probs_seq, seq_lengths, alphabet, beam_size, num_processes, cutoff_prob=1.0, cutof...
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): """ 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 r...
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 self.read_resampled()
Generator that yields series of consecutive audio frames comprising each utterence, separated by yielding a single None. Determines voice activity by ratio of frames in padding_ms. Uses a buffer to include padding_ms prior to being triggered. Example: (frame, ..., frame, None, frame, ..., frame,...
def vad_collector(self, padding_ms=300, ratio=0.75, frames=None): """Generator that yields series of consecutive audio frames comprising each utterence, separated by yielding a single None. Determines voice activity by ratio of frames in padding_ms. Uses a buffer to include padding_ms prior to being...
Global `cut` function that supports parallel processing. Note that this only works using dt, custom POSTokenizer instances are not supported.
def cut(sentence, HMM=True): """ Global `cut` function that supports parallel processing. Note that this only works using dt, custom POSTokenizer instances are not supported. """ global dt if jieba.pool is None: for w in dt.cut(sentence, HMM=HMM): yield w else: ...
Change the module's `cut` and `cut_for_search` functions to the parallel version. Note that this only works using dt, custom Tokenizer instances are not supported.
def enable_parallel(processnum=None): """ Change the module's `cut` and `cut_for_search` functions to the parallel version. Note that this only works using dt, custom Tokenizer instances are not supported. """ global pool, dt, cut, cut_for_search from multiprocessing import cpu_count ...
The main function that segments an entire sentence that contains Chinese characters into separated words. Parameter: - sentence: The str(unicode) to be segmented. - cut_all: Model type. True for full pattern, False for accurate pattern. - HMM: Whether to use the Hidd...
def cut(self, sentence, cut_all=False, HMM=True): ''' The main function that segments an entire sentence that contains Chinese characters into separated words. Parameter: - sentence: The str(unicode) to be segmented. - cut_all: Model type. True for full pattern, ...
Finer segmentation for search engines.
def cut_for_search(self, sentence, HMM=True): """ Finer segmentation for search engines. """ words = self.cut(sentence, HMM=HMM) for w in words: if len(w) > 2: for i in xrange(len(w) - 1): gram2 = w[i:i + 2] if s...
Load personalized dict to improve detect rate. Parameter: - f : A plain text file contains words and their ocurrences. Can be a file-like object, or the path of the dictionary file, whose encoding must be utf-8. Structure of dict file: word1 freq...
def load_userdict(self, f): ''' Load personalized dict to improve detect rate. Parameter: - f : A plain text file contains words and their ocurrences. Can be a file-like object, or the path of the dictionary file, whose encoding must be utf-8. ...
Add a word to dictionary. freq and tag can be omitted, freq defaults to be a calculated value that ensures the word can be cut out.
def add_word(self, word, freq=None, tag=None): """ Add a word to dictionary. freq and tag can be omitted, freq defaults to be a calculated value that ensures the word can be cut out. """ self.check_initialized() word = strdecode(word) freq = int(freq) if ...
Suggest word frequency to force the characters in a word to be joined or splitted. Parameter: - segment : The segments that the word is expected to be cut into, If the word should be treated as a whole, use a str. - tune : If True, tune the word frequency...
def suggest_freq(self, segment, tune=False): """ Suggest word frequency to force the characters in a word to be joined or splitted. Parameter: - segment : The segments that the word is expected to be cut into, If the word should be treated as a whole,...
Tokenize a sentence and yields tuples of (word, start, end) Parameter: - sentence: the str(unicode) to be segmented. - mode: "default" or "search", "search" is for finer segmentation. - HMM: whether to use the Hidden Markov Model.
def tokenize(self, unicode_sentence, mode="default", HMM=True): """ Tokenize a sentence and yields tuples of (word, start, end) Parameter: - sentence: the str(unicode) to be segmented. - mode: "default" or "search", "search" is for finer segmentation. - HMM: ...
Extract keywords from sentence using TextRank algorithm. Parameter: - topK: return how many top keywords. `None` for all possible words. - withWeight: if True, return a list of (word, weight); if False, return a list of words. - allowPOS: the allowed...
def textrank(self, sentence, topK=20, withWeight=False, allowPOS=('ns', 'n', 'vn', 'v'), withFlag=False): """ Extract keywords from sentence using TextRank algorithm. Parameter: - topK: return how many top keywords. `None` for all possible words. - withWeight: if True, re...
Extract keywords from sentence using TF-IDF algorithm. Parameter: - topK: return how many top keywords. `None` for all possible words. - withWeight: if True, return a list of (word, weight); if False, return a list of words. - allowPOS: the allowed P...
def extract_tags(self, sentence, topK=20, withWeight=False, allowPOS=(), withFlag=False): """ Extract keywords from sentence using TF-IDF algorithm. Parameter: - topK: return how many top keywords. `None` for all possible words. - withWeight: if True, return a list of (wo...
Generates raw (English, other) pairs from a ParaCrawl V3.0 data file. Args: paracrawl_file: A ParaCrawl V3.0 en-.. data file. Yields: Pairs of (sentence_en, sentence_xx), as Unicode strings. Raises: StopIteration: If the file ends while this method is in the middle of creating a translation p...
def paracrawl_v3_pairs(paracrawl_file): """Generates raw (English, other) pairs from a ParaCrawl V3.0 data file. Args: paracrawl_file: A ParaCrawl V3.0 en-.. data file. Yields: Pairs of (sentence_en, sentence_xx), as Unicode strings. Raises: StopIteration: If the file ends while this method is in t...
Generates Unicode strings, one for each <seg> in a ParaCrawl data file. Also decodes some of the most common HTML entities found in ParaCrawl data. Args: paracrawl_file: A ParaCrawl V3.0 en-.. data file. Yields: One Unicode string for each <seg> element in the ParaCrawl data file.
def _raw_sentences(paracrawl_file): """Generates Unicode strings, one for each <seg> in a ParaCrawl data file. Also decodes some of the most common HTML entities found in ParaCrawl data. Args: paracrawl_file: A ParaCrawl V3.0 en-.. data file. Yields: One Unicode string for each <seg> element in the Pa...
Generates a cleaned-up stream of (English, other) translation pairs. Cleaning includes both filtering and simplistic sentence splitting, with minimal assumptions on the non-English pair member: (1) All filtering is done based on the English member of the pair, and (2) sentence splitting assumes only that sente...
def clean_en_xx_pairs(en_xx_pairs): """Generates a cleaned-up stream of (English, other) translation pairs. Cleaning includes both filtering and simplistic sentence splitting, with minimal assumptions on the non-English pair member: (1) All filtering is done based on the English member of the pair, and (2) sen...
Download a set of images from api.brain-map.org to `target_dir`. Args: image_ids: list, a list of image ids. target_dir: str, a directory to which to download the images.
def maybe_download_image_dataset(image_ids, target_dir): """Download a set of images from api.brain-map.org to `target_dir`. Args: image_ids: list, a list of image ids. target_dir: str, a directory to which to download the images. """ tf.gfile.MakeDirs(target_dir) num_images = len(image_ids) for...
Obtain a list of image paths corresponding to training or eval case. Args: tmp_dir: str, the root path to which raw images were written, at the top level having meta/ and raw/ subdirs. case: bool, whether obtaining file paths for training (true) or eval (false). training_fraction: float, the ...
def _get_case_file_paths(tmp_dir, case, training_fraction=0.95): """Obtain a list of image paths corresponding to training or eval case. Args: tmp_dir: str, the root path to which raw images were written, at the top level having meta/ and raw/ subdirs. case: bool, whether obtaining file paths for tra...
Create a numpy array with specified shape and masked fraction. Args: shape: tuple, shape of the mask to create. fraction: float, fraction of the mask area to populate with `mask_scalar`. Returns: numpy.array: A numpy array storing the mask.
def random_square_mask(shape, fraction): """Create a numpy array with specified shape and masked fraction. Args: shape: tuple, shape of the mask to create. fraction: float, fraction of the mask area to populate with `mask_scalar`. Returns: numpy.array: A numpy array storing the mask. """ mask =...
Base problem example generator for Allen Brain Atlas problems. Args: tmp_dir: str, a directory where raw example input data has been stored. training: bool, whether the mode of operation is training (or, alternatively, evaluation), determining whether examples in tmp_dir prefixed with train or d...
def _generator(tmp_dir, training, size=_BASE_EXAMPLE_IMAGE_SIZE, training_fraction=0.95): """Base problem example generator for Allen Brain Atlas problems. Args: tmp_dir: str, a directory where raw example input data has been stored. training: bool, whether the mode of operation is training...
Set of hyperparameters.
def transformer_moe_base(): """Set of hyperparameters.""" hparams = common_hparams.basic_params1() hparams.norm_type = "layer" hparams.hidden_size = 512 hparams.batch_size = 4096 hparams.max_length = 2001 hparams.max_input_seq_length = 2000 hparams.max_target_seq_length = 2000 hparams.dropout = 0.0 ...
Hyper parameters specifics for long sequence generation.
def transformer_moe_8k(): """Hyper parameters specifics for long sequence generation.""" hparams = transformer_moe_base() hparams.batch_size = 8192 hparams.max_length = 0 # max_length == batch_size hparams.eval_drop_long_sequences = True hparams.min_length_bucket = 256 # Avoid cyclic problems for big bat...
Base transformers model with moe. Will have the following architecture: * No encoder. * Layer 0: a - sep (self-attention - unmasked separable convolutions) * Layer 1: a - sep * Layer 2: a - sep * Layer 3: a - sep * Layer 4: a - sep * Decoder architecture: * Layer 0: a - a - sepm (self-a...
def transformer_moe_2k(): """Base transformers model with moe. Will have the following architecture: * No encoder. * Layer 0: a - sep (self-attention - unmasked separable convolutions) * Layer 1: a - sep * Layer 2: a - sep * Layer 3: a - sep * Layer 4: a - sep * Decoder architecture: *...
Model which formulate a seq2seq problem as language modeling.
def transformer_moe_prepend_8k(): """Model which formulate a seq2seq problem as language modeling.""" hparams = transformer_moe_8k() hparams.prepend_mode = "prepend_inputs_masked_attention" hparams.eval_drop_long_sequences = False hparams.max_input_seq_length = 7500 hparams.default_ff = "sepm" hparams.lay...
Applies residual function for RevNet. Args: x: input tensor depth1: Number of output channels for the first and second conv layers. depth2: Number of output channels for the third conv layer. dim: '2d' if 2-dimensional, '3d' if 3-dimensional. first_batch_norm: Whether to keep the first batch norm...
def f(x, depth1, depth2, dim='2d', first_batch_norm=True, stride=1, training=True, bottleneck=True, padding='SAME'): """Applies residual function for RevNet. Args: x: input tensor depth1: Number of output channels for the first and second conv layers. depth2: Number of output channels for the thi...
Downsamples 'x' by `stride` using a 1x1 convolution filter. Args: x: input tensor of size [N, H, W, C] output_channels: Desired number of output channels. dim: '2d' if 2-dimensional, '3d' if 3-dimensional. stride: What stride to use. Usually 1 or 2. scope: Optional variable scope. Returns: ...
def downsample_bottleneck(x, output_channels, dim='2d', stride=1, scope='h'): """Downsamples 'x' by `stride` using a 1x1 convolution filter. Args: x: input tensor of size [N, H, W, C] output_channels: Desired number of output channels. dim: '2d' if 2-dimensional, '3d' if 3-dimensional. stride: What...