text stringlengths 81 112k |
|---|
Create temporary files for filenames and rename on exit.
def _incomplete_files(filenames):
"""Create temporary files for filenames and rename on exit."""
tmp_files = [get_incomplete_path(f) for f in filenames]
try:
yield tmp_files
for tmp, output in zip(tmp_files, filenames):
tf.io.gfile.rename(tmp... |
Create temporary dir for dirname and rename on exit.
def incomplete_dir(dirname):
"""Create temporary dir for dirname and rename on exit."""
tmp_dir = get_incomplete_path(dirname)
tf.io.gfile.makedirs(tmp_dir)
try:
yield tmp_dir
tf.io.gfile.rename(tmp_dir, dirname)
finally:
if tf.io.gfile.exists(... |
Shuffle a single record file in memory.
def _shuffle_tfrecord(path, random_gen):
"""Shuffle a single record file in memory."""
# Read all records
record_iter = tf.compat.v1.io.tf_record_iterator(path)
all_records = [
r for r in utils.tqdm(
record_iter, desc="Reading...", unit=" examples", leave... |
Writes generated str records to output_files in round-robin order.
def _write_tfrecords_from_generator(generator, output_files, shuffle=True):
"""Writes generated str records to output_files in round-robin order."""
if do_files_exist(output_files):
raise ValueError(
"Pre-processed files already exists:... |
Write records from generator round-robin across writers.
def _round_robin_write(writers, generator):
"""Write records from generator round-robin across writers."""
for i, example in enumerate(utils.tqdm(
generator, unit=" examples", leave=False)):
writers[i % len(writers)].write(example) |
Single item to a tf.train.Feature.
def _item_to_tf_feature(item, key_name):
"""Single item to a tf.train.Feature."""
v = item
if isinstance(v, (list, tuple)) and not v:
raise ValueError(
"Feature {} received an empty list value, so is unable to infer the "
"feature type to record. To support ... |
Builds tf.train.Features from (string -> int/float/str list) dictionary.
def _dict_to_tf_features(example_dict):
"""Builds tf.train.Features from (string -> int/float/str list) dictionary."""
features = {k: _item_to_tf_feature(v, k) for k, v
in six.iteritems(example_dict)}
return tf.train.Features(... |
Wrapper around Tqdm which can be updated in threads.
Usage:
```
with utils.async_tqdm(...) as pbar:
# pbar can then be modified inside a thread
# pbar.update_total(3)
# pbar.update()
```
Args:
*args: args of tqdm
**kwargs: kwargs of tqdm
Yields:
pbar: Async pbar which can be shar... |
Increment total pbar value.
def update_total(self, n=1):
"""Increment total pbar value."""
with self._lock:
self._pbar.total += n
self.refresh() |
Increment current value.
def update(self, n=1):
"""Increment current value."""
with self._lock:
self._pbar.update(n)
self.refresh() |
Generate examples as dicts.
def _build_pcollection(self, pipeline, folder, split):
"""Generate examples as dicts."""
beam = tfds.core.lazy_imports.apache_beam
split_type = self.builder_config.split_type
filename = os.path.join(folder, "{}.tar.gz".format(split_type))
def _extract_data(inputs):
... |
Copy data read from src file obj to new file in dest_path.
def _copy(src_file, dest_path):
"""Copy data read from src file obj to new file in dest_path."""
tf.io.gfile.makedirs(os.path.dirname(dest_path))
with tf.io.gfile.GFile(dest_path, 'wb') as dest_file:
while True:
data = src_file.read(io.DEFAULT_... |
Iter over tar archive, yielding (path, object-like) tuples.
Args:
arch_f: File object of the archive to iterate.
gz: If True, open a gzip'ed archive.
stream: If True, open the archive in stream mode which allows for faster
processing and less temporary disk consumption, but random access to the
... |
Add a progression bar for the current extraction.
def tqdm(self):
"""Add a progression bar for the current extraction."""
with utils.async_tqdm(
total=0, desc='Extraction completed...', unit=' file') as pbar_path:
self._pbar_path = pbar_path
yield |
Returns `promise.Promise` => to_path.
def extract(self, path, extract_method, to_path):
"""Returns `promise.Promise` => to_path."""
self._pbar_path.update_total(1)
if extract_method not in _EXTRACT_METHODS:
raise ValueError('Unknown extraction method "%s".' % extract_method)
future = self._execut... |
Returns `to_path` once resource has been extracted there.
def _sync_extract(self, from_path, method, to_path):
"""Returns `to_path` once resource has been extracted there."""
to_path_tmp = '%s%s_%s' % (to_path, constants.INCOMPLETE_SUFFIX,
uuid.uuid4().hex)
try:
for pat... |
Convert a `TensorInfo` object into a feature proto object.
def to_serialized_field(tensor_info):
"""Convert a `TensorInfo` object into a feature proto object."""
# Select the type
dtype = tensor_info.dtype
# TODO(b/119937875): TF Examples proto only support int64, float32 and string
# This create limitation... |
Convert the given value to Feature if necessary.
def to_feature(value):
"""Convert the given value to Feature if necessary."""
if isinstance(value, FeatureConnector):
return value
elif utils.is_dtype(value): # tf.int32, tf.string,...
return Tensor(shape=(), dtype=tf.as_dtype(value))
elif isinstance(va... |
Decode the given feature from the tfexample_dict.
Args:
feature_k (str): Feature key in the tfexample_dict
feature (FeatureConnector): Connector object to use to decode the field
tfexample_dict (dict): Dict containing the data to decode.
Returns:
decoded_feature: The output of the feature.decode_e... |
Ensure the two list of keys matches.
def _assert_keys_match(keys1, keys2):
"""Ensure the two list of keys matches."""
if set(keys1) != set(keys2):
raise ValueError('{} {}'.format(list(keys1), list(keys2))) |
See base class for details.
def get_tensor_info(self):
"""See base class for details."""
return {
feature_key: feature.get_tensor_info()
for feature_key, feature in self._feature_dict.items()
} |
See base class for details.
def get_serialized_info(self):
"""See base class for details."""
# Flatten tf-example features dict
# Use NonMutableDict to ensure there is no collision between features keys
features_dict = utils.NonMutableDict()
for feature_key, feature in self._feature_dict.items():
... |
See base class for details.
def encode_example(self, example_dict):
"""See base class for details."""
# Flatten dict matching the tf-example features
# Use NonMutableDict to ensure there is no collision between features keys
tfexample_dict = utils.NonMutableDict()
# Iterate over example fields
... |
See base class for details.
def decode_example(self, tfexample_dict):
"""See base class for details."""
tensor_dict = {}
# Iterate over the Tensor dict keys
for feature_key, feature in six.iteritems(self._feature_dict):
decoded_feature = decode_single_feature_from_dict(
feature_k=featur... |
See base class for details.
def save_metadata(self, data_dir, feature_name=None):
"""See base class for details."""
# Recursively save all child features
for feature_key, feature in six.iteritems(self._feature_dict):
if feature_name:
feature_key = '-'.join((feature_name, feature_key))
f... |
See base class for details.
def encode_example(self, example_data):
"""See base class for details."""
np_dtype = np.dtype(self._dtype.as_numpy_dtype)
# Convert to numpy if possible
if not isinstance(example_data, np.ndarray):
example_data = np.array(example_data, dtype=np_dtype)
# Ensure the ... |
See base class for details.
def decode_example(self, tfexample_data):
"""See base class for details."""
# TODO(epot): Support dynamic shape
if self.shape.count(None) < 2:
# Restore the shape if possible. TF Example flattened it.
shape = [-1 if i is None else i for i in self.shape]
tfexamp... |
Unpack the celeba config file.
The file starts with the number of lines, and a header.
Afterwards, there is a configuration for each file: one per line.
Args:
file_path: Path to the file with the configuration.
Returns:
keys: names of the attributes
values: map from the file name to... |
Yields examples.
def _generate_examples(self, file_id, extracted_dirs):
"""Yields examples."""
filedir = os.path.join(extracted_dirs["img_align_celeba"],
"img_align_celeba")
img_list_path = extracted_dirs["list_eval_partition"]
landmarks_path = extracted_dirs["landmarks_celeb... |
Generate QuickDraw bitmap examples.
Given a list of file paths with data for each class label, generate examples
in a random order.
Args:
file_paths: (dict of {str: str}) the paths to files containing the data,
indexed by label.
Yields:
The QuickDraw examples, as defined... |
Attempt to import tensorflow, and ensure its version is sufficient.
Raises:
ImportError: if either tensorflow is not importable or its version is
inadequate.
def ensure_tf_install(): # pylint: disable=g-statement-before-imports
"""Attempt to import tensorflow, and ensure its version is sufficient.
Rai... |
Patch TF to maintain compatibility across versions.
def _patch_tf(tf):
"""Patch TF to maintain compatibility across versions."""
global TF_PATCH
if TF_PATCH:
return
v_1_12 = distutils.version.LooseVersion("1.12.0")
v_1_13 = distutils.version.LooseVersion("1.13.0")
v_2 = distutils.version.LooseVersion(... |
Monkey patch tf 1.12 so tfds can use it.
def _patch_for_tf1_12(tf):
"""Monkey patch tf 1.12 so tfds can use it."""
tf.io.gfile = tf.gfile
tf.io.gfile.copy = tf.gfile.Copy
tf.io.gfile.exists = tf.gfile.Exists
tf.io.gfile.glob = tf.gfile.Glob
tf.io.gfile.isdir = tf.gfile.IsDirectory
tf.io.gfile.listdir = t... |
Monkey patch tf 1.13 so tfds can use it.
def _patch_for_tf1_13(tf):
"""Monkey patch tf 1.13 so tfds can use it."""
if not hasattr(tf.io.gfile, "GFile"):
tf.io.gfile.GFile = tf.gfile.GFile
if not hasattr(tf, "nest"):
tf.nest = tf.contrib.framework.nest
if not hasattr(tf.compat, "v2"):
tf.compat.v2 =... |
Whether ds is a Dataset. Compatible across TF versions.
def is_dataset(ds):
"""Whether ds is a Dataset. Compatible across TF versions."""
import tensorflow as tf
from tensorflow_datasets.core.utils import py_utils
dataset_types = [tf.data.Dataset]
v1_ds = py_utils.rgetattr(tf, "compat.v1.data.Dataset", None)... |
This function returns the examples in the raw (text) form.
def _generate_examples(self, data_file):
"""This function returns the examples in the raw (text) form."""
with tf.io.gfile.GFile(data_file) as f:
reader = csv.DictReader(f, delimiter='\t', quoting=csv.QUOTE_NONE)
for row in reader:
... |
Generate mnli examples.
Args:
filepath: a string
Yields:
dictionaries containing "premise", "hypothesis" and "label" strings
def _generate_examples(self, filepath):
"""Generate mnli examples.
Args:
filepath: a string
Yields:
dictionaries containing "premise", "hypothesis... |
Returns SplitGenerators from the folder names.
def _split_generators(self, dl_manager):
"""Returns SplitGenerators from the folder names."""
# At data creation time, parse the folder to deduce number of splits,
# labels, image size,
# The splits correspond to the high level folders
split_names = l... |
Generate example for each image in the dict.
def _generate_examples(self, label_images):
"""Generate example for each image in the dict."""
for label, image_paths in label_images.items():
for image_path in image_paths:
yield {
"image": image_path,
"label": label,
... |
Create a new dataset from a template.
def create_dataset_file(root_dir, data):
"""Create a new dataset from a template."""
file_path = os.path.join(root_dir, '{dataset_type}', '{dataset_name}.py')
context = (
_HEADER + _DATASET_DEFAULT_IMPORTS + _CITATION
+ _DESCRIPTION + _DATASET_DEFAULTS
)
wit... |
Append the new dataset file to the __init__.py.
def add_the_init(root_dir, data):
"""Append the new dataset file to the __init__.py."""
init_file = os.path.join(root_dir, '{dataset_type}', '__init__.py')
context = (
'from tensorflow_datasets.{dataset_type}.{dataset_name} import '
'{dataset_cls} # {T... |
Generate examples as dicts.
Args:
filepath: `str` path of the file to process.
Yields:
Generator yielding the next samples
def _generate_examples(self, filepath):
"""Generate examples as dicts.
Args:
filepath: `str` path of the file to process.
Yields:
Generator yielding... |
Returns SplitGenerators.
def _split_generators(self, dl_manager):
"""Returns SplitGenerators."""
path = dl_manager.manual_dir
train_path = os.path.join(path, _TRAIN_DIR)
val_path = os.path.join(path, _VALIDATION_DIR)
if not tf.io.gfile.exists(train_path) or not tf.io.gfile.exists(val_path):
... |
Yields examples.
def _generate_examples(self, imgs_path, csv_path):
"""Yields examples."""
with tf.io.gfile.GFile(csv_path) as csv_f:
reader = csv.DictReader(csv_f)
# Get keys for each label from csv
label_keys = reader.fieldnames[5:]
data = []
for row in reader:
# Get ima... |
Construct a list of BuilderConfigs.
Construct a list of 60 Imagenet2012CorruptedConfig objects, corresponding to
the 12 corruption types, with each type having 5 severities.
Returns:
A list of 60 Imagenet2012CorruptedConfig objects.
def _make_builder_configs():
"""Construct a list of BuilderConfigs.
C... |
Return the validation split of ImageNet2012.
Args:
dl_manager: download manager object.
Returns:
validation split.
def _split_generators(self, dl_manager):
"""Return the validation split of ImageNet2012.
Args:
dl_manager: download manager object.
Returns:
validation spli... |
Generate corrupted imagenet validation data.
Apply corruptions to the raw images according to self.corruption_type.
Args:
archive: an iterator for the raw dataset.
labels: a dictionary that maps the file names to imagenet labels.
Yields:
dictionary with the file name, an image file obje... |
Return corrupted images.
Args:
x: numpy array, uncorrupted image.
Returns:
numpy array, corrupted images.
def _get_corrupted_example(self, x):
"""Return corrupted images.
Args:
x: numpy array, uncorrupted image.
Returns:
numpy array, corrupted images.
"""
corrupt... |
Ensure the shape1 match the pattern given by shape2.
Ex:
assert_shape_match((64, 64, 3), (None, None, 3))
Args:
shape1 (tuple): Static shape
shape2 (tuple): Dynamic shape (can contain None)
def assert_shape_match(shape1, shape2):
"""Ensure the shape1 match the pattern given by shape2.
Ex:
as... |
tf.Session, hiding GPUs.
def raw_nogpu_session(graph=None):
"""tf.Session, hiding GPUs."""
config = tf.compat.v1.ConfigProto(device_count={'GPU': 0})
return tf.compat.v1.Session(config=config, graph=graph) |
Eager-compatible Graph().as_default() yielding the graph.
def maybe_with_graph(graph=None, create_if_none=True):
"""Eager-compatible Graph().as_default() yielding the graph."""
if tf.executing_eagerly():
yield None
else:
if graph is None and create_if_none:
graph = tf.Graph()
if graph is None:... |
Execute the given TensorFlow function.
def run(self, fct, input_):
"""Execute the given TensorFlow function."""
# TF 2.0
if tf.executing_eagerly():
return fct(input_).numpy()
# TF 1.0
else:
# Should compile the function if this is the first time encountered
if not isinstance(input... |
Create a new graph for the given args.
def _build_graph_run(self, run_args):
"""Create a new graph for the given args."""
# Could try to use tfe.py_func(fct) but this would require knowing
# information about the signature of the function.
# Create a new graph:
with tf.Graph().as_default() as g:
... |
Create a unique signature for each fct/inputs.
def _build_signature(self, run_args):
"""Create a unique signature for each fct/inputs."""
return (id(run_args.fct), run_args.input.dtype, run_args.input.shape) |
Converts the given image into a dict convertible to tf example.
def encode_example(self, video_or_path_or_fobj):
"""Converts the given image into a dict convertible to tf example."""
if isinstance(video_or_path_or_fobj, six.string_types):
if not os.path.isfile(video_or_path_or_fobj):
_, video_tem... |
Generate rock, paper or scissors images and labels given the directory path.
Args:
archive: object that iterates over the zip.
Yields:
The image path and its corresponding label.
def _generate_examples(self, archive):
"""Generate rock, paper or scissors images and labels given the directory p... |
Generate features and target given the directory path.
Args:
file_path: path where the csv file is stored
Yields:
The features and the target
def _generate_examples(self, file_path):
"""Generate features and target given the directory path.
Args:
file_path: path where the csv file ... |
Strip ID 0 and decrement ids by 1.
def pad_decr(ids):
"""Strip ID 0 and decrement ids by 1."""
if len(ids) < 1:
return list(ids)
if not any(ids):
return [] # all padding.
idx = -1
while not ids[idx]:
idx -= 1
if idx == -1:
ids = ids
else:
ids = ids[:idx + 1]
return [i - 1 for i in ... |
Prepare reserved tokens and a regex for splitting them out of strings.
def _prepare_reserved_tokens(reserved_tokens):
"""Prepare reserved tokens and a regex for splitting them out of strings."""
reserved_tokens = [tf.compat.as_text(tok) for tok in reserved_tokens or []]
dups = _find_duplicates(reserved_tokens)
... |
Constructs compiled regex to parse out reserved tokens.
def _make_reserved_tokens_re(reserved_tokens):
"""Constructs compiled regex to parse out reserved tokens."""
if not reserved_tokens:
return None
escaped_tokens = [_re_escape(rt) for rt in reserved_tokens]
pattern = "(%s)" % "|".join(escaped_tokens)
... |
Writes lines to file prepended by header and metadata.
def write_lines_to_file(cls_name, filename, lines, metadata_dict):
"""Writes lines to file prepended by header and metadata."""
metadata_dict = metadata_dict or {}
header_line = "%s%s" % (_HEADER_PREFIX, cls_name)
metadata_line = "%s%s" % (_METADATA_PREFIX... |
Read lines from file, parsing out header and metadata.
def read_lines_from_file(cls_name, filename):
"""Read lines from file, parsing out header and metadata."""
with tf.io.gfile.GFile(filename, "rb") as f:
lines = [tf.compat.as_text(line)[:-1] for line in f]
header_line = "%s%s" % (_HEADER_PREFIX, cls_name)... |
Splits a string into tokens.
def tokenize(self, s):
"""Splits a string into tokens."""
s = tf.compat.as_text(s)
if self.reserved_tokens:
# First split out the reserved tokens
substrs = self._reserved_tokens_re.split(s)
else:
substrs = [s]
toks = []
for substr in substrs:
... |
Convert a python slice [15:50] into a list[bool] mask of 100 elements.
def slice_to_percent_mask(slice_value):
"""Convert a python slice [15:50] into a list[bool] mask of 100 elements."""
if slice_value is None:
slice_value = slice(None)
# Select only the elements of the slice
selected = set(list(range(100... |
Return the mapping shard_id=>num_examples, assuming round-robin.
def get_shard_id2num_examples(num_shards, total_num_examples):
"""Return the mapping shard_id=>num_examples, assuming round-robin."""
# TODO(b/130353071): This has the strong assumption that the shards have
# been written in a round-robin fashion. ... |
Return the list of offsets associated with each shards.
Args:
shard_id2num_examples: `list[int]`, mapping shard_id=>num_examples
Returns:
mask_offsets: `list[int]`, offset to skip for each of the shard
def compute_mask_offsets(shard_id2num_examples):
"""Return the list of offsets associated with each s... |
Check that the two split dicts have the same names and num_shards.
def check_splits_equals(splits1, splits2):
"""Check that the two split dicts have the same names and num_shards."""
if set(splits1) ^ set(splits2): # Name intersection should be null
return False
for _, (split1, split2) in utils.zip_dict(spl... |
Add the split info.
def add(self, split_info):
"""Add the split info."""
if split_info.name in self:
raise ValueError("Split {} already present".format(split_info.name))
# TODO(epot): Make sure this works with Named splits correctly.
super(SplitDict, self).__setitem__(split_info.name, split_info) |
Returns a new SplitDict initialized from the `repeated_split_infos`.
def from_proto(cls, repeated_split_infos):
"""Returns a new SplitDict initialized from the `repeated_split_infos`."""
split_dict = cls()
for split_info_proto in repeated_split_infos:
split_info = SplitInfo()
split_info.CopyFro... |
Returns a list of SplitInfo protos that we have.
def to_proto(self):
"""Returns a list of SplitInfo protos that we have."""
# Return the proto.SplitInfo, sorted by name
return sorted((s.get_proto() for s in self.values()), key=lambda s: s.name) |
This function returns the examples in the raw (text) form.
def _generate_examples(self, filepath):
"""This function returns the examples in the raw (text) form."""
logging.info("generating examples from = %s", filepath)
with tf.io.gfile.GFile(filepath) as f:
squad = json.load(f)
for article in ... |
This function returns the examples in the raw (text) form.
def _generate_examples(self, data_file):
"""This function returns the examples in the raw (text) form."""
target_language = self.builder_config.target_language
with tf.io.gfile.GFile(data_file) as f:
for i, line in enumerate(f):
line... |
Returns a decorator which prevents concurrent calls to functions.
Usage:
synchronized = build_synchronize_decorator()
@synchronized
def read_value():
...
@synchronized
def write_value(x):
...
Returns:
make_threadsafe (fct): The decorator which lock all functions to which it
... |
Returns file name of file at given url.
def get_file_name(url):
"""Returns file name of file at given url."""
return os.path.basename(urllib.parse.urlparse(url).path) or 'unknown_name' |
Make built-in Librispeech BuilderConfigs.
Uses 4 text encodings (plain text, bytes, subwords with 8k vocab, subwords
with 32k vocab) crossed with the data subsets (clean100, clean360, all).
Returns:
`list<tfds.audio.LibrispeechConfig>`
def _make_builder_configs():
"""Make built-in Librispeech BuilderConf... |
Walk a Librispeech directory and yield examples.
def _walk_librispeech_dir(directory):
"""Walk a Librispeech directory and yield examples."""
directory = os.path.join(directory, "LibriSpeech")
for path, _, files in tf.io.gfile.walk(directory):
if not files:
continue
transcript_file = [f for f in f... |
Returns download urls for this config.
def download_urls(self):
"""Returns download urls for this config."""
urls = {
tfds.Split.TRAIN: ["train_clean100"],
tfds.Split.VALIDATION: ["dev_clean"],
tfds.Split.TEST: ["test_clean"],
}
if self.data in ["all", "clean360"]:
urls[tf... |
Conversion class name string => integer.
def str2int(self, str_value):
"""Conversion class name string => integer."""
str_value = tf.compat.as_text(str_value)
if self._str2int:
return self._str2int[str_value]
# No names provided, try to integerize
failed_parse = False
try:
int_valu... |
Conversion integer => class name string.
def int2str(self, int_value):
"""Conversion integer => class name string."""
if self._int2str:
# Maybe should support batched np array/eager tensors, to allow things
# like
# out_ids = model(inputs)
# labels = cifar10.info.features['label'].int2s... |
See base class for details.
def save_metadata(self, data_dir, feature_name=None):
"""See base class for details."""
# Save names if defined
if self._str2int is not None:
names_filepath = _get_names_filepath(data_dir, feature_name)
_write_names_to_file(names_filepath, self.names) |
See base class for details.
def load_metadata(self, data_dir, feature_name=None):
"""See base class for details."""
# Restore names if defined
names_filepath = _get_names_filepath(data_dir, feature_name)
if tf.io.gfile.exists(names_filepath):
self.names = _load_names_from_file(names_filepath) |
Builds token counts from generator.
def _token_counts_from_generator(generator, max_chars, reserved_tokens):
"""Builds token counts from generator."""
reserved_tokens = list(reserved_tokens) + [_UNDERSCORE_REPLACEMENT]
tokenizer = text_encoder.Tokenizer(
alphanum_only=False, reserved_tokens=reserved_tokens... |
Validate arguments for SubwordTextEncoder.build_from_corpus.
def _validate_build_arguments(max_subword_length, reserved_tokens,
target_vocab_size):
"""Validate arguments for SubwordTextEncoder.build_from_corpus."""
if max_subword_length <= 0:
raise ValueError(
"max_subword... |
Prepare tokens for encoding.
Tokens followed by a single space have "_" appended and the single space token
is dropped.
If a token is _UNDERSCORE_REPLACEMENT, it is broken up into 2 tokens.
Args:
tokens: `list<str>`, tokens to prepare.
Returns:
`list<str>` prepared tokens.
def _prepare_tokens_for... |
Encodes text into a list of integers.
def encode(self, s):
"""Encodes text into a list of integers."""
s = tf.compat.as_text(s)
tokens = self._tokenizer.tokenize(s)
tokens = _prepare_tokens_for_encode(tokens)
ids = []
for token in tokens:
ids.extend(self._token_to_ids(token))
return t... |
Decodes a list of integers into text.
def decode(self, ids):
"""Decodes a list of integers into text."""
ids = text_encoder.pad_decr(ids)
subword_ids = ids
del ids
subwords = []
# Some ids correspond to bytes. Because unicode characters are composed of
# possibly multiple bytes, we attemp... |
Convert a single token to a list of integer ids.
def _token_to_ids(self, token):
"""Convert a single token to a list of integer ids."""
# Check cache
cache_location = hash(token) % self._cache_size
cache_key, cache_value = self._token_to_ids_cache[cache_location]
if cache_key == token:
return... |
Encode a single token byte-wise into integer ids.
def _byte_encode(self, token):
"""Encode a single token byte-wise into integer ids."""
# Vocab ids for all bytes follow ids for the subwords
offset = len(self._subwords)
if token == "_":
return [len(self._subwords) + ord(" ")]
return [i + offs... |
Converts a subword integer ID to a subword string.
def _id_to_subword(self, subword_id):
"""Converts a subword integer ID to a subword string."""
if subword_id < 0 or subword_id >= (self.vocab_size - 1):
raise ValueError("Received id %d which is invalid. Ids must be within "
"[0, %... |
Greedily split token into subwords.
def _token_to_subwords(self, token):
"""Greedily split token into subwords."""
subwords = []
start = 0
while start < len(token):
subword = None
for end in range(
min(len(token), start + self._max_subword_len), start, -1):
candidate = to... |
Initializes the encoder from a list of subwords.
def _init_from_list(self, subwords):
"""Initializes the encoder from a list of subwords."""
subwords = [tf.compat.as_text(s) for s in subwords if s]
self._subwords = subwords
# Note that internally everything is 0-indexed. Padding is dealt with at the
... |
Save the vocabulary to a file.
def save_to_file(self, filename_prefix):
"""Save the vocabulary to a file."""
# Wrap in single quotes to make it easier to see the full subword when
# it has spaces and make it easier to search with ctrl+f.
filename = self._filename(filename_prefix)
lines = ["'%s'" % ... |
Extracts list of subwords from file.
def load_from_file(cls, filename_prefix):
"""Extracts list of subwords from file."""
filename = cls._filename(filename_prefix)
lines, _ = cls._read_lines_from_file(filename)
# Strip wrapping single quotes
vocab_list = [line[1:-1] for line in lines]
return cl... |
Builds a `SubwordTextEncoder` based on the `corpus_generator`.
Args:
corpus_generator: generator yielding `str`, from which subwords will be
constructed.
target_vocab_size: `int`, approximate size of the vocabulary to create.
max_subword_length: `int`, maximum length of a subword. Note th... |
Generate features given the directory path.
Args:
file_path: path where the csv file is stored
Yields:
The features, per row.
def _generate_examples(self, file_path):
"""Generate features given the directory path.
Args:
file_path: path where the csv file is stored
Yields:
... |
Generate Cats vs Dogs images and labels given a directory path.
def _generate_examples(self, archive):
"""Generate Cats vs Dogs images and labels given a directory path."""
num_skipped = 0
for fname, fobj in archive:
res = _NAME_RE.match(fname)
if not res: # README file, ...
continue
... |
Loads a data chunk as specified by the paths.
Args:
dat_path: Path to dat file of the chunk.
cat_path: Path to cat file of the chunk.
info_path: Path to info file of the chunk.
Returns:
Tuple with the dat, cat, info_arrays.
def _load_chunk(dat_path, cat_path, info_path):
"""Loads a data chunk a... |
Reads and returns binary formatted matrix stored in filename.
The file format is described on the data set page:
https://cs.nyu.edu/~ylclab/data/norb-v1.0-small/
Args:
filename: String with path to the file.
Returns:
Numpy array contained in the file.
def read_binary_matrix(filename):
"""Reads and... |
Returns splits.
def _split_generators(self, dl_manager):
"""Returns splits."""
filenames = {
"training_dat": _TRAINING_URL_TEMPLATE.format(type="dat"),
"training_cat": _TRAINING_URL_TEMPLATE.format(type="cat"),
"training_info": _TRAINING_URL_TEMPLATE.format(type="info"),
"testin... |
Generate examples for the Smallnorb dataset.
Args:
dat_path: Path to dat file of the chunk.
cat_path: Path to cat file of the chunk.
info_path: Path to info file of the chunk.
Yields:
Dictionaries with images and the different labels.
def _generate_examples(self, dat_path, cat_path, i... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.