INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
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))
feature.save_metadata(data_dir... |
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 shape and dtype match
if ... |
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]
tfexample_data = tf.reshape(tfexampl... |
Unpack the celeba config file. | def _process_celeba_config_file(self, file_path):
"""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 ... |
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_celeba"]
attr_path ... |
Generate QuickDraw bitmap examples. | def _generate_examples(self, file_paths):
"""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.
... |
Attempt to import tensorflow and ensure its version is sufficient. | def ensure_tf_install(): # pylint: disable=g-statement-before-imports
"""Attempt to import tensorflow, and ensure its version is sufficient.
Raises:
ImportError: if either tensorflow is not importable or its version is
inadequate.
"""
try:
import tensorflow as tf
except ImportError:
# Print ... |
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("2.0.0")
tf_version = distutils.version.LooseVersio... |
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 = tf.gfile.ListDirectory
tf.io.gfile.makedi... |
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 = types.ModuleType("tf.compat.v2")
tf.c... |
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)
v2_ds = py_utils.rgetattr(tf, "compat.v2.data.Dataset"... |
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:
# Everything in the row except for 'talk_name' will be a tra... |
Generate mnli examples. | def _generate_examples(self, filepath):
"""Generate mnli examples.
Args:
filepath: a string
Yields:
dictionaries containing "premise", "hypothesis" and "label" strings
"""
for idx, line in enumerate(tf.io.gfile.GFile(filepath, "rb")):
if idx == 0:
continue # skip header
... |
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 = list_folders(dl_manager.manual_dir)
# Extrac... |
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
)
with gfile.GFile(file_path.format(**data),... |
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} # {TODO} Sort alphabetically\n'
)
with gfile.GFil... |
Generate examples as dicts. | def _generate_examples(self, filepath):
"""Generate examples as dicts.
Args:
filepath: `str` path of the file to process.
Yields:
Generator yielding the next samples
"""
with tf.io.gfile.GFile(filepath, "rb") as f:
data = tfds.core.lazy_imports.scipy.io.loadmat(f)
# Maybe sh... |
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):
msg = ("You must download ... |
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 image based on indica... |
Construct a list of BuilderConfigs. | def _make_builder_configs():
"""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.
"""
config_list = []
for each_corru... |
Return the validation split of ImageNet2012. | def _split_generators(self, dl_manager):
"""Return the validation split of ImageNet2012.
Args:
dl_manager: download manager object.
Returns:
validation split.
"""
splits = super(Imagenet2012Corrupted, self)._split_generators(dl_manager)
validation = splits[1]
return [validation... |
Generate corrupted imagenet validation data. | def _generate_examples_validation(self, archive, labels):
"""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.
... |
Return corrupted images. | def _get_corrupted_example(self, x):
"""Return corrupted images.
Args:
x: numpy array, uncorrupted image.
Returns:
numpy array, corrupted images.
"""
corruption_type = self.builder_config.corruption_type
severity = self.builder_config.severity
return {
'gaussian_noise'... |
Ensure the shape1 match the pattern given by shape2. | def assert_shape_match(shape1, shape2):
"""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)
"""
shape1 = tf.TensorShape(shape1)
shape2 = tf.TensorShape(s... |
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:
yield None
else:
with graph.as_default():
... |
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_, np.ndarray):
input_ = np.arra... |
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 placeholder
input_ =... |
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_temp_path = tempfile.mkstemp()
try:
tf.gfile.Copy(... |
Generate rock paper or scissors images and labels given the directory path. | def _generate_examples(self, archive):
"""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.
"""
for fname, fobj in archive:
res = _NAME_RE.match(fname... |
Generate features and target given the directory path. | def _generate_examples(self, file_path):
"""Generate features and target given the directory path.
Args:
file_path: path where the csv file is stored
Yields:
The features and the target
"""
with tf.io.gfile.GFile(file_path) as f:
raw_data = csv.DictReader(f)
for row in raw... |
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 ids] |
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)
if dups:
raise ValueError("Duplicates found in tokens: %s" % dups)
... |
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)
reserved_tokens_re = _re_compile(pattern)
return reserv... |
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,
json.dumps(metadata_dict, ... |
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)
if lines[0] != header_line:
raise ValueError("Fil... |
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:
if substr in self.reserved_... |
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))[slice_value])
# Create the binary mask
return [i in selected for ... |
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. This assumption does not hold, for
# instance, with Beam generat... |
Return the list of offsets associated with each shards. | def compute_mask_offsets(shard_id2num_examples):
"""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
"""
total_num_examples = sum(shard_id2num_exam... |
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(splits1, splits2):
if split1.num_shards != split2.num_shards:
... |
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.CopyFrom(split_info_proto)
split_dict.add(split_info)
return split_... |
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 squad["data"]:
if "title" in article:
titl... |
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_parts = line.strip().split("\t")
if len(line_parts)... |
Returns a decorator which prevents concurrent calls to functions. | def build_synchronize_decorator():
"""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 decorato... |
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. | def _make_builder_configs():
"""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>`
"""
text_encoder_configs = [
... |
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 files if f.endswith(".txt")]
if not transcript_... |
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[tfds.Split.TRAIN].append("train_clean360")... |
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_value = int(str_value)
except ValueError:
... |
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'].int2str(out_ids)
return self._int2str[int... |
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)
num_chars = 0
token_counts = co... |
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_length must be > 0. Note that memory and compute for "
... |
Prepare tokens for encoding. | def _prepare_tokens_for_encode(tokens):
"""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<st... |
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 text_encoder.pad_incr(ids) |
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 attempt to decode contiguous lists of bytes
... |
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 cache_value
subwords = self._token_to_subwor... |
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 + offset for i in list(bytearray(tf.compat.as_bytes(token... |
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, %d)." % (subword_id + 1, self.vocab_size))
if 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 = token[start:end]
if (candidate ... |
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
# end of encode and the beginning of decode.
... |
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'" % s for s in self._subwords]
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 cls(vocab_list=vocab_list) |
Builds a SubwordTextEncoder based on the corpus_generator. | def build_from_corpus(cls,
corpus_generator,
target_vocab_size,
max_subword_length=20,
max_corpus_chars=None,
reserved_tokens=None):
"""Builds a `SubwordTextEncoder` based on the `corpus_generator... |
Generate features given the directory path. | def _generate_examples(self, file_path):
"""Generate features given the directory path.
Args:
file_path: path where the csv file is stored
Yields:
The features, per row.
"""
fieldnames = [
'class_label', 'lepton_pT', 'lepton_eta', 'lepton_phi',
'missing_energy_magnitud... |
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
label = res.group(1).lower()
if tf.compat.as_bytes("JF... |
Loads a data chunk as specified by the paths. | def _load_chunk(dat_path, cat_path, info_path):
"""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.
"""
dat_array = r... |
Reads and returns binary formatted matrix stored in filename. | def read_binary_matrix(filename):
"""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.
"""
wi... |
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"),
"testing_dat": _TESTING_... |
Generate examples for the Smallnorb dataset. | def _generate_examples(self, dat_path, cat_path, info_path):
"""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 d... |
Constructs a tf. data. Dataset from TFRecord files. | def build_dataset(instruction_dicts,
dataset_from_file_fn,
shuffle_files=False,
parallel_reads=64):
"""Constructs a `tf.data.Dataset` from TFRecord files.
Args:
instruction_dicts: `list` of {'filepath':, 'mask':, 'offset_mask':}
containing the informa... |
Create a dataset containing individual instruction for each shard. | def _build_instruction_ds(instructions):
"""Create a dataset containing individual instruction for each shard.
Each instruction is a dict:
```
{
"filepath": tf.Tensor(shape=(), dtype=tf.string),
"mask_offset": tf.Tensor(shape=(), dtype=tf.int64),
"mask": tf.Tensor(shape=(100,), dtype=tf.bool)... |
Build the mask dataset to indicate which element to skip. | def _build_mask_ds(mask, mask_offset):
"""Build the mask dataset to indicate which element to skip.
Args:
mask: `tf.Tensor`, binary mask to apply to all following elements. This
mask should have a length 100.
mask_offset: `tf.Tensor`, Integer specifying from how much the mask
should be shifted ... |
Map an instruction to a real datasets for one particular shard. | def _build_ds_from_instruction(instruction, ds_from_file_fn):
"""Map an instruction to a real datasets for one particular shard.
Args:
instruction: A `dict` of `tf.Tensor` containing the instruction to load
the particular shard (filename, mask,...)
ds_from_file_fn: `fct`, function which returns the d... |
Converts a tf. data. Dataset to an iterable of NumPy arrays. | def as_numpy(dataset, graph=None):
"""Converts a `tf.data.Dataset` to an iterable of NumPy arrays.
`as_numpy` converts a possibly nested structure of `tf.data.Dataset`s
and `tf.Tensor`s to iterables of NumPy arrays and NumPy arrays, respectively.
Args:
dataset: a possibly nested structure of `tf.data.Data... |
Loads the images and latent values into Numpy arrays. | def _load_data(filepath):
"""Loads the images and latent values into Numpy arrays."""
with h5py.File(filepath, "r") as h5dataset:
image_array = np.array(h5dataset["images"])
# The 'label' data set in the hdf5 file actually contains the float values
# and not the class labels.
values_array = np.array... |
Discretizes array values to class labels. | def _discretize(a):
"""Discretizes array values to class labels."""
arr = np.asarray(a)
index = np.argsort(arr)
inverse_index = np.zeros(arr.size, dtype=np.intp)
inverse_index[index] = np.arange(arr.size, dtype=np.intp)
arr = arr[index]
obs = np.r_[True, arr[1:] != arr[:-1]]
return obs.cumsum()[inverse_... |
Generate examples for the Shapes3d dataset. | def _generate_examples(self, filepath):
"""Generate examples for the Shapes3d dataset.
Args:
filepath: path to the Shapes3d hdf5 file.
Yields:
Dictionaries with images and the different labels.
"""
# Simultaneously iterating through the different data sets in the hdf5
# file will b... |
Strips formatting and unwanted sections from raw page content. | def _parse_and_clean_wikicode(raw_content):
"""Strips formatting and unwanted sections from raw page content."""
wikicode = tfds.core.lazy_imports.mwparserfromhell.parse(raw_content)
# Filters for references, tables, and file/image links.
re_rm_wikilink = re.compile(
"^(?:File|Image|Media):", flags=re.IG... |
Build PCollection of examples in the raw ( text ) form. | def _build_pcollection(self, pipeline, filepaths, language):
"""Build PCollection of examples in the raw (text) form."""
beam = tfds.core.lazy_imports.apache_beam
def _extract_content(filepath):
"""Extracts article content from a single WikiMedia XML file."""
logging.info("generating examples ... |
Generate data for a given dataset. | def download_and_prepare(builder):
"""Generate data for a given dataset."""
print("download_and_prepare for dataset {}...".format(builder.info.full_name))
dl_config = download_config()
if isinstance(builder, tfds.core.BeamBasedBuilder):
beam = tfds.core.lazy_imports.apache_beam
# TODO(b/129149715): Re... |
See base class for details. | def encode_example(self, bbox):
"""See base class for details."""
# Validate the coordinates
for coordinate in bbox:
if not isinstance(coordinate, float):
raise ValueError(
'BBox coordinates should be float. Got {}.'.format(bbox))
if not 0.0 <= coordinate <= 1.0:
rais... |
Yields ( labels np_image ) tuples. | def _load_data(path, labels_number=1):
"""Yields (labels, np_image) tuples."""
with tf.io.gfile.GFile(path, "rb") as f:
data = f.read()
offset = 0
max_offset = len(data) - 1
while offset < max_offset:
labels = np.frombuffer(data, dtype=np.uint8, count=labels_number,
offset=o... |
Returns SplitGenerators. | def _split_generators(self, dl_manager):
"""Returns SplitGenerators."""
cifar_path = dl_manager.download_and_extract(self._cifar_info.url)
cifar_info = self._cifar_info
cifar_path = os.path.join(cifar_path, cifar_info.prefix)
# Load the label names
for label_key, label_file in zip(cifar_info.l... |
Generate CIFAR examples as dicts. | def _generate_examples(self, filepaths):
"""Generate CIFAR examples as dicts.
Shared across CIFAR-{10, 100}. Uses self._cifar_info as
configuration.
Args:
filepaths (list[str]): The files to use to generate the data.
Yields:
The cifar examples, as defined in the dataset info features.... |
Requires function to be called using keyword arguments. | def disallow_positional_args(wrapped=None, allowed=None):
"""Requires function to be called using keyword arguments."""
# See
# https://wrapt.readthedocs.io/en/latest/decorators.html#decorators-with-optional-arguments
# for decorator pattern.
if wrapped is None:
return functools.partial(disallow_positiona... |
Returns arguments of fn with default = REQUIRED_ARG. | def _required_args(fn):
"""Returns arguments of fn with default=REQUIRED_ARG."""
spec = getargspec(fn)
if not spec.defaults:
return []
arg_names = spec.args[-len(spec.defaults):]
return [name for name, val in zip(arg_names, spec.defaults)
if val is REQUIRED_ARG] |
Download a file from GCS optionally to a file. | def download_gcs_file(path, out_fname=None, prefix_filter=None):
"""Download a file from GCS, optionally to a file."""
url = posixpath.join(GCS_BUCKET, path)
if prefix_filter:
url += "?prefix=%s" % prefix_filter
stream = bool(out_fname)
resp = requests.get(url, stream=stream)
if not resp.ok:
raise V... |
List all files in GCS bucket. | def gcs_files(prefix_filter=None):
"""List all files in GCS bucket."""
top_level_xml_str = download_gcs_file("", prefix_filter=prefix_filter)
xml_root = ElementTree.fromstring(top_level_xml_str)
filenames = [el[0].text for el in xml_root if el.tag.endswith("Contents")]
return filenames |
Return paths to GCS files in the given dataset directory. | def gcs_dataset_info_files(dataset_dir):
"""Return paths to GCS files in the given dataset directory."""
prefix = posixpath.join(GCS_DATASET_INFO_DIR, dataset_dir, "")
# Filter for this dataset
filenames = [el for el in gcs_files(prefix_filter=prefix)
if el.startswith(prefix) and len(el) > len(pr... |
If the dataset is available on the GCS bucket gs:// tfds - data/ datasets. | def is_dataset_on_gcs(dataset_name):
"""If the dataset is available on the GCS bucket gs://tfds-data/datasets."""
dir_name = posixpath.join(GCS_DATASETS_DIR, dataset_name)
return len(gcs_files(prefix_filter=dir_name)) > 2 |
Run kaggle command with subprocess. | def _run_kaggle_command(command_args, competition_name):
"""Run kaggle command with subprocess."""
try:
output = sp.check_output(command_args)
return tf.compat.as_text(output)
except sp.CalledProcessError as err:
output = err.output
_log_command_output(output, error=True)
if output.startswith(... |
List of competition files. | def competition_files(self):
"""List of competition files."""
command = [
"kaggle",
"datasets" if "/" in self._competition_name else "competitions",
"files",
"-v",
self._competition_name,
]
output = _run_kaggle_command(command, self._competition_name)
return s... |
Returns kaggle:// urls. | def competition_urls(self):
"""Returns 'kaggle://' urls."""
return [
KaggleFile(self._competition_name, fname).to_url()
for fname in self.competition_files # pylint: disable=not-an-iterable
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.