INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Zip data struct together and return a data struct with the same shape.
def zip_nested(arg0, *args, **kwargs): """Zip data struct together and return a data struct with the same shape.""" # Python 2 do not support kwargs only arguments dict_only = kwargs.pop("dict_only", False) assert not kwargs # Could add support for more exotic data_struct, like OrderedDict if isinstance(ar...
Simulate proto inheritance. By default, protobuf do not support direct inheritance, so this decorator simulates inheritance to the class to which it is applied. Example: ``` @as_proto_class(proto.MyProto) class A(object): def custom_method(self): return self.proto_field * 10 p = proto.MyProt...
def as_proto_cls(proto_cls): """Simulate proto inheritance. By default, protobuf do not support direct inheritance, so this decorator simulates inheritance to the class to which it is applied. Example: ``` @as_proto_class(proto.MyProto) class A(object): def custom_method(self): return self.pr...
Path to tensorflow_datasets directory.
def tfds_dir(): """Path to tensorflow_datasets directory.""" return os.path.dirname(os.path.dirname(os.path.dirname(__file__)))
Writes to path atomically, by writing to temp file and renaming it.
def atomic_write(path, mode): """Writes to path atomically, by writing to temp file and renaming it.""" tmp_path = "%s%s_%s" % (path, constants.INCOMPLETE_SUFFIX, uuid.uuid4().hex) with tf.io.gfile.GFile(tmp_path, mode) as file_: yield file_ tf.io.gfile.rename(tmp_path, path, overwrite=True)
Given a hash constructor, returns checksum digest and size of file.
def read_checksum_digest(path, checksum_cls=hashlib.sha256): """Given a hash constructor, returns checksum digest and size of file.""" checksum = checksum_cls() size = 0 with tf.io.gfile.GFile(path, "rb") as f: while True: block = f.read(io.DEFAULT_BUFFER_SIZE) size += len(block) if not bl...
Reraise an exception with an additional message.
def reraise(additional_msg): """Reraise an exception with an additional message.""" exc_type, exc_value, exc_traceback = sys.exc_info() msg = str(exc_value) + "\n" + additional_msg six.reraise(exc_type, exc_type(msg), exc_traceback)
Get attr that handles dots in attr name.
def rgetattr(obj, attr, *args): """Get attr that handles dots in attr name.""" def _getattr(obj, attr): return getattr(obj, attr, *args) return functools.reduce(_getattr, [obj] + attr.split("."))
Returns SplitGenerators.
def _split_generators(self, dl_manager): """Returns SplitGenerators.""" image_tar_file = os.path.join(dl_manager.manual_dir, self.builder_config.file_name) if not tf.io.gfile.exists(image_tar_file): # The current celebahq generation code depends on a concrete version ...
This function returns the examples in the raw (text) form.
def _generate_examples(self, source_file, target_file): """This function returns the examples in the raw (text) form.""" with tf.io.gfile.GFile(source_file) as f: source_sentences = f.read().split("\n") with tf.io.gfile.GFile(target_file) as f: target_sentences = f.read().split("\n") assert...
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.""" rows_per_pair_id = collections.defaultdict(list) with tf.io.gfile.GFile(filepath) as f: reader = csv.DictReader(f, delimiter='\t', quoting=csv.QUOTE_NONE) for row in reader: rows_per...
Yields examples.
def _generate_example(self, data_path, image_id): """Yields examples.""" image_filepath = os.path.join( data_path, "VOCdevkit/VOC2007/JPEGImages", "{}.jpg".format(image_id)) annon_filepath = os.path.join( data_path, "VOCdevkit/VOC2007/Annotations", "{}.xml".format(image_id)) def _get_ex...
Update the encoding format.
def set_encoding_format(self, encoding_format): """Update the encoding format.""" supported = ENCODE_FN.keys() if encoding_format not in supported: raise ValueError('`encoding_format` must be one of %s.' % supported) self._encoding_format = encoding_format
Update the shape.
def set_shape(self, shape): """Update the shape.""" channels = shape[-1] acceptable_channels = ACCEPTABLE_CHANNELS[self._encoding_format] if channels not in acceptable_channels: raise ValueError('Acceptable `channels` for %s: %s (was %s)' % ( self._encoding_format, acceptable_channels, c...
Returns np_image encoded as jpeg or png.
def _encode_image(self, np_image): """Returns np_image encoded as jpeg or png.""" if np_image.dtype != np.uint8: raise ValueError('Image should be uint8. Detected: %s.' % np_image.dtype) utils.assert_shape_match(np_image.shape, self._shape) return self._runner.run(ENCODE_FN[self._encoding_format],...
Convert the given image into a dict convertible to tf example.
def encode_example(self, image_or_path_or_fobj): """Convert the given image into a dict convertible to tf example.""" if isinstance(image_or_path_or_fobj, np.ndarray): encoded_image = self._encode_image(image_or_path_or_fobj) elif isinstance(image_or_path_or_fobj, six.string_types): with tf.io.g...
Reconstruct the image from the tf example.
def decode_example(self, example): """Reconstruct the image from the tf example.""" img = tf.image.decode_image( example, channels=self._shape[-1], dtype=tf.uint8) img.set_shape(self._shape) return img
See base class for details.
def save_metadata(self, data_dir, feature_name=None): """See base class for details.""" filepath = _get_metadata_filepath(data_dir, feature_name) with tf.io.gfile.GFile(filepath, 'w') as f: json.dump({ 'shape': [-1 if d is None else d for d in self._shape], 'encoding_format': self....
See base class for details.
def load_metadata(self, data_dir, feature_name=None): """See base class for details.""" # Restore names if defined filepath = _get_metadata_filepath(data_dir, feature_name) if tf.io.gfile.exists(filepath): with tf.io.gfile.GFile(filepath, 'r') as f: info_data = json.load(f) self.set_...
Create a moving image sequence from the given image a left padding values. Args: image: [in_h, in_w, n_channels] uint8 array pad_lefts: [sequence_length, 2] int32 array of left padding values total_padding: tensor of padding values, (pad_h, pad_w) Returns: [sequence_length, out_h, out_w, n_channel...
def _create_moving_sequence(image, pad_lefts, total_padding): """Create a moving image sequence from the given image a left padding values. Args: image: [in_h, in_w, n_channels] uint8 array pad_lefts: [sequence_length, 2] int32 array of left padding values total_padding: tensor of padding values, (pad_...
Construct a linear trajectory from x0. Args: x0: N-D float tensor. velocity: N-D float tensor t: [sequence_length]-length float tensor Returns: x: [sequence_length, ndims] float tensor.
def _get_linear_trajectory(x0, velocity, t): """Construct a linear trajectory from x0. Args: x0: N-D float tensor. velocity: N-D float tensor t: [sequence_length]-length float tensor Returns: x: [sequence_length, ndims] float tensor. """ x0 = tf.convert_to_tensor(x0) velocity = tf.convert_...
Turn simple static images into sequences of the originals bouncing around. Adapted from Srivastava et al. http://www.cs.toronto.edu/~nitish/unsupervised_video/ Example usage: ```python import tensorflow as tf import tensorflow_datasets as tfds from tensorflow_datasets.video import moving_sequence tf.c...
def image_as_moving_sequence( image, sequence_length=20, output_size=(64, 64), velocity=0.1, start_position=None): """Turn simple static images into sequences of the originals bouncing around. Adapted from Srivastava et al. http://www.cs.toronto.edu/~nitish/unsupervised_video/ Example usage: ```pyth...
Returns splits.
def _split_generators(self, dl_manager): """Returns splits.""" dl_urls = { split: _BASE_DOWNLOAD_PATH + "%s.tfrecord" % split for split in _SPLITS } dl_urls["instrument_labels"] = (_BASE_DOWNLOAD_PATH + "instrument_labels.txt") dl_paths = dl_manager.downlo...
Return the tuple (major, minor, patch) version extracted from the str.
def _str_to_version(version_str, allow_wildcard=False): """Return the tuple (major, minor, patch) version extracted from the str.""" reg = _VERSION_WILDCARD_REG if allow_wildcard else _VERSION_RESOLVED_REG res = reg.match(version_str) if not res: msg = "Invalid version '{}'. Format should be x.y.z".format(v...
Returns True if other_version matches. Args: other_version: string, of the form "x[.y[.x]]" where {x,y,z} can be a number or a wildcard.
def match(self, other_version): """Returns True if other_version matches. Args: other_version: string, of the form "x[.y[.x]]" where {x,y,z} can be a number or a wildcard. """ major, minor, patch = _str_to_version(other_version, allow_wildcard=True) return (major in [self.major, "*"] ...
Returns labels for validation. Args: val_path: path to TAR file containing validation images. It is used to retrieve the name of pictures and associate them to labels. Returns: dict, mapping from image name (str) to label (str).
def _get_validation_labels(val_path): """Returns labels for validation. Args: val_path: path to TAR file containing validation images. It is used to retrieve the name of pictures and associate them to labels. Returns: dict, mapping from image name (str) to label (str). """ labels...
Yields examples.
def _generate_examples(self, archive, validation_labels=None): """Yields examples.""" if validation_labels: # Validation split for example in self._generate_examples_validation(archive, validation_labels): yield example # Training split....
Returns a temporary filename based on filename.
def get_incomplete_path(filename): """Returns a temporary filename based on filename.""" random_suffix = "".join( random.choice(string.ascii_uppercase + string.digits) for _ in range(6)) return filename + ".incomplete" + random_suffix
Whether any of the filenames exist.
def do_files_exist(filenames): """Whether any of the filenames exist.""" preexisting = [tf.io.gfile.exists(f) for f in filenames] return any(preexisting)
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, output) finally: for tmp in tmp_files: if tf...
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(tmp_dir): tf.io.gfile.rmtree(tmp_dir)
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=False) ] # Shuffling in memory ran...
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: {}.".format(output_files)) with _incomplete_files(output_files) ...
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 empty value, the corresponding " ...
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(feature=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...
def _async_tqdm(*args, **kwargs): """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:...
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): """Extracts files from th...
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_BUFFER_SIZE) if not data: break dest_fil...
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 ...
def iter_tar(arch_f, gz=False, stream=False): """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 tempo...
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._executor.submit(self._sync_extract, ...
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 path, handle in iter_archive(from_path, method): _copy...
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 like float64 downsampled to float32, bool converted # to ...
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(value, dict): return FeaturesDict(value) else:...
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...
def decode_single_feature_from_dict( feature_k, feature, tfexample_dict): """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 contain...
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(): serialized_info = featur...
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 for feature_key, (feature, e...
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=feature_key, feature=feat...
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. 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...
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. 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...
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. 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. 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. 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" 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. 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 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. 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. 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. 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 split. """ splits = super(Imagenet2012Corrupted, self)._split_generators(dl_manager) validation = splits[1] return [validation...
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...
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. 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. """ corruption_type = self.builder_config.corruption_type severity = self.builder_config.severity return { 'gaussian_noise'...
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: 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. 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 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. 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 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. 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 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)...