id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
21,600
tzutalin/labelImg
libs/utils.py
natural_sort
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_...
python
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_...
[ "def", "natural_sort", "(", "list", ",", "key", "=", "lambda", "s", ":", "s", ")", ":", "def", "get_alphanum_key_func", "(", "key", ")", ":", "convert", "=", "lambda", "text", ":", "int", "(", "text", ")", "if", "text", ".", "isdigit", "(", ")", "e...
Sort the list into natural alphanumeric order.
[ "Sort", "the", "list", "into", "natural", "alphanumeric", "order", "." ]
6afd15aa88f89f41254e0004ed219b3965eb2c0d
https://github.com/tzutalin/labelImg/blob/6afd15aa88f89f41254e0004ed219b3965eb2c0d/libs/utils.py#L95-L103
21,601
tzutalin/labelImg
libs/canvas.py
Canvas.selectShapePoint
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) ...
python
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) ...
[ "def", "selectShapePoint", "(", "self", ",", "point", ")", ":", "self", ".", "deSelectShape", "(", ")", "if", "self", ".", "selectedVertex", "(", ")", ":", "# A vertex is marked for selection.", "index", ",", "shape", "=", "self", ".", "hVertex", ",", "self"...
Select the first shape created which contains this point.
[ "Select", "the", "first", "shape", "created", "which", "contains", "this", "point", "." ]
6afd15aa88f89f41254e0004ed219b3965eb2c0d
https://github.com/tzutalin/labelImg/blob/6afd15aa88f89f41254e0004ed219b3965eb2c0d/libs/canvas.py#L307-L319
21,602
tzutalin/labelImg
labelImg.py
MainWindow.toggleDrawingSensitive
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...
python
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...
[ "def", "toggleDrawingSensitive", "(", "self", ",", "drawing", "=", "True", ")", ":", "self", ".", "actions", ".", "editMode", ".", "setEnabled", "(", "not", "drawing", ")", "if", "not", "drawing", "and", "self", ".", "beginner", "(", ")", ":", "# Cancel ...
In the middle of drawing, toggling between modes should be disabled.
[ "In", "the", "middle", "of", "drawing", "toggling", "between", "modes", "should", "be", "disabled", "." ]
6afd15aa88f89f41254e0004ed219b3965eb2c0d
https://github.com/tzutalin/labelImg/blob/6afd15aa88f89f41254e0004ed219b3965eb2c0d/labelImg.py#L621-L629
21,603
tzutalin/labelImg
labelImg.py
MainWindow.btnstate
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...
python
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...
[ "def", "btnstate", "(", "self", ",", "item", "=", "None", ")", ":", "if", "not", "self", ".", "canvas", ".", "editing", "(", ")", ":", "return", "item", "=", "self", ".", "currentItem", "(", ")", "if", "not", "item", ":", "# If not selected Item, take ...
Function to handle difficult examples Update on each object
[ "Function", "to", "handle", "difficult", "examples", "Update", "on", "each", "object" ]
6afd15aa88f89f41254e0004ed219b3965eb2c0d
https://github.com/tzutalin/labelImg/blob/6afd15aa88f89f41254e0004ed219b3965eb2c0d/labelImg.py#L685-L709
21,604
tzutalin/labelImg
labelImg.py
MainWindow.newShape
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( ...
python
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( ...
[ "def", "newShape", "(", "self", ")", ":", "if", "not", "self", ".", "useDefaultLabelCheckbox", ".", "isChecked", "(", ")", "or", "not", "self", ".", "defaultLabelTextLine", ".", "text", "(", ")", ":", "if", "len", "(", "self", ".", "labelHist", ")", ">...
Pop-up and give focus to the label editor. position MUST be in global coordinates.
[ "Pop", "-", "up", "and", "give", "focus", "to", "the", "label", "editor", "." ]
6afd15aa88f89f41254e0004ed219b3965eb2c0d
https://github.com/tzutalin/labelImg/blob/6afd15aa88f89f41254e0004ed219b3965eb2c0d/labelImg.py#L839-L876
21,605
tzutalin/labelImg
labelImg.py
MainWindow.scaleFitWindow
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...
python
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...
[ "def", "scaleFitWindow", "(", "self", ")", ":", "e", "=", "2.0", "# So that no scrollbars are generated.", "w1", "=", "self", ".", "centralWidget", "(", ")", ".", "width", "(", ")", "-", "e", "h1", "=", "self", ".", "centralWidget", "(", ")", ".", "heigh...
Figure out the size of the pixmap in order to fit the main widget.
[ "Figure", "out", "the", "size", "of", "the", "pixmap", "in", "order", "to", "fit", "the", "main", "widget", "." ]
6afd15aa88f89f41254e0004ed219b3965eb2c0d
https://github.com/tzutalin/labelImg/blob/6afd15aa88f89f41254e0004ed219b3965eb2c0d/labelImg.py#L1069-L1079
21,606
tzutalin/labelImg
libs/pascal_voc_io.py
PascalVocWriter.genXML
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...
python
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...
[ "def", "genXML", "(", "self", ")", ":", "# Check conditions", "if", "self", ".", "filename", "is", "None", "or", "self", ".", "foldername", "is", "None", "or", "self", ".", "imgSize", "is", "None", ":", "return", "None", "top", "=", "Element", "(", "'a...
Return XML root
[ "Return", "XML", "root" ]
6afd15aa88f89f41254e0004ed219b3965eb2c0d
https://github.com/tzutalin/labelImg/blob/6afd15aa88f89f41254e0004ed219b3965eb2c0d/libs/pascal_voc_io.py#L37-L78
21,607
ccxt/ccxt
python/ccxt/base/exchange.py
Exchange.fetch2
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,...
python
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,...
[ "def", "fetch2", "(", "self", ",", "path", ",", "api", "=", "'public'", ",", "method", "=", "'GET'", ",", "params", "=", "{", "}", ",", "headers", "=", "None", ",", "body", "=", "None", ")", ":", "if", "self", ".", "enableRateLimit", ":", "self", ...
A better wrapper over request for deferred signing
[ "A", "better", "wrapper", "over", "request", "for", "deferred", "signing" ]
23062efd7a5892c79b370c9d951c03cf8c0ddf23
https://github.com/ccxt/ccxt/blob/23062efd7a5892c79b370c9d951c03cf8c0ddf23/python/ccxt/base/exchange.py#L423-L429
21,608
ccxt/ccxt
python/ccxt/base/exchange.py
Exchange.request
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)
python
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)
[ "def", "request", "(", "self", ",", "path", ",", "api", "=", "'public'", ",", "method", "=", "'GET'", ",", "params", "=", "{", "}", ",", "headers", "=", "None", ",", "body", "=", "None", ")", ":", "return", "self", ".", "fetch2", "(", "path", ","...
Exchange.request is the entry point for all generated methods
[ "Exchange", ".", "request", "is", "the", "entry", "point", "for", "all", "generated", "methods" ]
23062efd7a5892c79b370c9d951c03cf8c0ddf23
https://github.com/ccxt/ccxt/blob/23062efd7a5892c79b370c9d951c03cf8c0ddf23/python/ccxt/base/exchange.py#L431-L433
21,609
ccxt/ccxt
python/ccxt/base/exchange.py
Exchange.find_broadly_matched_key
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
python
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
[ "def", "find_broadly_matched_key", "(", "self", ",", "broad", ",", "string", ")", ":", "keys", "=", "list", "(", "broad", ".", "keys", "(", ")", ")", "for", "i", "in", "range", "(", "0", ",", "len", "(", "keys", ")", ")", ":", "key", "=", "keys",...
A helper method for matching error strings exactly vs broadly
[ "A", "helper", "method", "for", "matching", "error", "strings", "exactly", "vs", "broadly" ]
23062efd7a5892c79b370c9d951c03cf8c0ddf23
https://github.com/ccxt/ccxt/blob/23062efd7a5892c79b370c9d951c03cf8c0ddf23/python/ccxt/base/exchange.py#L445-L452
21,610
ccxt/ccxt
python/ccxt/base/exchange.py
Exchange.truncate
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))
python
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))
[ "def", "truncate", "(", "num", ",", "precision", "=", "0", ")", ":", "if", "precision", ">", "0", ":", "decimal_precision", "=", "math", ".", "pow", "(", "10", ",", "precision", ")", "return", "math", ".", "trunc", "(", "num", "*", "decimal_precision",...
Deprecated, use decimal_to_precision instead
[ "Deprecated", "use", "decimal_to_precision", "instead" ]
23062efd7a5892c79b370c9d951c03cf8c0ddf23
https://github.com/ccxt/ccxt/blob/23062efd7a5892c79b370c9d951c03cf8c0ddf23/python/ccxt/base/exchange.py#L622-L627
21,611
ccxt/ccxt
python/ccxt/base/exchange.py
Exchange.check_address
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...
python
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...
[ "def", "check_address", "(", "self", ",", "address", ")", ":", "if", "address", "is", "None", ":", "self", ".", "raise_error", "(", "InvalidAddress", ",", "details", "=", "'address is None'", ")", "if", "all", "(", "letter", "==", "address", "[", "0", "]...
Checks an address is not the same character repeated or an empty sequence
[ "Checks", "an", "address", "is", "not", "the", "same", "character", "repeated", "or", "an", "empty", "sequence" ]
23062efd7a5892c79b370c9d951c03cf8c0ddf23
https://github.com/ccxt/ccxt/blob/23062efd7a5892c79b370c9d951c03cf8c0ddf23/python/ccxt/base/exchange.py#L1000-L1006
21,612
mozilla/DeepSpeech
util/benchmark.py
keep_only_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)
python
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)
[ "def", "keep_only_digits", "(", "s", ")", ":", "fs", "=", "''", "for", "c", "in", "s", ":", "if", "c", ".", "isdigit", "(", ")", ":", "fs", "+=", "c", "return", "int", "(", "fs", ")" ]
r''' local helper to just keep digits
[ "r", "local", "helper", "to", "just", "keep", "digits" ]
f64aa73e7fbe9dde40d4fcf23b42ab304747d152
https://github.com/mozilla/DeepSpeech/blob/f64aa73e7fbe9dde40d4fcf23b42ab304747d152/util/benchmark.py#L6-L15
21,613
mozilla/DeepSpeech
examples/vad_transcriber/wavSplit.py
read_wave
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 ...
python
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 ...
[ "def", "read_wave", "(", "path", ")", ":", "with", "contextlib", ".", "closing", "(", "wave", ".", "open", "(", "path", ",", "'rb'", ")", ")", "as", "wf", ":", "num_channels", "=", "wf", ".", "getnchannels", "(", ")", "assert", "num_channels", "==", ...
Reads a .wav file. Takes the path, and returns (PCM audio data, sample rate).
[ "Reads", "a", ".", "wav", "file", "." ]
f64aa73e7fbe9dde40d4fcf23b42ab304747d152
https://github.com/mozilla/DeepSpeech/blob/f64aa73e7fbe9dde40d4fcf23b42ab304747d152/examples/vad_transcriber/wavSplit.py#L6-L21
21,614
mozilla/DeepSpeech
examples/vad_transcriber/wavSplit.py
write_wave
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)
python
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)
[ "def", "write_wave", "(", "path", ",", "audio", ",", "sample_rate", ")", ":", "with", "contextlib", ".", "closing", "(", "wave", ".", "open", "(", "path", ",", "'wb'", ")", ")", "as", "wf", ":", "wf", ".", "setnchannels", "(", "1", ")", "wf", ".", ...
Writes a .wav file. Takes path, PCM audio data, and sample rate.
[ "Writes", "a", ".", "wav", "file", "." ]
f64aa73e7fbe9dde40d4fcf23b42ab304747d152
https://github.com/mozilla/DeepSpeech/blob/f64aa73e7fbe9dde40d4fcf23b42ab304747d152/examples/vad_transcriber/wavSplit.py#L24-L33
21,615
mozilla/DeepSpeech
examples/vad_transcriber/wavSplit.py
frame_generator
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) ...
python
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) ...
[ "def", "frame_generator", "(", "frame_duration_ms", ",", "audio", ",", "sample_rate", ")", ":", "n", "=", "int", "(", "sample_rate", "*", "(", "frame_duration_ms", "/", "1000.0", ")", "*", "2", ")", "offset", "=", "0", "timestamp", "=", "0.0", "duration", ...
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.
[ "Generates", "audio", "frames", "from", "PCM", "audio", "data", "." ]
f64aa73e7fbe9dde40d4fcf23b42ab304747d152
https://github.com/mozilla/DeepSpeech/blob/f64aa73e7fbe9dde40d4fcf23b42ab304747d152/examples/vad_transcriber/wavSplit.py#L44-L59
21,616
mozilla/DeepSpeech
examples/vad_transcriber/audioTranscript_gui.py
Worker.run
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...
python
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...
[ "def", "run", "(", "self", ")", ":", "# Retrieve args/kwargs here; and fire up the processing using them", "try", ":", "transcript", "=", "self", ".", "fn", "(", "*", "self", ".", "args", ",", "*", "*", "self", ".", "kwargs", ")", "except", ":", "traceback", ...
Initialise the runner function with the passed args, kwargs
[ "Initialise", "the", "runner", "function", "with", "the", "passed", "args", "kwargs" ]
f64aa73e7fbe9dde40d4fcf23b42ab304747d152
https://github.com/mozilla/DeepSpeech/blob/f64aa73e7fbe9dde40d4fcf23b42ab304747d152/examples/vad_transcriber/audioTranscript_gui.py#L71-L88
21,617
mozilla/DeepSpeech
bin/benchmark_nc.py
get_arch_string
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...
python
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...
[ "def", "get_arch_string", "(", ")", ":", "rc", ",", "stdout", ",", "stderr", "=", "exec_command", "(", "'uname -sm'", ")", "if", "rc", ">", "0", ":", "raise", "AssertionError", "(", "'Error checking OS'", ")", "stdout", "=", "stdout", ".", "lower", "(", ...
r''' Check local or remote system arch, to produce TaskCluster proper link.
[ "r", "Check", "local", "or", "remote", "system", "arch", "to", "produce", "TaskCluster", "proper", "link", "." ]
f64aa73e7fbe9dde40d4fcf23b42ab304747d152
https://github.com/mozilla/DeepSpeech/blob/f64aa73e7fbe9dde40d4fcf23b42ab304747d152/bin/benchmark_nc.py#L68-L91
21,618
mozilla/DeepSpeech
bin/benchmark_nc.py
extract_native_client_tarball
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...
python
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...
[ "def", "extract_native_client_tarball", "(", "dir", ")", ":", "assert_valid_dir", "(", "dir", ")", "target_tarball", "=", "os", ".", "path", ".", "join", "(", "dir", ",", "'native_client.tar.xz'", ")", "if", "os", ".", "path", ".", "isfile", "(", "target_tar...
r''' Download a native_client.tar.xz file from TaskCluster and extract it to dir.
[ "r", "Download", "a", "native_client", ".", "tar", ".", "xz", "file", "from", "TaskCluster", "and", "extract", "it", "to", "dir", "." ]
f64aa73e7fbe9dde40d4fcf23b42ab304747d152
https://github.com/mozilla/DeepSpeech/blob/f64aa73e7fbe9dde40d4fcf23b42ab304747d152/bin/benchmark_nc.py#L97-L110
21,619
mozilla/DeepSpeech
bin/benchmark_nc.py
maybe_inspect_zip
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 ...
python
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 ...
[ "def", "maybe_inspect_zip", "(", "models", ")", ":", "if", "not", "(", "is_zip_file", "(", "models", ")", ")", ":", "return", "models", "if", "len", "(", "models", ")", ">", "1", ":", "return", "models", "if", "len", "(", "models", ")", "<", "1", "...
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.
[ "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", "."...
f64aa73e7fbe9dde40d4fcf23b42ab304747d152
https://github.com/mozilla/DeepSpeech/blob/f64aa73e7fbe9dde40d4fcf23b42ab304747d152/bin/benchmark_nc.py#L121-L137
21,620
mozilla/DeepSpeech
bin/benchmark_nc.py
teardown_tempdir
def teardown_tempdir(dir): r''' Cleanup temporary directory. ''' if ssh_conn: delete_tree(dir) assert_valid_dir(dir) shutil.rmtree(dir)
python
def teardown_tempdir(dir): r''' Cleanup temporary directory. ''' if ssh_conn: delete_tree(dir) assert_valid_dir(dir) shutil.rmtree(dir)
[ "def", "teardown_tempdir", "(", "dir", ")", ":", "if", "ssh_conn", ":", "delete_tree", "(", "dir", ")", "assert_valid_dir", "(", "dir", ")", "shutil", ".", "rmtree", "(", "dir", ")" ]
r''' Cleanup temporary directory.
[ "r", "Cleanup", "temporary", "directory", "." ]
f64aa73e7fbe9dde40d4fcf23b42ab304747d152
https://github.com/mozilla/DeepSpeech/blob/f64aa73e7fbe9dde40d4fcf23b42ab304747d152/bin/benchmark_nc.py#L280-L289
21,621
mozilla/DeepSpeech
bin/benchmark_nc.py
get_sshconfig
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...
python
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...
[ "def", "get_sshconfig", "(", ")", ":", "with", "open", "(", "os", ".", "path", ".", "expanduser", "(", "'~/.ssh/config'", ")", ")", "as", "f", ":", "cfg", "=", "paramiko", ".", "SSHConfig", "(", ")", "cfg", ".", "parse", "(", "f", ")", "ret_dict", ...
r''' Read user's SSH configuration file
[ "r", "Read", "user", "s", "SSH", "configuration", "file" ]
f64aa73e7fbe9dde40d4fcf23b42ab304747d152
https://github.com/mozilla/DeepSpeech/blob/f64aa73e7fbe9dde40d4fcf23b42ab304747d152/bin/benchmark_nc.py#L291-L308
21,622
mozilla/DeepSpeech
bin/benchmark_nc.py
establish_ssh
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. ...
python
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. ...
[ "def", "establish_ssh", "(", "target", "=", "None", ",", "auto_trust", "=", "False", ",", "allow_agent", "=", "True", ",", "look_keys", "=", "True", ")", ":", "def", "password_prompt", "(", "username", ",", "hostname", ")", ":", "r'''\n If the Host is r...
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", "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", "...
f64aa73e7fbe9dde40d4fcf23b42ab304747d152
https://github.com/mozilla/DeepSpeech/blob/f64aa73e7fbe9dde40d4fcf23b42ab304747d152/bin/benchmark_nc.py#L310-L375
21,623
mozilla/DeepSpeech
bin/benchmark_nc.py
run_benchmarks
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...
python
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...
[ "def", "run_benchmarks", "(", "dir", ",", "models", ",", "wav", ",", "alphabet", ",", "lm_binary", "=", "None", ",", "trie", "=", "None", ",", "iters", "=", "-", "1", ")", ":", "assert_valid_dir", "(", "dir", ")", "inference_times", "=", "[", "]", "f...
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.
[ "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", "." ]
f64aa73e7fbe9dde40d4fcf23b42ab304747d152
https://github.com/mozilla/DeepSpeech/blob/f64aa73e7fbe9dde40d4fcf23b42ab304747d152/bin/benchmark_nc.py#L377-L422
21,624
mozilla/DeepSpeech
bin/benchmark_nc.py
produce_csv
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...
python
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...
[ "def", "produce_csv", "(", "input", ",", "output", ")", ":", "output", ".", "write", "(", "'\"model\",\"mean\",\"std\"\\n'", ")", "for", "model_data", "in", "input", ":", "output", ".", "write", "(", "'\"%s\",%f,%f\\n'", "%", "(", "model_data", "[", "'name'", ...
r''' Take an input dictionnary and write it to the object-file output.
[ "r", "Take", "an", "input", "dictionnary", "and", "write", "it", "to", "the", "object", "-", "file", "output", "." ]
f64aa73e7fbe9dde40d4fcf23b42ab304747d152
https://github.com/mozilla/DeepSpeech/blob/f64aa73e7fbe9dde40d4fcf23b42ab304747d152/bin/benchmark_nc.py#L424-L433
21,625
mozilla/DeepSpeech
bin/import_voxforge.py
_parallel_downloader
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...
python
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...
[ "def", "_parallel_downloader", "(", "voxforge_url", ",", "archive_dir", ",", "total", ",", "counter", ")", ":", "def", "download", "(", "d", ")", ":", "\"\"\"Binds voxforge_url, archive_dir, total, and counter into this scope\n Downloads the given file\n :param d: a...
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", "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", "." ...
f64aa73e7fbe9dde40d4fcf23b42ab304747d152
https://github.com/mozilla/DeepSpeech/blob/f64aa73e7fbe9dde40d4fcf23b42ab304747d152/bin/import_voxforge.py#L50-L72
21,626
mozilla/DeepSpeech
bin/import_voxforge.py
_parallel_extracter
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 ...
python
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 ...
[ "def", "_parallel_extracter", "(", "data_dir", ",", "number_of_test", ",", "number_of_dev", ",", "total", ",", "counter", ")", ":", "def", "extract", "(", "d", ")", ":", "\"\"\"Binds data_dir, number_of_test, number_of_dev, total, and counter into this scope\n Extracts...
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 :...
[ "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"...
f64aa73e7fbe9dde40d4fcf23b42ab304747d152
https://github.com/mozilla/DeepSpeech/blob/f64aa73e7fbe9dde40d4fcf23b42ab304747d152/bin/import_voxforge.py#L74-L105
21,627
mozilla/DeepSpeech
util/text.py
text_to_char_array
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])
python
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])
[ "def", "text_to_char_array", "(", "original", ",", "alphabet", ")", ":", "return", "np", ".", "asarray", "(", "[", "alphabet", ".", "label_from_string", "(", "c", ")", "for", "c", "in", "original", "]", ")" ]
r""" Given a Python string ``original``, remove unsupported characters, map characters to integers and return a numpy array representing the processed string.
[ "r", "Given", "a", "Python", "string", "original", "remove", "unsupported", "characters", "map", "characters", "to", "integers", "and", "return", "a", "numpy", "array", "representing", "the", "processed", "string", "." ]
f64aa73e7fbe9dde40d4fcf23b42ab304747d152
https://github.com/mozilla/DeepSpeech/blob/f64aa73e7fbe9dde40d4fcf23b42ab304747d152/util/text.py#L50-L55
21,628
mozilla/DeepSpeech
DeepSpeech.py
calculate_mean_edit_distance_and_loss
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...
python
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...
[ "def", "calculate_mean_edit_distance_and_loss", "(", "iterator", ",", "dropout", ",", "reuse", ")", ":", "# Obtain the next batch of data", "(", "batch_x", ",", "batch_seq_len", ")", ",", "batch_y", "=", "iterator", ".", "get_next", "(", ")", "# Calculate the logits o...
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.
[ "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",...
f64aa73e7fbe9dde40d4fcf23b42ab304747d152
https://github.com/mozilla/DeepSpeech/blob/f64aa73e7fbe9dde40d4fcf23b42ab304747d152/DeepSpeech.py#L176-L195
21,629
mozilla/DeepSpeech
DeepSpeech.py
get_tower_results
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 ...
python
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 ...
[ "def", "get_tower_results", "(", "iterator", ",", "optimizer", ",", "dropout_rates", ")", ":", "# To calculate the mean of the losses", "tower_avg_losses", "=", "[", "]", "# Tower gradients to return", "tower_gradients", "=", "[", "]", "with", "tf", ".", "variable_scope...
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.
[ "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", "averag...
f64aa73e7fbe9dde40d4fcf23b42ab304747d152
https://github.com/mozilla/DeepSpeech/blob/f64aa73e7fbe9dde40d4fcf23b42ab304747d152/DeepSpeech.py#L231-L273
21,630
mozilla/DeepSpeech
DeepSpeech.py
average_gradients
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 ...
python
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 ...
[ "def", "average_gradients", "(", "tower_gradients", ")", ":", "# List of average gradients to return to the caller", "average_grads", "=", "[", "]", "# Run this on cpu_device to conserve GPU memory", "with", "tf", ".", "device", "(", "Config", ".", "cpu_device", ")", ":", ...
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.
[ "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", "a...
f64aa73e7fbe9dde40d4fcf23b42ab304747d152
https://github.com/mozilla/DeepSpeech/blob/f64aa73e7fbe9dde40d4fcf23b42ab304747d152/DeepSpeech.py#L276-L310
21,631
mozilla/DeepSpeech
native_client/ctcdecode/__init__.py
ctc_beam_search_decoder
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...
python
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...
[ "def", "ctc_beam_search_decoder", "(", "probs_seq", ",", "alphabet", ",", "beam_size", ",", "cutoff_prob", "=", "1.0", ",", "cutoff_top_n", "=", "40", ",", "scorer", "=", "None", ")", ":", "beam_results", "=", "swigwrapper", ".", "ctc_beam_search_decoder", "(", ...
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", "CTC", "Beam", "Search", "Decoder", "." ]
f64aa73e7fbe9dde40d4fcf23b42ab304747d152
https://github.com/mozilla/DeepSpeech/blob/f64aa73e7fbe9dde40d4fcf23b42ab304747d152/native_client/ctcdecode/__init__.py#L25-L59
21,632
mozilla/DeepSpeech
native_client/ctcdecode/__init__.py
ctc_beam_search_decoder_batch
def ctc_beam_search_decoder_batch(probs_seq, seq_lengths, alphabet, beam_size, num_processes, cutoff_prob=1.0, cutof...
python
def ctc_beam_search_decoder_batch(probs_seq, seq_lengths, alphabet, beam_size, num_processes, cutoff_prob=1.0, cutof...
[ "def", "ctc_beam_search_decoder_batch", "(", "probs_seq", ",", "seq_lengths", ",", "alphabet", ",", "beam_size", ",", "num_processes", ",", "cutoff_prob", "=", "1.0", ",", "cutoff_top_n", "=", "40", ",", "scorer", "=", "None", ")", ":", "batch_beam_results", "="...
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...
[ "Wrapper", "for", "the", "batched", "CTC", "beam", "search", "decoder", "." ]
f64aa73e7fbe9dde40d4fcf23b42ab304747d152
https://github.com/mozilla/DeepSpeech/blob/f64aa73e7fbe9dde40d4fcf23b42ab304747d152/native_client/ctcdecode/__init__.py#L62-L104
21,633
mozilla/DeepSpeech
examples/mic_vad_streaming/mic_vad_streaming.py
Audio.resample
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...
python
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...
[ "def", "resample", "(", "self", ",", "data", ",", "input_rate", ")", ":", "data16", "=", "np", ".", "fromstring", "(", "string", "=", "data", ",", "dtype", "=", "np", ".", "int16", ")", "resample_size", "=", "int", "(", "len", "(", "data16", ")", "...
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
[ "Microphone", "may", "not", "support", "our", "native", "processing", "sampling", "rate", "so", "resample", "from", "input_rate", "to", "RATE_PROCESS", "here", "for", "webrtcvad", "and", "deepspeech" ]
f64aa73e7fbe9dde40d4fcf23b42ab304747d152
https://github.com/mozilla/DeepSpeech/blob/f64aa73e7fbe9dde40d4fcf23b42ab304747d152/examples/mic_vad_streaming/mic_vad_streaming.py#L52-L66
21,634
mozilla/DeepSpeech
examples/mic_vad_streaming/mic_vad_streaming.py
Audio.read_resampled
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)
python
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)
[ "def", "read_resampled", "(", "self", ")", ":", "return", "self", ".", "resample", "(", "data", "=", "self", ".", "buffer_queue", ".", "get", "(", ")", ",", "input_rate", "=", "self", ".", "input_rate", ")" ]
Return a block of audio data resampled to 16000hz, blocking if necessary.
[ "Return", "a", "block", "of", "audio", "data", "resampled", "to", "16000hz", "blocking", "if", "necessary", "." ]
f64aa73e7fbe9dde40d4fcf23b42ab304747d152
https://github.com/mozilla/DeepSpeech/blob/f64aa73e7fbe9dde40d4fcf23b42ab304747d152/examples/mic_vad_streaming/mic_vad_streaming.py#L68-L71
21,635
mozilla/DeepSpeech
examples/mic_vad_streaming/mic_vad_streaming.py
VADAudio.frame_generator
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()
python
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()
[ "def", "frame_generator", "(", "self", ")", ":", "if", "self", ".", "input_rate", "==", "self", ".", "RATE_PROCESS", ":", "while", "True", ":", "yield", "self", ".", "read", "(", ")", "else", ":", "while", "True", ":", "yield", "self", ".", "read_resam...
Generator that yields all audio frames from microphone.
[ "Generator", "that", "yields", "all", "audio", "frames", "from", "microphone", "." ]
f64aa73e7fbe9dde40d4fcf23b42ab304747d152
https://github.com/mozilla/DeepSpeech/blob/f64aa73e7fbe9dde40d4fcf23b42ab304747d152/examples/mic_vad_streaming/mic_vad_streaming.py#L103-L110
21,636
fxsjy/jieba
jieba/posseg/__init__.py
cut
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: ...
python
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: ...
[ "def", "cut", "(", "sentence", ",", "HMM", "=", "True", ")", ":", "global", "dt", "if", "jieba", ".", "pool", "is", "None", ":", "for", "w", "in", "dt", ".", "cut", "(", "sentence", ",", "HMM", "=", "HMM", ")", ":", "yield", "w", "else", ":", ...
Global `cut` function that supports parallel processing. Note that this only works using dt, custom POSTokenizer instances are not supported.
[ "Global", "cut", "function", "that", "supports", "parallel", "processing", "." ]
8212b6c5725d08311952a3a08e5509eeaee33eb7
https://github.com/fxsjy/jieba/blob/8212b6c5725d08311952a3a08e5509eeaee33eb7/jieba/posseg/__init__.py#L272-L291
21,637
fxsjy/jieba
jieba/__init__.py
enable_parallel
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 ...
python
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 ...
[ "def", "enable_parallel", "(", "processnum", "=", "None", ")", ":", "global", "pool", ",", "dt", ",", "cut", ",", "cut_for_search", "from", "multiprocessing", "import", "cpu_count", "if", "os", ".", "name", "==", "'nt'", ":", "raise", "NotImplementedError", ...
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.
[ "Change", "the", "module", "s", "cut", "and", "cut_for_search", "functions", "to", "the", "parallel", "version", "." ]
8212b6c5725d08311952a3a08e5509eeaee33eb7
https://github.com/fxsjy/jieba/blob/8212b6c5725d08311952a3a08e5509eeaee33eb7/jieba/__init__.py#L569-L589
21,638
fxsjy/jieba
jieba/__init__.py
Tokenizer.cut
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, ...
python
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, ...
[ "def", "cut", "(", "self", ",", "sentence", ",", "cut_all", "=", "False", ",", "HMM", "=", "True", ")", ":", "sentence", "=", "strdecode", "(", "sentence", ")", "if", "cut_all", ":", "re_han", "=", "re_han_cut_all", "re_skip", "=", "re_skip_cut_all", "el...
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...
[ "The", "main", "function", "that", "segments", "an", "entire", "sentence", "that", "contains", "Chinese", "characters", "into", "separated", "words", "." ]
8212b6c5725d08311952a3a08e5509eeaee33eb7
https://github.com/fxsjy/jieba/blob/8212b6c5725d08311952a3a08e5509eeaee33eb7/jieba/__init__.py#L275-L315
21,639
fxsjy/jieba
jieba/__init__.py
Tokenizer.cut_for_search
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...
python
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...
[ "def", "cut_for_search", "(", "self", ",", "sentence", ",", "HMM", "=", "True", ")", ":", "words", "=", "self", ".", "cut", "(", "sentence", ",", "HMM", "=", "HMM", ")", "for", "w", "in", "words", ":", "if", "len", "(", "w", ")", ">", "2", ":",...
Finer segmentation for search engines.
[ "Finer", "segmentation", "for", "search", "engines", "." ]
8212b6c5725d08311952a3a08e5509eeaee33eb7
https://github.com/fxsjy/jieba/blob/8212b6c5725d08311952a3a08e5509eeaee33eb7/jieba/__init__.py#L317-L333
21,640
fxsjy/jieba
jieba/__init__.py
Tokenizer.load_userdict
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. ...
python
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. ...
[ "def", "load_userdict", "(", "self", ",", "f", ")", ":", "self", ".", "check_initialized", "(", ")", "if", "isinstance", "(", "f", ",", "string_types", ")", ":", "f_name", "=", "f", "f", "=", "open", "(", "f", ",", "'rb'", ")", "else", ":", "f_name...
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...
[ "Load", "personalized", "dict", "to", "improve", "detect", "rate", "." ]
8212b6c5725d08311952a3a08e5509eeaee33eb7
https://github.com/fxsjy/jieba/blob/8212b6c5725d08311952a3a08e5509eeaee33eb7/jieba/__init__.py#L359-L395
21,641
fxsjy/jieba
jieba/__init__.py
Tokenizer.add_word
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 ...
python
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 ...
[ "def", "add_word", "(", "self", ",", "word", ",", "freq", "=", "None", ",", "tag", "=", "None", ")", ":", "self", ".", "check_initialized", "(", ")", "word", "=", "strdecode", "(", "word", ")", "freq", "=", "int", "(", "freq", ")", "if", "freq", ...
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.
[ "Add", "a", "word", "to", "dictionary", "." ]
8212b6c5725d08311952a3a08e5509eeaee33eb7
https://github.com/fxsjy/jieba/blob/8212b6c5725d08311952a3a08e5509eeaee33eb7/jieba/__init__.py#L397-L416
21,642
fxsjy/jieba
jieba/__init__.py
Tokenizer.suggest_freq
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,...
python
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,...
[ "def", "suggest_freq", "(", "self", ",", "segment", ",", "tune", "=", "False", ")", ":", "self", ".", "check_initialized", "(", ")", "ftotal", "=", "float", "(", "self", ".", "total", ")", "freq", "=", "1", "if", "isinstance", "(", "segment", ",", "s...
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...
[ "Suggest", "word", "frequency", "to", "force", "the", "characters", "in", "a", "word", "to", "be", "joined", "or", "splitted", "." ]
8212b6c5725d08311952a3a08e5509eeaee33eb7
https://github.com/fxsjy/jieba/blob/8212b6c5725d08311952a3a08e5509eeaee33eb7/jieba/__init__.py#L424-L453
21,643
tensorflow/tensor2tensor
tensor2tensor/data_generators/allen_brain.py
_get_case_file_paths
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...
python
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...
[ "def", "_get_case_file_paths", "(", "tmp_dir", ",", "case", ",", "training_fraction", "=", "0.95", ")", ":", "paths", "=", "tf", ".", "gfile", ".", "Glob", "(", "\"%s/*.jpg\"", "%", "tmp_dir", ")", "if", "not", "paths", ":", "raise", "ValueError", "(", "...
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 ...
[ "Obtain", "a", "list", "of", "image", "paths", "corresponding", "to", "training", "or", "eval", "case", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/allen_brain.py#L81-L121
21,644
tensorflow/tensor2tensor
tensor2tensor/data_generators/allen_brain.py
maybe_download_image_dataset
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...
python
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...
[ "def", "maybe_download_image_dataset", "(", "image_ids", ",", "target_dir", ")", ":", "tf", ".", "gfile", ".", "MakeDirs", "(", "target_dir", ")", "num_images", "=", "len", "(", "image_ids", ")", "for", "i", ",", "image_id", "in", "enumerate", "(", "image_id...
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.
[ "Download", "a", "set", "of", "images", "from", "api", ".", "brain", "-", "map", ".", "org", "to", "target_dir", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/allen_brain.py#L124-L163
21,645
tensorflow/tensor2tensor
tensor2tensor/data_generators/allen_brain.py
random_square_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 =...
python
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 =...
[ "def", "random_square_mask", "(", "shape", ",", "fraction", ")", ":", "mask", "=", "np", ".", "ones", "(", "shape", ")", "patch_area", "=", "shape", "[", "0", "]", "*", "shape", "[", "1", "]", "*", "fraction", "patch_dim", "=", "np", ".", "int", "(...
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.
[ "Create", "a", "numpy", "array", "with", "specified", "shape", "and", "masked", "fraction", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/allen_brain.py#L166-L189
21,646
tensorflow/tensor2tensor
tensor2tensor/data_generators/allen_brain.py
_generator
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...
python
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...
[ "def", "_generator", "(", "tmp_dir", ",", "training", ",", "size", "=", "_BASE_EXAMPLE_IMAGE_SIZE", ",", "training_fraction", "=", "0.95", ")", ":", "maybe_download_image_dataset", "(", "_IMAGE_IDS", ",", "tmp_dir", ")", "image_files", "=", "_get_case_file_paths", "...
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...
[ "Base", "problem", "example", "generator", "for", "Allen", "Brain", "Atlas", "problems", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/allen_brain.py#L192-L260
21,647
tensorflow/tensor2tensor
tensor2tensor/models/research/transformer_moe.py
transformer_moe_2k
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: *...
python
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: *...
[ "def", "transformer_moe_2k", "(", ")", ":", "hparams", "=", "transformer_moe_8k", "(", ")", "hparams", ".", "batch_size", "=", "2048", "hparams", ".", "default_ff", "=", "\"sep\"", "# hparams.layer_types contains the network architecture:", "encoder_archi", "=", "\"a/a/...
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...
[ "Base", "transformers", "model", "with", "moe", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/transformer_moe.py#L365-L395
21,648
tensorflow/tensor2tensor
tensor2tensor/models/research/transformer_moe.py
transformer_moe_prepend_8k
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...
python
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...
[ "def", "transformer_moe_prepend_8k", "(", ")", ":", "hparams", "=", "transformer_moe_8k", "(", ")", "hparams", ".", "prepend_mode", "=", "\"prepend_inputs_masked_attention\"", "hparams", ".", "eval_drop_long_sequences", "=", "False", "hparams", ".", "max_input_seq_length"...
Model which formulate a seq2seq problem as language modeling.
[ "Model", "which", "formulate", "a", "seq2seq", "problem", "as", "language", "modeling", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/transformer_moe.py#L409-L418
21,649
tensorflow/tensor2tensor
tensor2tensor/models/revnet.py
f
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...
python
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...
[ "def", "f", "(", "x", ",", "depth1", ",", "depth2", ",", "dim", "=", "'2d'", ",", "first_batch_norm", "=", "True", ",", "stride", "=", "1", ",", "training", "=", "True", ",", "bottleneck", "=", "True", ",", "padding", "=", "'SAME'", ")", ":", "conv...
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...
[ "Applies", "residual", "function", "for", "RevNet", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/revnet.py#L72-L122
21,650
tensorflow/tensor2tensor
tensor2tensor/models/revnet.py
downsample_bottleneck
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...
python
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...
[ "def", "downsample_bottleneck", "(", "x", ",", "output_channels", ",", "dim", "=", "'2d'", ",", "stride", "=", "1", ",", "scope", "=", "'h'", ")", ":", "conv", "=", "CONFIG", "[", "dim", "]", "[", "'conv'", "]", "with", "tf", ".", "variable_scope", "...
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: ...
[ "Downsamples", "x", "by", "stride", "using", "a", "1x1", "convolution", "filter", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/revnet.py#L125-L144
21,651
tensorflow/tensor2tensor
tensor2tensor/models/revnet.py
downsample_residual
def downsample_residual(x, output_channels, dim='2d', stride=1, scope='h'): """Downsamples 'x' by `stride` using average pooling. 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 ...
python
def downsample_residual(x, output_channels, dim='2d', stride=1, scope='h'): """Downsamples 'x' by `stride` using average pooling. 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 ...
[ "def", "downsample_residual", "(", "x", ",", "output_channels", ",", "dim", "=", "'2d'", ",", "stride", "=", "1", ",", "scope", "=", "'h'", ")", ":", "with", "tf", ".", "variable_scope", "(", "scope", ")", ":", "if", "stride", ">", "1", ":", "avg_poo...
Downsamples 'x' by `stride` using average pooling. 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: A downsa...
[ "Downsamples", "x", "by", "stride", "using", "average", "pooling", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/revnet.py#L147-L175
21,652
tensorflow/tensor2tensor
tensor2tensor/models/revnet.py
init
def init(images, num_channels, dim='2d', stride=2, kernel_size=7, maxpool=True, training=True, scope='init'): """Standard ResNet initial block used as first RevNet block. Args: images: [N, H, W, 3] tensor of input images to the model. num_channels: Output depth of convolutional layer in initial bl...
python
def init(images, num_channels, dim='2d', stride=2, kernel_size=7, maxpool=True, training=True, scope='init'): """Standard ResNet initial block used as first RevNet block. Args: images: [N, H, W, 3] tensor of input images to the model. num_channels: Output depth of convolutional layer in initial bl...
[ "def", "init", "(", "images", ",", "num_channels", ",", "dim", "=", "'2d'", ",", "stride", "=", "2", ",", "kernel_size", "=", "7", ",", "maxpool", "=", "True", ",", "training", "=", "True", ",", "scope", "=", "'init'", ")", ":", "conv", "=", "CONFI...
Standard ResNet initial block used as first RevNet block. Args: images: [N, H, W, 3] tensor of input images to the model. num_channels: Output depth of convolutional layer in initial block. dim: '2d' if 2-dimensional, '3d' if 3-dimensional. stride: stride for the convolution and pool layer. kerne...
[ "Standard", "ResNet", "initial", "block", "used", "as", "first", "RevNet", "block", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/revnet.py#L178-L205
21,653
tensorflow/tensor2tensor
tensor2tensor/models/revnet.py
unit
def unit(x1, x2, block_num, depth, num_layers, dim='2d', bottleneck=True, first_batch_norm=True, stride=1, training=True): """Implements bottleneck RevNet unit from authors' RevNet architecture. Args: x1: [N, H, W, C] tensor of network activations. x2: [N, H, W, C] tensor of network activations. ...
python
def unit(x1, x2, block_num, depth, num_layers, dim='2d', bottleneck=True, first_batch_norm=True, stride=1, training=True): """Implements bottleneck RevNet unit from authors' RevNet architecture. Args: x1: [N, H, W, C] tensor of network activations. x2: [N, H, W, C] tensor of network activations. ...
[ "def", "unit", "(", "x1", ",", "x2", ",", "block_num", ",", "depth", ",", "num_layers", ",", "dim", "=", "'2d'", ",", "bottleneck", "=", "True", ",", "first_batch_norm", "=", "True", ",", "stride", "=", "1", ",", "training", "=", "True", ")", ":", ...
Implements bottleneck RevNet unit from authors' RevNet architecture. Args: x1: [N, H, W, C] tensor of network activations. x2: [N, H, W, C] tensor of network activations. block_num: integer ID of block depth: First depth in bottleneck residual unit. num_layers: Number of layers in the RevNet bloc...
[ "Implements", "bottleneck", "RevNet", "unit", "from", "authors", "RevNet", "architecture", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/revnet.py#L208-L258
21,654
tensorflow/tensor2tensor
tensor2tensor/models/revnet.py
final_block
def final_block(x1, x2, dim='2d', training=True, scope='final_block'): """Converts activations from last RevNet block to pre-logits. Args: x1: [NxHxWxC] tensor of network activations. x2: [NxHxWxC] tensor of network activations. dim: '2d' if 2-dimensional, '3d' if 3-dimensional. training: True for ...
python
def final_block(x1, x2, dim='2d', training=True, scope='final_block'): """Converts activations from last RevNet block to pre-logits. Args: x1: [NxHxWxC] tensor of network activations. x2: [NxHxWxC] tensor of network activations. dim: '2d' if 2-dimensional, '3d' if 3-dimensional. training: True for ...
[ "def", "final_block", "(", "x1", ",", "x2", ",", "dim", "=", "'2d'", ",", "training", "=", "True", ",", "scope", "=", "'final_block'", ")", ":", "# Final batch norm and relu", "with", "tf", ".", "variable_scope", "(", "scope", ")", ":", "y", "=", "tf", ...
Converts activations from last RevNet block to pre-logits. Args: x1: [NxHxWxC] tensor of network activations. x2: [NxHxWxC] tensor of network activations. dim: '2d' if 2-dimensional, '3d' if 3-dimensional. training: True for train phase, False for eval phase. scope: Optional variable scope for th...
[ "Converts", "activations", "from", "last", "RevNet", "block", "to", "pre", "-", "logits", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/revnet.py#L261-L285
21,655
tensorflow/tensor2tensor
tensor2tensor/models/revnet.py
revnet
def revnet(inputs, hparams, reuse=None): """Uses Tensor2Tensor memory optimized RevNet block to build a RevNet. Args: inputs: [NxHxWx3] tensor of input images to the model. hparams: HParams object that contains the following parameters, in addition to the parameters contained in the basic_params1() o...
python
def revnet(inputs, hparams, reuse=None): """Uses Tensor2Tensor memory optimized RevNet block to build a RevNet. Args: inputs: [NxHxWx3] tensor of input images to the model. hparams: HParams object that contains the following parameters, in addition to the parameters contained in the basic_params1() o...
[ "def", "revnet", "(", "inputs", ",", "hparams", ",", "reuse", "=", "None", ")", ":", "training", "=", "hparams", ".", "mode", "==", "tf", ".", "estimator", ".", "ModeKeys", ".", "TRAIN", "with", "tf", ".", "variable_scope", "(", "'RevNet'", ",", "reuse...
Uses Tensor2Tensor memory optimized RevNet block to build a RevNet. Args: inputs: [NxHxWx3] tensor of input images to the model. hparams: HParams object that contains the following parameters, in addition to the parameters contained in the basic_params1() object in the common_hparams module: ...
[ "Uses", "Tensor2Tensor", "memory", "optimized", "RevNet", "block", "to", "build", "a", "RevNet", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/revnet.py#L288-L335
21,656
tensorflow/tensor2tensor
tensor2tensor/models/revnet.py
revnet_base
def revnet_base(): """Default hparams for Revnet.""" hparams = common_hparams.basic_params1() hparams.add_hparam('num_channels', [64, 128, 256, 416]) hparams.add_hparam('num_layers_per_block', [1, 1, 10, 1]) hparams.add_hparam('bottleneck', True) hparams.add_hparam('first_batch_norm', [False, True, True, Tr...
python
def revnet_base(): """Default hparams for Revnet.""" hparams = common_hparams.basic_params1() hparams.add_hparam('num_channels', [64, 128, 256, 416]) hparams.add_hparam('num_layers_per_block', [1, 1, 10, 1]) hparams.add_hparam('bottleneck', True) hparams.add_hparam('first_batch_norm', [False, True, True, Tr...
[ "def", "revnet_base", "(", ")", ":", "hparams", "=", "common_hparams", ".", "basic_params1", "(", ")", "hparams", ".", "add_hparam", "(", "'num_channels'", ",", "[", "64", ",", "128", ",", "256", ",", "416", "]", ")", "hparams", ".", "add_hparam", "(", ...
Default hparams for Revnet.
[ "Default", "hparams", "for", "Revnet", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/revnet.py#L345-L378
21,657
tensorflow/tensor2tensor
tensor2tensor/models/revnet.py
revnet_range
def revnet_range(rhp): """Hyperparameters for tuning revnet.""" rhp.set_float('learning_rate', 0.05, 0.2, scale=rhp.LOG_SCALE) rhp.set_float('weight_decay', 1e-5, 1e-3, scale=rhp.LOG_SCALE) rhp.set_discrete('num_channels_init_block', [64, 128]) return rhp
python
def revnet_range(rhp): """Hyperparameters for tuning revnet.""" rhp.set_float('learning_rate', 0.05, 0.2, scale=rhp.LOG_SCALE) rhp.set_float('weight_decay', 1e-5, 1e-3, scale=rhp.LOG_SCALE) rhp.set_discrete('num_channels_init_block', [64, 128]) return rhp
[ "def", "revnet_range", "(", "rhp", ")", ":", "rhp", ".", "set_float", "(", "'learning_rate'", ",", "0.05", ",", "0.2", ",", "scale", "=", "rhp", ".", "LOG_SCALE", ")", "rhp", ".", "set_float", "(", "'weight_decay'", ",", "1e-5", ",", "1e-3", ",", "scal...
Hyperparameters for tuning revnet.
[ "Hyperparameters", "for", "tuning", "revnet", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/revnet.py#L435-L440
21,658
tensorflow/tensor2tensor
tensor2tensor/models/video/basic_deterministic_params.py
next_frame_basic_deterministic
def next_frame_basic_deterministic(): """Basic 2-frame conv model.""" hparams = base.next_frame_base() hparams.video_num_input_frames = 4 hparams.video_num_target_frames = 1 hparams.hidden_size = 64 hparams.batch_size = 4 hparams.num_hidden_layers = 2 hparams.optimizer = "Adafactor" hparams.learning_r...
python
def next_frame_basic_deterministic(): """Basic 2-frame conv model.""" hparams = base.next_frame_base() hparams.video_num_input_frames = 4 hparams.video_num_target_frames = 1 hparams.hidden_size = 64 hparams.batch_size = 4 hparams.num_hidden_layers = 2 hparams.optimizer = "Adafactor" hparams.learning_r...
[ "def", "next_frame_basic_deterministic", "(", ")", ":", "hparams", "=", "base", ".", "next_frame_base", "(", ")", "hparams", ".", "video_num_input_frames", "=", "4", "hparams", ".", "video_num_target_frames", "=", "1", "hparams", ".", "hidden_size", "=", "64", "...
Basic 2-frame conv model.
[ "Basic", "2", "-", "frame", "conv", "model", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/video/basic_deterministic_params.py#L27-L56
21,659
tensorflow/tensor2tensor
tensor2tensor/models/video/basic_deterministic_params.py
next_frame_pixel_noise
def next_frame_pixel_noise(): """Basic 2-frame conv model with pixel noise.""" hparams = next_frame_basic_deterministic() hparams.add_hparam("video_modality_input_noise", 0.05) hparams.bottom["inputs"] = modalities.video_pixel_noise_bottom hparams.top["inputs"] = modalities.video_top return hparams
python
def next_frame_pixel_noise(): """Basic 2-frame conv model with pixel noise.""" hparams = next_frame_basic_deterministic() hparams.add_hparam("video_modality_input_noise", 0.05) hparams.bottom["inputs"] = modalities.video_pixel_noise_bottom hparams.top["inputs"] = modalities.video_top return hparams
[ "def", "next_frame_pixel_noise", "(", ")", ":", "hparams", "=", "next_frame_basic_deterministic", "(", ")", "hparams", ".", "add_hparam", "(", "\"video_modality_input_noise\"", ",", "0.05", ")", "hparams", ".", "bottom", "[", "\"inputs\"", "]", "=", "modalities", ...
Basic 2-frame conv model with pixel noise.
[ "Basic", "2", "-", "frame", "conv", "model", "with", "pixel", "noise", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/video/basic_deterministic_params.py#L60-L66
21,660
tensorflow/tensor2tensor
tensor2tensor/models/video/basic_deterministic_params.py
next_frame_sampling
def next_frame_sampling(): """Basic conv model with scheduled sampling.""" hparams = next_frame_basic_deterministic() hparams.scheduled_sampling_mode = "prob_inverse_exp" hparams.scheduled_sampling_max_prob = 1.0 hparams.scheduled_sampling_decay_steps = 10000 return hparams
python
def next_frame_sampling(): """Basic conv model with scheduled sampling.""" hparams = next_frame_basic_deterministic() hparams.scheduled_sampling_mode = "prob_inverse_exp" hparams.scheduled_sampling_max_prob = 1.0 hparams.scheduled_sampling_decay_steps = 10000 return hparams
[ "def", "next_frame_sampling", "(", ")", ":", "hparams", "=", "next_frame_basic_deterministic", "(", ")", "hparams", ".", "scheduled_sampling_mode", "=", "\"prob_inverse_exp\"", "hparams", ".", "scheduled_sampling_max_prob", "=", "1.0", "hparams", ".", "scheduled_sampling_...
Basic conv model with scheduled sampling.
[ "Basic", "conv", "model", "with", "scheduled", "sampling", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/video/basic_deterministic_params.py#L79-L85
21,661
tensorflow/tensor2tensor
tensor2tensor/models/video/basic_deterministic_params.py
next_frame_ae
def next_frame_ae(): """Conv autoencoder.""" hparams = next_frame_basic_deterministic() hparams.bottom["inputs"] = modalities.video_bitwise_bottom hparams.top["inputs"] = modalities.video_top hparams.hidden_size = 256 hparams.batch_size = 8 hparams.num_hidden_layers = 4 hparams.num_compress_steps = 4 ...
python
def next_frame_ae(): """Conv autoencoder.""" hparams = next_frame_basic_deterministic() hparams.bottom["inputs"] = modalities.video_bitwise_bottom hparams.top["inputs"] = modalities.video_top hparams.hidden_size = 256 hparams.batch_size = 8 hparams.num_hidden_layers = 4 hparams.num_compress_steps = 4 ...
[ "def", "next_frame_ae", "(", ")", ":", "hparams", "=", "next_frame_basic_deterministic", "(", ")", "hparams", ".", "bottom", "[", "\"inputs\"", "]", "=", "modalities", ".", "video_bitwise_bottom", "hparams", ".", "top", "[", "\"inputs\"", "]", "=", "modalities",...
Conv autoencoder.
[ "Conv", "autoencoder", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/video/basic_deterministic_params.py#L96-L106
21,662
tensorflow/tensor2tensor
tensor2tensor/models/video/basic_deterministic_params.py
next_frame_ae_tiny
def next_frame_ae_tiny(): """Conv autoencoder, tiny set for testing.""" hparams = next_frame_tiny() hparams.bottom["inputs"] = modalities.video_bitwise_bottom hparams.top["inputs"] = modalities.video_top hparams.batch_size = 8 hparams.dropout = 0.4 return hparams
python
def next_frame_ae_tiny(): """Conv autoencoder, tiny set for testing.""" hparams = next_frame_tiny() hparams.bottom["inputs"] = modalities.video_bitwise_bottom hparams.top["inputs"] = modalities.video_top hparams.batch_size = 8 hparams.dropout = 0.4 return hparams
[ "def", "next_frame_ae_tiny", "(", ")", ":", "hparams", "=", "next_frame_tiny", "(", ")", "hparams", ".", "bottom", "[", "\"inputs\"", "]", "=", "modalities", ".", "video_bitwise_bottom", "hparams", ".", "top", "[", "\"inputs\"", "]", "=", "modalities", ".", ...
Conv autoencoder, tiny set for testing.
[ "Conv", "autoencoder", "tiny", "set", "for", "testing", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/video/basic_deterministic_params.py#L110-L117
21,663
tensorflow/tensor2tensor
tensor2tensor/models/video/basic_deterministic_params.py
next_frame_tiny
def next_frame_tiny(): """Tiny for testing.""" hparams = next_frame_basic_deterministic() hparams.hidden_size = 32 hparams.num_hidden_layers = 1 hparams.num_compress_steps = 2 hparams.filter_double_steps = 1 return hparams
python
def next_frame_tiny(): """Tiny for testing.""" hparams = next_frame_basic_deterministic() hparams.hidden_size = 32 hparams.num_hidden_layers = 1 hparams.num_compress_steps = 2 hparams.filter_double_steps = 1 return hparams
[ "def", "next_frame_tiny", "(", ")", ":", "hparams", "=", "next_frame_basic_deterministic", "(", ")", "hparams", ".", "hidden_size", "=", "32", "hparams", ".", "num_hidden_layers", "=", "1", "hparams", ".", "num_compress_steps", "=", "2", "hparams", ".", "filter_...
Tiny for testing.
[ "Tiny", "for", "testing", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/video/basic_deterministic_params.py#L129-L136
21,664
tensorflow/tensor2tensor
tensor2tensor/models/video/basic_deterministic_params.py
next_frame_l1
def next_frame_l1(): """Basic conv model with L1 modality.""" hparams = next_frame_basic_deterministic() hparams.loss["targets"] = modalities.video_l1_loss hparams.top["targets"] = modalities.video_l1_top hparams.video_modality_loss_cutoff = 2.4 return hparams
python
def next_frame_l1(): """Basic conv model with L1 modality.""" hparams = next_frame_basic_deterministic() hparams.loss["targets"] = modalities.video_l1_loss hparams.top["targets"] = modalities.video_l1_top hparams.video_modality_loss_cutoff = 2.4 return hparams
[ "def", "next_frame_l1", "(", ")", ":", "hparams", "=", "next_frame_basic_deterministic", "(", ")", "hparams", ".", "loss", "[", "\"targets\"", "]", "=", "modalities", ".", "video_l1_loss", "hparams", ".", "top", "[", "\"targets\"", "]", "=", "modalities", ".",...
Basic conv model with L1 modality.
[ "Basic", "conv", "model", "with", "L1", "modality", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/video/basic_deterministic_params.py#L140-L146
21,665
tensorflow/tensor2tensor
tensor2tensor/models/video/basic_deterministic_params.py
next_frame_l2
def next_frame_l2(): """Basic conv model with L2 modality.""" hparams = next_frame_basic_deterministic() hparams.loss["targets"] = modalities.video_l2_loss hparams.top["targets"] = modalities.video_l1_top hparams.video_modality_loss_cutoff = 2.4 return hparams
python
def next_frame_l2(): """Basic conv model with L2 modality.""" hparams = next_frame_basic_deterministic() hparams.loss["targets"] = modalities.video_l2_loss hparams.top["targets"] = modalities.video_l1_top hparams.video_modality_loss_cutoff = 2.4 return hparams
[ "def", "next_frame_l2", "(", ")", ":", "hparams", "=", "next_frame_basic_deterministic", "(", ")", "hparams", ".", "loss", "[", "\"targets\"", "]", "=", "modalities", ".", "video_l2_loss", "hparams", ".", "top", "[", "\"targets\"", "]", "=", "modalities", ".",...
Basic conv model with L2 modality.
[ "Basic", "conv", "model", "with", "L2", "modality", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/video/basic_deterministic_params.py#L150-L156
21,666
tensorflow/tensor2tensor
tensor2tensor/models/video/basic_deterministic_params.py
next_frame_base_range
def next_frame_base_range(rhp): """Basic tuning grid.""" rhp.set_float("dropout", 0.2, 0.6) rhp.set_discrete("hidden_size", [64, 128, 256]) rhp.set_int("num_compress_steps", 5, 8) rhp.set_discrete("batch_size", [4, 8, 16, 32]) rhp.set_int("num_hidden_layers", 1, 3) rhp.set_int("filter_double_steps", 1, 6)...
python
def next_frame_base_range(rhp): """Basic tuning grid.""" rhp.set_float("dropout", 0.2, 0.6) rhp.set_discrete("hidden_size", [64, 128, 256]) rhp.set_int("num_compress_steps", 5, 8) rhp.set_discrete("batch_size", [4, 8, 16, 32]) rhp.set_int("num_hidden_layers", 1, 3) rhp.set_int("filter_double_steps", 1, 6)...
[ "def", "next_frame_base_range", "(", "rhp", ")", ":", "rhp", ".", "set_float", "(", "\"dropout\"", ",", "0.2", ",", "0.6", ")", "rhp", ".", "set_discrete", "(", "\"hidden_size\"", ",", "[", "64", ",", "128", ",", "256", "]", ")", "rhp", ".", "set_int",...
Basic tuning grid.
[ "Basic", "tuning", "grid", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/video/basic_deterministic_params.py#L160-L170
21,667
tensorflow/tensor2tensor
tensor2tensor/models/video/basic_deterministic_params.py
next_frame_ae_range
def next_frame_ae_range(rhp): """Autoencoder world model tuning grid.""" rhp.set_float("dropout", 0.3, 0.5) rhp.set_int("num_compress_steps", 1, 3) rhp.set_int("num_hidden_layers", 2, 6) rhp.set_float("learning_rate_constant", 1., 2.) rhp.set_float("initializer_gain", 0.8, 1.5) rhp.set_int("filter_double_...
python
def next_frame_ae_range(rhp): """Autoencoder world model tuning grid.""" rhp.set_float("dropout", 0.3, 0.5) rhp.set_int("num_compress_steps", 1, 3) rhp.set_int("num_hidden_layers", 2, 6) rhp.set_float("learning_rate_constant", 1., 2.) rhp.set_float("initializer_gain", 0.8, 1.5) rhp.set_int("filter_double_...
[ "def", "next_frame_ae_range", "(", "rhp", ")", ":", "rhp", ".", "set_float", "(", "\"dropout\"", ",", "0.3", ",", "0.5", ")", "rhp", ".", "set_int", "(", "\"num_compress_steps\"", ",", "1", ",", "3", ")", "rhp", ".", "set_int", "(", "\"num_hidden_layers\""...
Autoencoder world model tuning grid.
[ "Autoencoder", "world", "model", "tuning", "grid", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/video/basic_deterministic_params.py#L194-L201
21,668
tensorflow/tensor2tensor
tensor2tensor/rl/trainer_model_free.py
initialize_env_specs
def initialize_env_specs(hparams, env_problem_name): """Initializes env_specs using the appropriate env.""" if env_problem_name: env = registry.env_problem(env_problem_name, batch_size=hparams.batch_size) else: env = rl_utils.setup_env(hparams, hparams.batch_size, hparams.eval...
python
def initialize_env_specs(hparams, env_problem_name): """Initializes env_specs using the appropriate env.""" if env_problem_name: env = registry.env_problem(env_problem_name, batch_size=hparams.batch_size) else: env = rl_utils.setup_env(hparams, hparams.batch_size, hparams.eval...
[ "def", "initialize_env_specs", "(", "hparams", ",", "env_problem_name", ")", ":", "if", "env_problem_name", ":", "env", "=", "registry", ".", "env_problem", "(", "env_problem_name", ",", "batch_size", "=", "hparams", ".", "batch_size", ")", "else", ":", "env", ...
Initializes env_specs using the appropriate env.
[ "Initializes", "env_specs", "using", "the", "appropriate", "env", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/rl/trainer_model_free.py#L68-L79
21,669
tensorflow/tensor2tensor
tensor2tensor/utils/learning_rate.py
learning_rate_factor
def learning_rate_factor(name, step_num, hparams): """Compute the designated learning rate factor from hparams.""" if name == "constant": tf.logging.info("Base learning rate: %f", hparams.learning_rate_constant) return hparams.learning_rate_constant elif name == "linear_warmup": return tf.minimum(1.0,...
python
def learning_rate_factor(name, step_num, hparams): """Compute the designated learning rate factor from hparams.""" if name == "constant": tf.logging.info("Base learning rate: %f", hparams.learning_rate_constant) return hparams.learning_rate_constant elif name == "linear_warmup": return tf.minimum(1.0,...
[ "def", "learning_rate_factor", "(", "name", ",", "step_num", ",", "hparams", ")", ":", "if", "name", "==", "\"constant\"", ":", "tf", ".", "logging", ".", "info", "(", "\"Base learning rate: %f\"", ",", "hparams", ".", "learning_rate_constant", ")", "return", ...
Compute the designated learning rate factor from hparams.
[ "Compute", "the", "designated", "learning", "rate", "factor", "from", "hparams", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/learning_rate.py#L26-L69
21,670
tensorflow/tensor2tensor
tensor2tensor/utils/learning_rate.py
learning_rate_schedule
def learning_rate_schedule(hparams): """Learning rate schedule based on hparams.""" mlperf_log.transformer_print(key=mlperf_log.OPT_LR, deferred=True) mlperf_log.transformer_print( key=mlperf_log.OPT_LR_WARMUP_STEPS, value=hparams.learning_rate_warmup_steps) step_num = _global_step(hparams) schedu...
python
def learning_rate_schedule(hparams): """Learning rate schedule based on hparams.""" mlperf_log.transformer_print(key=mlperf_log.OPT_LR, deferred=True) mlperf_log.transformer_print( key=mlperf_log.OPT_LR_WARMUP_STEPS, value=hparams.learning_rate_warmup_steps) step_num = _global_step(hparams) schedu...
[ "def", "learning_rate_schedule", "(", "hparams", ")", ":", "mlperf_log", ".", "transformer_print", "(", "key", "=", "mlperf_log", ".", "OPT_LR", ",", "deferred", "=", "True", ")", "mlperf_log", ".", "transformer_print", "(", "key", "=", "mlperf_log", ".", "OPT...
Learning rate schedule based on hparams.
[ "Learning", "rate", "schedule", "based", "on", "hparams", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/learning_rate.py#L72-L85
21,671
tensorflow/tensor2tensor
tensor2tensor/utils/learning_rate.py
legacy_learning_rate_schedule
def legacy_learning_rate_schedule(hparams): """Backwards-compatible learning-rate schedule.""" step_num = _global_step(hparams) warmup_steps = tf.to_float(hparams.learning_rate_warmup_steps) if hparams.learning_rate_decay_scheme == "noam": ret = 5000.0 * hparams.hidden_size**-0.5 * tf.minimum( (step...
python
def legacy_learning_rate_schedule(hparams): """Backwards-compatible learning-rate schedule.""" step_num = _global_step(hparams) warmup_steps = tf.to_float(hparams.learning_rate_warmup_steps) if hparams.learning_rate_decay_scheme == "noam": ret = 5000.0 * hparams.hidden_size**-0.5 * tf.minimum( (step...
[ "def", "legacy_learning_rate_schedule", "(", "hparams", ")", ":", "step_num", "=", "_global_step", "(", "hparams", ")", "warmup_steps", "=", "tf", ".", "to_float", "(", "hparams", ".", "learning_rate_warmup_steps", ")", "if", "hparams", ".", "learning_rate_decay_sch...
Backwards-compatible learning-rate schedule.
[ "Backwards", "-", "compatible", "learning", "-", "rate", "schedule", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/learning_rate.py#L88-L102
21,672
tensorflow/tensor2tensor
tensor2tensor/utils/learning_rate.py
_global_step
def _global_step(hparams): """Adjust global step if a multi-step optimizer is used.""" step = tf.to_float(tf.train.get_or_create_global_step()) multiplier = hparams.optimizer_multistep_accumulate_steps if not multiplier: return step tf.logging.info("Dividing global step by %d for multi-step optimizer." ...
python
def _global_step(hparams): """Adjust global step if a multi-step optimizer is used.""" step = tf.to_float(tf.train.get_or_create_global_step()) multiplier = hparams.optimizer_multistep_accumulate_steps if not multiplier: return step tf.logging.info("Dividing global step by %d for multi-step optimizer." ...
[ "def", "_global_step", "(", "hparams", ")", ":", "step", "=", "tf", ".", "to_float", "(", "tf", ".", "train", ".", "get_or_create_global_step", "(", ")", ")", "multiplier", "=", "hparams", ".", "optimizer_multistep_accumulate_steps", "if", "not", "multiplier", ...
Adjust global step if a multi-step optimizer is used.
[ "Adjust", "global", "step", "if", "a", "multi", "-", "step", "optimizer", "is", "used", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/learning_rate.py#L105-L114
21,673
tensorflow/tensor2tensor
tensor2tensor/utils/learning_rate.py
_piecewise_learning_rate
def _piecewise_learning_rate(step, boundaries, values): """Scale learning rate according to the given schedule. Multipliers are not cumulative. Args: step: global step boundaries: List of steps to transition on. values: Multiplier to apply at each boundary transition. Returns: Scaled value fo...
python
def _piecewise_learning_rate(step, boundaries, values): """Scale learning rate according to the given schedule. Multipliers are not cumulative. Args: step: global step boundaries: List of steps to transition on. values: Multiplier to apply at each boundary transition. Returns: Scaled value fo...
[ "def", "_piecewise_learning_rate", "(", "step", ",", "boundaries", ",", "values", ")", ":", "values", "=", "[", "1.0", "]", "+", "values", "boundaries", "=", "[", "float", "(", "x", ")", "for", "x", "in", "boundaries", "]", "return", "tf", ".", "train"...
Scale learning rate according to the given schedule. Multipliers are not cumulative. Args: step: global step boundaries: List of steps to transition on. values: Multiplier to apply at each boundary transition. Returns: Scaled value for the learning rate.
[ "Scale", "learning", "rate", "according", "to", "the", "given", "schedule", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/learning_rate.py#L122-L138
21,674
tensorflow/tensor2tensor
tensor2tensor/utils/learning_rate.py
_learning_rate_decay
def _learning_rate_decay(hparams, warmup_steps=0): """Learning rate decay multiplier.""" scheme = hparams.learning_rate_decay_scheme warmup_steps = tf.to_float(warmup_steps) global_step = _global_step(hparams) if not scheme or scheme == "none": return tf.constant(1.) tf.logging.info("Applying learning...
python
def _learning_rate_decay(hparams, warmup_steps=0): """Learning rate decay multiplier.""" scheme = hparams.learning_rate_decay_scheme warmup_steps = tf.to_float(warmup_steps) global_step = _global_step(hparams) if not scheme or scheme == "none": return tf.constant(1.) tf.logging.info("Applying learning...
[ "def", "_learning_rate_decay", "(", "hparams", ",", "warmup_steps", "=", "0", ")", ":", "scheme", "=", "hparams", ".", "learning_rate_decay_scheme", "warmup_steps", "=", "tf", ".", "to_float", "(", "warmup_steps", ")", "global_step", "=", "_global_step", "(", "h...
Learning rate decay multiplier.
[ "Learning", "rate", "decay", "multiplier", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/learning_rate.py#L141-L183
21,675
tensorflow/tensor2tensor
tensor2tensor/utils/learning_rate.py
_learning_rate_warmup
def _learning_rate_warmup(warmup_steps, warmup_schedule="exp", hparams=None): """Learning rate warmup multiplier.""" if not warmup_steps: return tf.constant(1.) tf.logging.info("Applying %s learning rate warmup for %d steps", warmup_schedule, warmup_steps) warmup_steps = tf.to_float(warm...
python
def _learning_rate_warmup(warmup_steps, warmup_schedule="exp", hparams=None): """Learning rate warmup multiplier.""" if not warmup_steps: return tf.constant(1.) tf.logging.info("Applying %s learning rate warmup for %d steps", warmup_schedule, warmup_steps) warmup_steps = tf.to_float(warm...
[ "def", "_learning_rate_warmup", "(", "warmup_steps", ",", "warmup_schedule", "=", "\"exp\"", ",", "hparams", "=", "None", ")", ":", "if", "not", "warmup_steps", ":", "return", "tf", ".", "constant", "(", "1.", ")", "tf", ".", "logging", ".", "info", "(", ...
Learning rate warmup multiplier.
[ "Learning", "rate", "warmup", "multiplier", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/learning_rate.py#L186-L202
21,676
tensorflow/tensor2tensor
tensor2tensor/data_generators/algorithmic_math.py
is_in_expr
def is_in_expr(expr, find): """Returns True if `find` is a subtree of `expr`.""" return expr == find or (isinstance(expr, ExprNode) and expr.is_in(find))
python
def is_in_expr(expr, find): """Returns True if `find` is a subtree of `expr`.""" return expr == find or (isinstance(expr, ExprNode) and expr.is_in(find))
[ "def", "is_in_expr", "(", "expr", ",", "find", ")", ":", "return", "expr", "==", "find", "or", "(", "isinstance", "(", "expr", ",", "ExprNode", ")", "and", "expr", ".", "is_in", "(", "find", ")", ")" ]
Returns True if `find` is a subtree of `expr`.
[ "Returns", "True", "if", "find", "is", "a", "subtree", "of", "expr", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/algorithmic_math.py#L90-L92
21,677
tensorflow/tensor2tensor
tensor2tensor/data_generators/algorithmic_math.py
random_expr_with_required_var
def random_expr_with_required_var(depth, required_var, optional_list, ops): """Generate a random expression tree with a required variable. The required variable appears exactly once in the expression. Args: depth: At least one leaf will be this many levels down from the top. required_var: A char. This c...
python
def random_expr_with_required_var(depth, required_var, optional_list, ops): """Generate a random expression tree with a required variable. The required variable appears exactly once in the expression. Args: depth: At least one leaf will be this many levels down from the top. required_var: A char. This c...
[ "def", "random_expr_with_required_var", "(", "depth", ",", "required_var", ",", "optional_list", ",", "ops", ")", ":", "if", "not", "depth", ":", "if", "required_var", ":", "return", "required_var", "return", "str", "(", "optional_list", "[", "random", ".", "r...
Generate a random expression tree with a required variable. The required variable appears exactly once in the expression. Args: depth: At least one leaf will be this many levels down from the top. required_var: A char. This char is guaranteed to be placed exactly once at a leaf somewhere in the tr...
[ "Generate", "a", "random", "expression", "tree", "with", "a", "required", "variable", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/algorithmic_math.py#L95-L129
21,678
tensorflow/tensor2tensor
tensor2tensor/data_generators/algorithmic_math.py
random_expr
def random_expr(depth, vlist, ops): """Generate a random expression tree. Args: depth: At least one leaf will be this many levels down from the top. vlist: A list of chars. These chars are randomly selected as leaf values. ops: A list of ExprOp instances. Returns: An ExprNode instance which is t...
python
def random_expr(depth, vlist, ops): """Generate a random expression tree. Args: depth: At least one leaf will be this many levels down from the top. vlist: A list of chars. These chars are randomly selected as leaf values. ops: A list of ExprOp instances. Returns: An ExprNode instance which is t...
[ "def", "random_expr", "(", "depth", ",", "vlist", ",", "ops", ")", ":", "if", "not", "depth", ":", "return", "str", "(", "vlist", "[", "random", ".", "randrange", "(", "len", "(", "vlist", ")", ")", "]", ")", "max_depth_side", "=", "random", ".", "...
Generate a random expression tree. Args: depth: At least one leaf will be this many levels down from the top. vlist: A list of chars. These chars are randomly selected as leaf values. ops: A list of ExprOp instances. Returns: An ExprNode instance which is the root of the generated expression tree.
[ "Generate", "a", "random", "expression", "tree", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/algorithmic_math.py#L132-L155
21,679
tensorflow/tensor2tensor
tensor2tensor/data_generators/algorithmic_math.py
algebra_inverse_solve
def algebra_inverse_solve(left, right, var, solve_ops): """Solves for the value of the given var in an expression. Args: left: The root of the ExprNode tree on the left side of the equals sign. right: The root of the ExprNode tree on the right side of the equals sign. var: A char. The variable to solve...
python
def algebra_inverse_solve(left, right, var, solve_ops): """Solves for the value of the given var in an expression. Args: left: The root of the ExprNode tree on the left side of the equals sign. right: The root of the ExprNode tree on the right side of the equals sign. var: A char. The variable to solve...
[ "def", "algebra_inverse_solve", "(", "left", ",", "right", ",", "var", ",", "solve_ops", ")", ":", "is_in_left", "=", "is_in_expr", "(", "left", ",", "var", ")", "is_in_right", "=", "is_in_expr", "(", "right", ",", "var", ")", "if", "is_in_left", "==", "...
Solves for the value of the given var in an expression. Args: left: The root of the ExprNode tree on the left side of the equals sign. right: The root of the ExprNode tree on the right side of the equals sign. var: A char. The variable to solve for. solve_ops: A dictionary with the following properti...
[ "Solves", "for", "the", "value", "of", "the", "given", "var", "in", "an", "expression", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/algorithmic_math.py#L158-L211
21,680
tensorflow/tensor2tensor
tensor2tensor/data_generators/algorithmic_math.py
format_sympy_expr
def format_sympy_expr(sympy_expr, functions=None): """Convert sympy expression into a string which can be encoded. Args: sympy_expr: Any sympy expression tree or string. functions: Defines special functions. A dict mapping human readable string names, like "log", "exp", "sin", "cos", etc., to singl...
python
def format_sympy_expr(sympy_expr, functions=None): """Convert sympy expression into a string which can be encoded. Args: sympy_expr: Any sympy expression tree or string. functions: Defines special functions. A dict mapping human readable string names, like "log", "exp", "sin", "cos", etc., to singl...
[ "def", "format_sympy_expr", "(", "sympy_expr", ",", "functions", "=", "None", ")", ":", "if", "functions", "is", "None", ":", "functions", "=", "{", "}", "str_expr", "=", "str", "(", "sympy_expr", ")", "result", "=", "str_expr", ".", "replace", "(", "\" ...
Convert sympy expression into a string which can be encoded. Args: sympy_expr: Any sympy expression tree or string. functions: Defines special functions. A dict mapping human readable string names, like "log", "exp", "sin", "cos", etc., to single chars. Each function gets a unique token, like...
[ "Convert", "sympy", "expression", "into", "a", "string", "which", "can", "be", "encoded", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/algorithmic_math.py#L214-L233
21,681
tensorflow/tensor2tensor
tensor2tensor/data_generators/algorithmic_math.py
generate_algebra_inverse_sample
def generate_algebra_inverse_sample(vlist, ops, solve_ops, min_depth, max_depth): """Randomly generate an algebra inverse dataset sample. Given an input equation and variable, produce the expression equal to the variable. Args: vlist: Variable list. List of chars that c...
python
def generate_algebra_inverse_sample(vlist, ops, solve_ops, min_depth, max_depth): """Randomly generate an algebra inverse dataset sample. Given an input equation and variable, produce the expression equal to the variable. Args: vlist: Variable list. List of chars that c...
[ "def", "generate_algebra_inverse_sample", "(", "vlist", ",", "ops", ",", "solve_ops", ",", "min_depth", ",", "max_depth", ")", ":", "side", "=", "random", ".", "randrange", "(", "2", ")", "left_depth", "=", "random", ".", "randrange", "(", "min_depth", "if",...
Randomly generate an algebra inverse dataset sample. Given an input equation and variable, produce the expression equal to the variable. Args: vlist: Variable list. List of chars that can be used in the expression. ops: List of ExprOp instances. The allowed operators for the expression. solve_ops: S...
[ "Randomly", "generate", "an", "algebra", "inverse", "dataset", "sample", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/algorithmic_math.py#L236-L274
21,682
tensorflow/tensor2tensor
tensor2tensor/data_generators/algorithmic_math.py
generate_algebra_simplify_sample
def generate_algebra_simplify_sample(vlist, ops, min_depth, max_depth): """Randomly generate an algebra simplify dataset sample. Given an input expression, produce the simplified expression. Args: vlist: Variable list. List of chars that can be used in the expression. ops: List of ExprOp instances. The ...
python
def generate_algebra_simplify_sample(vlist, ops, min_depth, max_depth): """Randomly generate an algebra simplify dataset sample. Given an input expression, produce the simplified expression. Args: vlist: Variable list. List of chars that can be used in the expression. ops: List of ExprOp instances. The ...
[ "def", "generate_algebra_simplify_sample", "(", "vlist", ",", "ops", ",", "min_depth", ",", "max_depth", ")", ":", "depth", "=", "random", ".", "randrange", "(", "min_depth", ",", "max_depth", "+", "1", ")", "expr", "=", "random_expr", "(", "depth", ",", "...
Randomly generate an algebra simplify dataset sample. Given an input expression, produce the simplified expression. Args: vlist: Variable list. List of chars that can be used in the expression. ops: List of ExprOp instances. The allowed operators for the expression. min_depth: Expression trees will no...
[ "Randomly", "generate", "an", "algebra", "simplify", "dataset", "sample", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/algorithmic_math.py#L277-L299
21,683
tensorflow/tensor2tensor
tensor2tensor/data_generators/algorithmic_math.py
generate_calculus_integrate_sample
def generate_calculus_integrate_sample(vlist, ops, min_depth, max_depth, functions): """Randomly generate a symbolic integral dataset sample. Given an input expression, produce the indefinite integral. Args: vlist: Variable list. List of chars that can be used in the e...
python
def generate_calculus_integrate_sample(vlist, ops, min_depth, max_depth, functions): """Randomly generate a symbolic integral dataset sample. Given an input expression, produce the indefinite integral. Args: vlist: Variable list. List of chars that can be used in the e...
[ "def", "generate_calculus_integrate_sample", "(", "vlist", ",", "ops", ",", "min_depth", ",", "max_depth", ",", "functions", ")", ":", "var_index", "=", "random", ".", "randrange", "(", "len", "(", "vlist", ")", ")", "var", "=", "vlist", "[", "var_index", ...
Randomly generate a symbolic integral dataset sample. Given an input expression, produce the indefinite integral. Args: vlist: Variable list. List of chars that can be used in the expression. ops: List of ExprOp instances. The allowed operators for the expression. min_depth: Expression trees will not ...
[ "Randomly", "generate", "a", "symbolic", "integral", "dataset", "sample", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/algorithmic_math.py#L302-L335
21,684
tensorflow/tensor2tensor
tensor2tensor/data_generators/algorithmic_math.py
algebra_inverse
def algebra_inverse(alphabet_size=26, min_depth=0, max_depth=2, nbr_cases=10000): """Generate the algebra inverse dataset. Each sample is a symbolic math equation involving unknown variables. The task is to solve for the given variable. The target is the resulting expression. Args: a...
python
def algebra_inverse(alphabet_size=26, min_depth=0, max_depth=2, nbr_cases=10000): """Generate the algebra inverse dataset. Each sample is a symbolic math equation involving unknown variables. The task is to solve for the given variable. The target is the resulting expression. Args: a...
[ "def", "algebra_inverse", "(", "alphabet_size", "=", "26", ",", "min_depth", "=", "0", ",", "max_depth", "=", "2", ",", "nbr_cases", "=", "10000", ")", ":", "if", "max_depth", "<", "min_depth", ":", "raise", "ValueError", "(", "\"max_depth must be greater than...
Generate the algebra inverse dataset. Each sample is a symbolic math equation involving unknown variables. The task is to solve for the given variable. The target is the resulting expression. Args: alphabet_size: How many possible variables there are. Max 52. min_depth: Minimum depth of the expression...
[ "Generate", "the", "algebra", "inverse", "dataset", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/algorithmic_math.py#L439-L477
21,685
tensorflow/tensor2tensor
tensor2tensor/data_generators/algorithmic_math.py
algebra_simplify
def algebra_simplify(alphabet_size=26, min_depth=0, max_depth=2, nbr_cases=10000): """Generate the algebra simplify dataset. Each sample is a symbolic math expression involving unknown variables. The task is to simplify the expression. The target is ...
python
def algebra_simplify(alphabet_size=26, min_depth=0, max_depth=2, nbr_cases=10000): """Generate the algebra simplify dataset. Each sample is a symbolic math expression involving unknown variables. The task is to simplify the expression. The target is ...
[ "def", "algebra_simplify", "(", "alphabet_size", "=", "26", ",", "min_depth", "=", "0", ",", "max_depth", "=", "2", ",", "nbr_cases", "=", "10000", ")", ":", "if", "max_depth", "<", "min_depth", ":", "raise", "ValueError", "(", "\"max_depth must be greater tha...
Generate the algebra simplify dataset. Each sample is a symbolic math expression involving unknown variables. The task is to simplify the expression. The target is the resulting expression. Args: alphabet_size: How many possible variables there are. Max 52. min_depth: Minimum depth of the expression tre...
[ "Generate", "the", "algebra", "simplify", "dataset", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/algorithmic_math.py#L480-L517
21,686
tensorflow/tensor2tensor
tensor2tensor/data_generators/algorithmic_math.py
calculus_integrate
def calculus_integrate(alphabet_size=26, min_depth=0, max_depth=2, nbr_cases=10000): """Generate the calculus integrate dataset. Each sample is a symbolic math expression involving unknown variables. The task is to take the indefinite integral ...
python
def calculus_integrate(alphabet_size=26, min_depth=0, max_depth=2, nbr_cases=10000): """Generate the calculus integrate dataset. Each sample is a symbolic math expression involving unknown variables. The task is to take the indefinite integral ...
[ "def", "calculus_integrate", "(", "alphabet_size", "=", "26", ",", "min_depth", "=", "0", ",", "max_depth", "=", "2", ",", "nbr_cases", "=", "10000", ")", ":", "if", "max_depth", "<", "min_depth", ":", "raise", "ValueError", "(", "\"max_depth must be greater t...
Generate the calculus integrate dataset. Each sample is a symbolic math expression involving unknown variables. The task is to take the indefinite integral of the expression. The target is the resulting expression. Args: alphabet_size: How many possible variables there are. Max 26. min_depth: Minimum ...
[ "Generate", "the", "calculus", "integrate", "dataset", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/algorithmic_math.py#L520-L573
21,687
tensorflow/tensor2tensor
tensor2tensor/data_generators/algorithmic_math.py
ExprNode.is_in
def is_in(self, expr): """Returns True if `expr` is a subtree.""" if expr == self: return True is_in_left = is_in_expr(self.left, expr) is_in_right = is_in_expr(self.right, expr) return is_in_left or is_in_right
python
def is_in(self, expr): """Returns True if `expr` is a subtree.""" if expr == self: return True is_in_left = is_in_expr(self.left, expr) is_in_right = is_in_expr(self.right, expr) return is_in_left or is_in_right
[ "def", "is_in", "(", "self", ",", "expr", ")", ":", "if", "expr", "==", "self", ":", "return", "True", "is_in_left", "=", "is_in_expr", "(", "self", ".", "left", ",", "expr", ")", "is_in_right", "=", "is_in_expr", "(", "self", ".", "right", ",", "exp...
Returns True if `expr` is a subtree.
[ "Returns", "True", "if", "expr", "is", "a", "subtree", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/algorithmic_math.py#L81-L87
21,688
tensorflow/tensor2tensor
tensor2tensor/data_generators/problem.py
preprocess_example_common
def preprocess_example_common(example, mode, hparams): """Preprocessing steps common to all models.""" if "inputs" in example and hparams.max_input_seq_length > 0: example["inputs"] = example["inputs"][:hparams.max_input_seq_length] if hparams.prepend_mode != "none": if mode == tf.estimator.ModeKeys.PREDI...
python
def preprocess_example_common(example, mode, hparams): """Preprocessing steps common to all models.""" if "inputs" in example and hparams.max_input_seq_length > 0: example["inputs"] = example["inputs"][:hparams.max_input_seq_length] if hparams.prepend_mode != "none": if mode == tf.estimator.ModeKeys.PREDI...
[ "def", "preprocess_example_common", "(", "example", ",", "mode", ",", "hparams", ")", ":", "if", "\"inputs\"", "in", "example", "and", "hparams", ".", "max_input_seq_length", ">", "0", ":", "example", "[", "\"inputs\"", "]", "=", "example", "[", "\"inputs\"", ...
Preprocessing steps common to all models.
[ "Preprocessing", "steps", "common", "to", "all", "models", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/problem.py#L142-L162
21,689
tensorflow/tensor2tensor
tensor2tensor/data_generators/problem.py
_copy_problem_hparams
def _copy_problem_hparams(p_hparams): """Use input modality, vocab, and space id for target.""" p = p_hparams # Duplicate input modality. p.modality["targets"] = p.modality["inputs"] # Duplicate input vocab size. p.vocab_size["targets"] = p.vocab_size["inputs"] # Duplicate input vocabulary. p.vocabulary...
python
def _copy_problem_hparams(p_hparams): """Use input modality, vocab, and space id for target.""" p = p_hparams # Duplicate input modality. p.modality["targets"] = p.modality["inputs"] # Duplicate input vocab size. p.vocab_size["targets"] = p.vocab_size["inputs"] # Duplicate input vocabulary. p.vocabulary...
[ "def", "_copy_problem_hparams", "(", "p_hparams", ")", ":", "p", "=", "p_hparams", "# Duplicate input modality.", "p", ".", "modality", "[", "\"targets\"", "]", "=", "p", ".", "modality", "[", "\"inputs\"", "]", "# Duplicate input vocab size.", "p", ".", "vocab_si...
Use input modality, vocab, and space id for target.
[ "Use", "input", "modality", "vocab", "and", "space", "id", "for", "target", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/problem.py#L947-L959
21,690
tensorflow/tensor2tensor
tensor2tensor/data_generators/problem.py
_default_hparams
def _default_hparams(): """A set of basic model hyperparameters.""" return hparam.HParams( # Use this parameter to get comparable perplexity numbers with different # tokenizations. This value should be set to the ratio of the number of # tokens in the test set according to the tokenization used t...
python
def _default_hparams(): """A set of basic model hyperparameters.""" return hparam.HParams( # Use this parameter to get comparable perplexity numbers with different # tokenizations. This value should be set to the ratio of the number of # tokens in the test set according to the tokenization used t...
[ "def", "_default_hparams", "(", ")", ":", "return", "hparam", ".", "HParams", "(", "# Use this parameter to get comparable perplexity numbers with different", "# tokenizations. This value should be set to the ratio of the number of", "# tokens in the test set according to the tokenization u...
A set of basic model hyperparameters.
[ "A", "set", "of", "basic", "model", "hyperparameters", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/problem.py#L1017-L1050
21,691
tensorflow/tensor2tensor
tensor2tensor/data_generators/problem.py
Problem.tpu_batch_size_per_shard
def tpu_batch_size_per_shard(self, model_hparams): """Batch size in examples per TPU core. Args: model_hparams: model hyperparameters Returns: an integer """ if self.batch_size_means_tokens and not model_hparams.use_fixed_batch_size: return model_hparams.batch_size // self.max_len...
python
def tpu_batch_size_per_shard(self, model_hparams): """Batch size in examples per TPU core. Args: model_hparams: model hyperparameters Returns: an integer """ if self.batch_size_means_tokens and not model_hparams.use_fixed_batch_size: return model_hparams.batch_size // self.max_len...
[ "def", "tpu_batch_size_per_shard", "(", "self", ",", "model_hparams", ")", ":", "if", "self", ".", "batch_size_means_tokens", "and", "not", "model_hparams", ".", "use_fixed_batch_size", ":", "return", "model_hparams", ".", "batch_size", "//", "self", ".", "max_lengt...
Batch size in examples per TPU core. Args: model_hparams: model hyperparameters Returns: an integer
[ "Batch", "size", "in", "examples", "per", "TPU", "core", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/problem.py#L272-L283
21,692
tensorflow/tensor2tensor
tensor2tensor/data_generators/problem.py
Problem.preprocess
def preprocess(self, dataset, mode, hparams, interleave=True): """Runtime preprocessing on the whole dataset. Return a tf.data.Datset -- the preprocessed version of the given one. By default this function calls preprocess_example. Args: dataset: the Dataset of already decoded but not yet preproc...
python
def preprocess(self, dataset, mode, hparams, interleave=True): """Runtime preprocessing on the whole dataset. Return a tf.data.Datset -- the preprocessed version of the given one. By default this function calls preprocess_example. Args: dataset: the Dataset of already decoded but not yet preproc...
[ "def", "preprocess", "(", "self", ",", "dataset", ",", "mode", ",", "hparams", ",", "interleave", "=", "True", ")", ":", "def", "_preprocess", "(", "example", ")", ":", "examples", "=", "self", ".", "preprocess_example", "(", "example", ",", "mode", ",",...
Runtime preprocessing on the whole dataset. Return a tf.data.Datset -- the preprocessed version of the given one. By default this function calls preprocess_example. Args: dataset: the Dataset of already decoded but not yet preprocessed features. mode: tf.estimator.ModeKeys hparams: HPara...
[ "Runtime", "preprocessing", "on", "the", "whole", "dataset", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/problem.py#L395-L425
21,693
tensorflow/tensor2tensor
tensor2tensor/data_generators/problem.py
Problem.filepattern
def filepattern(self, data_dir, mode, shard=None): """Get filepattern for data files for mode. Matches mode to a suffix. * DatasetSplit.TRAIN: train * DatasetSplit.EVAL: dev * DatasetSplit.TEST: test * tf.estimator.ModeKeys.PREDICT: dev Args: data_dir: str, data directory. mode...
python
def filepattern(self, data_dir, mode, shard=None): """Get filepattern for data files for mode. Matches mode to a suffix. * DatasetSplit.TRAIN: train * DatasetSplit.EVAL: dev * DatasetSplit.TEST: test * tf.estimator.ModeKeys.PREDICT: dev Args: data_dir: str, data directory. mode...
[ "def", "filepattern", "(", "self", ",", "data_dir", ",", "mode", ",", "shard", "=", "None", ")", ":", "path", "=", "os", ".", "path", ".", "join", "(", "data_dir", ",", "self", ".", "dataset_filename", "(", ")", ")", "shard_str", "=", "\"-%05d\"", "%...
Get filepattern for data files for mode. Matches mode to a suffix. * DatasetSplit.TRAIN: train * DatasetSplit.EVAL: dev * DatasetSplit.TEST: test * tf.estimator.ModeKeys.PREDICT: dev Args: data_dir: str, data directory. mode: DatasetSplit shard: int, if provided, will only re...
[ "Get", "filepattern", "for", "data", "files", "for", "mode", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/problem.py#L458-L485
21,694
tensorflow/tensor2tensor
tensor2tensor/data_generators/problem.py
Problem.maybe_reverse_features
def maybe_reverse_features(self, feature_map): """Reverse features between inputs and targets if the problem is '_rev'.""" if not self._was_reversed: return inputs = feature_map.pop("inputs", None) targets = feature_map.pop("targets", None) inputs_seg = feature_map.pop("inputs_segmentation", N...
python
def maybe_reverse_features(self, feature_map): """Reverse features between inputs and targets if the problem is '_rev'.""" if not self._was_reversed: return inputs = feature_map.pop("inputs", None) targets = feature_map.pop("targets", None) inputs_seg = feature_map.pop("inputs_segmentation", N...
[ "def", "maybe_reverse_features", "(", "self", ",", "feature_map", ")", ":", "if", "not", "self", ".", "_was_reversed", ":", "return", "inputs", "=", "feature_map", ".", "pop", "(", "\"inputs\"", ",", "None", ")", "targets", "=", "feature_map", ".", "pop", ...
Reverse features between inputs and targets if the problem is '_rev'.
[ "Reverse", "features", "between", "inputs", "and", "targets", "if", "the", "problem", "is", "_rev", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/problem.py#L544-L565
21,695
tensorflow/tensor2tensor
tensor2tensor/data_generators/problem.py
Problem.dataset
def dataset(self, mode, data_dir=None, num_threads=None, output_buffer_size=None, shuffle_files=None, hparams=None, preprocess=True, dataset_split=None, shard=None, partition_id=0,...
python
def dataset(self, mode, data_dir=None, num_threads=None, output_buffer_size=None, shuffle_files=None, hparams=None, preprocess=True, dataset_split=None, shard=None, partition_id=0,...
[ "def", "dataset", "(", "self", ",", "mode", ",", "data_dir", "=", "None", ",", "num_threads", "=", "None", ",", "output_buffer_size", "=", "None", ",", "shuffle_files", "=", "None", ",", "hparams", "=", "None", ",", "preprocess", "=", "True", ",", "datas...
Build a Dataset for this problem. Args: mode: tf.estimator.ModeKeys; determines which files to read from. data_dir: directory that contains data files. num_threads: int, number of threads to use for decode and preprocess Dataset.map calls. output_buffer_size: int, how many elements ...
[ "Build", "a", "Dataset", "for", "this", "problem", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/problem.py#L583-L698
21,696
tensorflow/tensor2tensor
tensor2tensor/data_generators/problem.py
Problem.decode_example
def decode_example(self, serialized_example): """Return a dict of Tensors from a serialized tensorflow.Example.""" data_fields, data_items_to_decoders = self.example_reading_spec() # Necessary to rejoin examples in the correct order with the Cloud ML Engine # batch prediction API. data_fields["batch...
python
def decode_example(self, serialized_example): """Return a dict of Tensors from a serialized tensorflow.Example.""" data_fields, data_items_to_decoders = self.example_reading_spec() # Necessary to rejoin examples in the correct order with the Cloud ML Engine # batch prediction API. data_fields["batch...
[ "def", "decode_example", "(", "self", ",", "serialized_example", ")", ":", "data_fields", ",", "data_items_to_decoders", "=", "self", ".", "example_reading_spec", "(", ")", "# Necessary to rejoin examples in the correct order with the Cloud ML Engine", "# batch prediction API.", ...
Return a dict of Tensors from a serialized tensorflow.Example.
[ "Return", "a", "dict", "of", "Tensors", "from", "a", "serialized", "tensorflow", ".", "Example", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/problem.py#L700-L717
21,697
tensorflow/tensor2tensor
tensor2tensor/data_generators/problem.py
Problem.make_estimator_input_fn
def make_estimator_input_fn(self, mode, hparams, data_dir=None, force_repeat=False, prevent_repeat=False, dataset_kwargs=None): """Retur...
python
def make_estimator_input_fn(self, mode, hparams, data_dir=None, force_repeat=False, prevent_repeat=False, dataset_kwargs=None): """Retur...
[ "def", "make_estimator_input_fn", "(", "self", ",", "mode", ",", "hparams", ",", "data_dir", "=", "None", ",", "force_repeat", "=", "False", ",", "prevent_repeat", "=", "False", ",", "dataset_kwargs", "=", "None", ")", ":", "def", "estimator_input_fn", "(", ...
Return input_fn wrapped for Estimator.
[ "Return", "input_fn", "wrapped", "for", "Estimator", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/problem.py#L771-L791
21,698
tensorflow/tensor2tensor
tensor2tensor/data_generators/problem.py
Problem._dataset_partition
def _dataset_partition(self, mode, config, params): """Which part of the training data to read. If there are multiple parallel calls to input_fn (multiple TPU hosts), then we want each one to read from a separate partition of the training data. Args: mode: tf.estimator.ModeKeys config:...
python
def _dataset_partition(self, mode, config, params): """Which part of the training data to read. If there are multiple parallel calls to input_fn (multiple TPU hosts), then we want each one to read from a separate partition of the training data. Args: mode: tf.estimator.ModeKeys config:...
[ "def", "_dataset_partition", "(", "self", ",", "mode", ",", "config", ",", "params", ")", ":", "if", "mode", "!=", "tf", ".", "estimator", ".", "ModeKeys", ".", "TRAIN", "or", "not", "hasattr", "(", "config", ",", "\"tpu_config\"", ")", ":", "# Reset in ...
Which part of the training data to read. If there are multiple parallel calls to input_fn (multiple TPU hosts), then we want each one to read from a separate partition of the training data. Args: mode: tf.estimator.ModeKeys config: RunConfig params: A dict that contains parameters. ...
[ "Which", "part", "of", "the", "training", "data", "to", "read", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/problem.py#L793-L828
21,699
tensorflow/tensor2tensor
tensor2tensor/data_generators/problem.py
Problem.serving_input_fn
def serving_input_fn(self, hparams, decode_hparams=None, use_tpu=False): """Input fn for serving export, starting from serialized example.""" mode = tf.estimator.ModeKeys.PREDICT serialized_example = tf.placeholder( dtype=tf.string, shape=[None], name="serialized_example") dataset = tf.data.Data...
python
def serving_input_fn(self, hparams, decode_hparams=None, use_tpu=False): """Input fn for serving export, starting from serialized example.""" mode = tf.estimator.ModeKeys.PREDICT serialized_example = tf.placeholder( dtype=tf.string, shape=[None], name="serialized_example") dataset = tf.data.Data...
[ "def", "serving_input_fn", "(", "self", ",", "hparams", ",", "decode_hparams", "=", "None", ",", "use_tpu", "=", "False", ")", ":", "mode", "=", "tf", ".", "estimator", ".", "ModeKeys", ".", "PREDICT", "serialized_example", "=", "tf", ".", "placeholder", "...
Input fn for serving export, starting from serialized example.
[ "Input", "fn", "for", "serving", "export", "starting", "from", "serialized", "example", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/problem.py#L899-L930