tf.compat.v1.data.TFRecordDataset A Dataset comprising records from one or more TFRecord files. Inherits From: Dataset, Dataset
tf.compat.v1.data.TFRecordDataset(
    filenames, compression_type=None, buffer_size=None, num_parallel_reads=None
)

 Args
  filenames   A tf.string tensor or tf.data.Dataset containing one or more filenames.
  compression_type   (Optional.) A tf.string scalar evaluating to one of "" (no compression), "ZLIB", or "GZIP".
  buffer_size   (Optional.) A tf.int64 scalar representing the number of bytes in the read buffer. If your input pipeline is I/O bottlenecked, consider setting this parameter to a value 1-100 MBs. If None, a sensible default for both local and remote file systems is used.
  num_parallel_reads   (Optional.) A tf.int64 scalar representing the number of files to read in parallel. If greater than one, the records of files read in parallel are outputted in an interleaved order. If your input pipeline is I/O bottlenecked, consider setting this parameter to a value greater than one to parallelize the I/O. If None, files will be read sequentially.

 Raises
  TypeError   If any argument does not have the expected type.
  ValueError   If any argument does not have the expected shape.

 Attributes
  element_spec   The type specification of an element of this dataset.
dataset = tf.data.Dataset.from_tensor_slices([1, 2, 3])
dataset.element_spec
TensorSpec(shape=(), dtype=tf.int32, name=None)

  output_classes   Returns the class of each component of an element of this dataset. (deprecated) Warning: THIS FUNCTION IS DEPRECATED. It will be removed in a future version. Instructions for updating: Use tf.compat.v1.data.get_output_classes(dataset).

  output_shapes   Returns the shape of each component of an element of this dataset. (deprecated)Warning: THIS FUNCTION IS DEPRECATED. It will be removed in a future version. Instructions for updating: Use tf.compat.v1.data.get_output_shapes(dataset).

  output_types   Returns the type of each component of an element of this dataset. (deprecated)Warning: THIS FUNCTION IS DEPRECATED. It will be removed in a future version. Instructions for updating: Use tf.compat.v1.data.get_output_types(dataset).
   Methods apply View source
apply(
    transformation_func
)
 Applies a transformation function to this dataset. apply enables chaining of custom Dataset transformations, which are represented as functions that take one Dataset argument and return a transformed Dataset.
dataset = tf.data.Dataset.range(100)
def dataset_fn(ds):
  return ds.filter(lambda x: x < 5)
dataset = dataset.apply(dataset_fn)
list(dataset.as_numpy_iterator())
[0, 1, 2, 3, 4]

 Args
  transformation_func   A function that takes one Dataset argument and returns a Dataset.

 Returns
  Dataset   The Dataset returned by applying transformation_func to this dataset.    as_numpy_iterator View source
as_numpy_iterator()
 Returns an iterator which converts all elements of the dataset to numpy. Use as_numpy_iterator to inspect the content of your dataset. To see element shapes and types, print dataset elements directly instead of using as_numpy_iterator.
dataset = tf.data.Dataset.from_tensor_slices([1, 2, 3])
for element in dataset:
  print(element)
tf.Tensor(1, shape=(), dtype=int32)
tf.Tensor(2, shape=(), dtype=int32)
tf.Tensor(3, shape=(), dtype=int32)
 This method requires that you are running in eager mode and the dataset's element_spec contains only TensorSpec components.
dataset = tf.data.Dataset.from_tensor_slices([1, 2, 3])
for element in dataset.as_numpy_iterator():
  print(element)
1
2
3

dataset = tf.data.Dataset.from_tensor_slices([1, 2, 3])
print(list(dataset.as_numpy_iterator()))
[1, 2, 3]
 as_numpy_iterator() will preserve the nested structure of dataset elements.
dataset = tf.data.Dataset.from_tensor_slices({'a': ([1, 2], [3, 4]),
                                              'b': [5, 6]})
list(dataset.as_numpy_iterator()) == [{'a': (1, 3), 'b': 5},
                                      {'a': (2, 4), 'b': 6}]
True

 Returns   An iterable over the elements of the dataset, with their tensors converted to numpy arrays.

 Raises
  TypeError   if an element contains a non-Tensor value.
  RuntimeError   if eager execution is not enabled.    batch View source
batch(
    batch_size, drop_remainder=False
)
 Combines consecutive elements of this dataset into batches.
dataset = tf.data.Dataset.range(8)
dataset = dataset.batch(3)
list(dataset.as_numpy_iterator())
[array([0, 1, 2]), array([3, 4, 5]), array([6, 7])]

dataset = tf.data.Dataset.range(8)
dataset = dataset.batch(3, drop_remainder=True)
list(dataset.as_numpy_iterator())
[array([0, 1, 2]), array([3, 4, 5])]
 The components of the resulting element will have an additional outer dimension, which will be batch_size (or N % batch_size for the last element if batch_size does not divide the number of input elements N evenly and drop_remainder is False). If your program depends on the batches having the same outer dimension, you should set the drop_remainder argument to True to prevent the smaller batch from being produced.

 Args
  batch_size   A tf.int64 scalar tf.Tensor, representing the number of consecutive elements of this dataset to combine in a single batch.
  drop_remainder   (Optional.) A tf.bool scalar tf.Tensor, representing whether the last batch should be dropped in the case it has fewer than batch_size elements; the default behavior is not to drop the smaller batch.

 Returns
  Dataset   A Dataset.    cache View source
cache(
    filename=''
)
 Caches the elements in this dataset. The first time the dataset is iterated over, its elements will be cached either in the specified file or in memory. Subsequent iterations will use the cached data.
Note: For the cache to be finalized, the input dataset must be iterated through in its entirety. Otherwise, subsequent iterations will not use cached data.

dataset = tf.data.Dataset.range(5)
dataset = dataset.map(lambda x: x**2)
dataset = dataset.cache()
# The first time reading through the data will generate the data using
# `range` and `map`.
list(dataset.as_numpy_iterator())
[0, 1, 4, 9, 16]
# Subsequent iterations read from the cache.
list(dataset.as_numpy_iterator())
[0, 1, 4, 9, 16]
 When caching to a file, the cached data will persist across runs. Even the first iteration through the data will read from the cache file. Changing the input pipeline before the call to .cache() will have no effect until the cache file is removed or the filename is changed.
dataset = tf.data.Dataset.range(5)
dataset = dataset.cache("/path/to/file")  # doctest: +SKIP
list(dataset.as_numpy_iterator())  # doctest: +SKIP
[0, 1, 2, 3, 4]
dataset = tf.data.Dataset.range(10)
dataset = dataset.cache("/path/to/file")  # Same file! # doctest: +SKIP
list(dataset.as_numpy_iterator())  # doctest: +SKIP
[0, 1, 2, 3, 4]

Note: cache will produce exactly the same elements during each iteration through the dataset. If you wish to randomize the iteration order, make sure to call shuffle after calling cache.

 Args
  filename   A tf.string scalar tf.Tensor, representing the name of a directory on the filesystem to use for caching elements in this Dataset. If a filename is not provided, the dataset will be cached in memory.

 Returns
  Dataset   A Dataset.    cardinality View source
cardinality()
 Returns the cardinality of the dataset, if known. cardinality may return tf.data.INFINITE_CARDINALITY if the dataset contains an infinite number of elements or tf.data.UNKNOWN_CARDINALITY if the analysis fails to determine the number of elements in the dataset (e.g. when the dataset source is a file).
dataset = tf.data.Dataset.range(42)
print(dataset.cardinality().numpy())
42
dataset = dataset.repeat()
cardinality = dataset.cardinality()
print((cardinality == tf.data.INFINITE_CARDINALITY).numpy())
True
dataset = dataset.filter(lambda x: True)
cardinality = dataset.cardinality()
print((cardinality == tf.data.UNKNOWN_CARDINALITY).numpy())
True

 Returns   A scalar tf.int64 Tensor representing the cardinality of the dataset. If the cardinality is infinite or unknown, cardinality returns the named constants tf.data.INFINITE_CARDINALITY and tf.data.UNKNOWN_CARDINALITY respectively.
 concatenate View source
concatenate(
    dataset
)
 Creates a Dataset by concatenating the given dataset with this dataset.
a = tf.data.Dataset.range(1, 4)  # ==> [ 1, 2, 3 ]
b = tf.data.Dataset.range(4, 8)  # ==> [ 4, 5, 6, 7 ]
ds = a.concatenate(b)
list(ds.as_numpy_iterator())
[1, 2, 3, 4, 5, 6, 7]
# The input dataset and dataset to be concatenated should have the same
# nested structures and output types.
c = tf.data.Dataset.zip((a, b))
a.concatenate(c)
Traceback (most recent call last):
TypeError: Two datasets to concatenate have different types
<dtype: 'int64'> and (tf.int64, tf.int64)
d = tf.data.Dataset.from_tensor_slices(["a", "b", "c"])
a.concatenate(d)
Traceback (most recent call last):
TypeError: Two datasets to concatenate have different types
<dtype: 'int64'> and <dtype: 'string'>

 Args
  dataset   Dataset to be concatenated.

 Returns
  Dataset   A Dataset.    enumerate View source
enumerate(
    start=0
)
 Enumerates the elements of this dataset. It is similar to python's enumerate.
dataset = tf.data.Dataset.from_tensor_slices([1, 2, 3])
dataset = dataset.enumerate(start=5)
for element in dataset.as_numpy_iterator():
  print(element)
(5, 1)
(6, 2)
(7, 3)

# The nested structure of the input dataset determines the structure of
# elements in the resulting dataset.
dataset = tf.data.Dataset.from_tensor_slices([(7, 8), (9, 10)])
dataset = dataset.enumerate()
for element in dataset.as_numpy_iterator():
  print(element)
(0, array([7, 8], dtype=int32))
(1, array([ 9, 10], dtype=int32))

 Args
  start   A tf.int64 scalar tf.Tensor, representing the start value for enumeration.

 Returns
  Dataset   A Dataset.    filter View source
filter(
    predicate
)
 Filters this dataset according to predicate.
dataset = tf.data.Dataset.from_tensor_slices([1, 2, 3])
dataset = dataset.filter(lambda x: x < 3)
list(dataset.as_numpy_iterator())
[1, 2]
# `tf.math.equal(x, y)` is required for equality comparison
def filter_fn(x):
  return tf.math.equal(x, 1)
dataset = dataset.filter(filter_fn)
list(dataset.as_numpy_iterator())
[1]

 Args
  predicate   A function mapping a dataset element to a boolean.

 Returns
  Dataset   The Dataset containing the elements of this dataset for which predicate is True.    filter_with_legacy_function View source
filter_with_legacy_function(
    predicate
)
 Filters this dataset according to predicate. (deprecated) Warning: THIS FUNCTION IS DEPRECATED. It will be removed in a future version. Instructions for updating: Use `tf.data.Dataset.filter()
Note: This is an escape hatch for existing uses of filter that do not work with V2 functions. New uses are strongly discouraged and existing uses should migrate to filter as this method will be removed in V2.

 Args
  predicate   A function mapping a nested structure of tensors (having shapes and types defined by self.output_shapes and self.output_types) to a scalar tf.bool tensor.

 Returns
  Dataset   The Dataset containing the elements of this dataset for which predicate is True.    flat_map View source
flat_map(
    map_func
)
 Maps map_func across this dataset and flattens the result. Use flat_map if you want to make sure that the order of your dataset stays the same. For example, to flatten a dataset of batches into a dataset of their elements:
dataset = tf.data.Dataset.from_tensor_slices(
               [[1, 2, 3], [4, 5, 6], [7, 8, 9]])
dataset = dataset.flat_map(lambda x: Dataset.from_tensor_slices(x))
list(dataset.as_numpy_iterator())
[1, 2, 3, 4, 5, 6, 7, 8, 9]
 tf.data.Dataset.interleave() is a generalization of flat_map, since flat_map produces the same output as tf.data.Dataset.interleave(cycle_length=1)

 Args
  map_func   A function mapping a dataset element to a dataset.

 Returns
  Dataset   A Dataset.    from_generator View source
@staticmethod
from_generator(
    generator, output_types=None, output_shapes=None, args=None,
    output_signature=None
)
 Creates a Dataset whose elements are generated by generator. (deprecated arguments) Warning: SOME ARGUMENTS ARE DEPRECATED: (output_shapes, output_types). They will be removed in a future version. Instructions for updating: Use output_signature instead The generator argument must be a callable object that returns an object that supports the iter() protocol (e.g. a generator function). The elements generated by generator must be compatible with either the given output_signature argument or with the given output_types and (optionally) output_shapes arguments, whichiver was specified. The recommended way to call from_generator is to use the output_signature argument. In this case the output will be assumed to consist of objects with the classes, shapes and types defined by tf.TypeSpec objects from output_signature argument:
def gen():
  ragged_tensor = tf.ragged.constant([[1, 2], [3]])
  yield 42, ragged_tensor

dataset = tf.data.Dataset.from_generator(
     gen,
     output_signature=(
         tf.TensorSpec(shape=(), dtype=tf.int32),
         tf.RaggedTensorSpec(shape=(2, None), dtype=tf.int32)))

list(dataset.take(1))
[(<tf.Tensor: shape=(), dtype=int32, numpy=42>,
<tf.RaggedTensor [[1, 2], [3]]>)]
 There is also a deprecated way to call from_generator by either with output_types argument alone or together with output_shapes argument. In this case the output of the function will be assumed to consist of tf.Tensor objects with with the types defined by output_types and with the shapes which are either unknown or defined by output_shapes.
Note: The current implementation of Dataset.from_generator() uses tf.numpy_function and inherits the same constraints. In particular, it requires the dataset and iterator related operations to be placed on a device in the same process as the Python program that called Dataset.from_generator(). The body of generator will not be serialized in a GraphDef, and you should not use this method if you need to serialize your model and restore it in a different environment.

Note: If generator depends on mutable global variables or other external state, be aware that the runtime may invoke generator multiple times (in order to support repeating the Dataset) and at any time between the call to Dataset.from_generator() and the production of the first element from the generator. Mutating global variables or external state can cause undefined behavior, and we recommend that you explicitly cache any external state in generator before calling Dataset.from_generator().

 Args
  generator   A callable object that returns an object that supports the iter() protocol. If args is not specified, generator must take no arguments; otherwise it must take as many arguments as there are values in args.
  output_types   (Optional.) A nested structure of tf.DType objects corresponding to each component of an element yielded by generator.
  output_shapes   (Optional.) A nested structure of tf.TensorShape objects corresponding to each component of an element yielded by generator.
  args   (Optional.) A tuple of tf.Tensor objects that will be evaluated and passed to generator as NumPy-array arguments.
  output_signature   (Optional.) A nested structure of tf.TypeSpec objects corresponding to each component of an element yielded by generator.

 Returns
  Dataset   A Dataset.    from_sparse_tensor_slices View source
@staticmethod
from_sparse_tensor_slices(
    sparse_tensor
)
 Splits each rank-N tf.sparse.SparseTensor in this dataset row-wise. (deprecated) Warning: THIS FUNCTION IS DEPRECATED. It will be removed in a future version. Instructions for updating: Use tf.data.Dataset.from_tensor_slices().

 Args
  sparse_tensor   A tf.sparse.SparseTensor.

 Returns
  Dataset   A Dataset of rank-(N-1) sparse tensors.    from_tensor_slices View source
@staticmethod
from_tensor_slices(
    tensors
)
 Creates a Dataset whose elements are slices of the given tensors. The given tensors are sliced along their first dimension. This operation preserves the structure of the input tensors, removing the first dimension of each tensor and using it as the dataset dimension. All input tensors must have the same size in their first dimensions.
# Slicing a 1D tensor produces scalar tensor elements.
dataset = tf.data.Dataset.from_tensor_slices([1, 2, 3])
list(dataset.as_numpy_iterator())
[1, 2, 3]

# Slicing a 2D tensor produces 1D tensor elements.
dataset = tf.data.Dataset.from_tensor_slices([[1, 2], [3, 4]])
list(dataset.as_numpy_iterator())
[array([1, 2], dtype=int32), array([3, 4], dtype=int32)]

# Slicing a tuple of 1D tensors produces tuple elements containing
# scalar tensors.
dataset = tf.data.Dataset.from_tensor_slices(([1, 2], [3, 4], [5, 6]))
list(dataset.as_numpy_iterator())
[(1, 3, 5), (2, 4, 6)]

# Dictionary structure is also preserved.
dataset = tf.data.Dataset.from_tensor_slices({"a": [1, 2], "b": [3, 4]})
list(dataset.as_numpy_iterator()) == [{'a': 1, 'b': 3},
                                      {'a': 2, 'b': 4}]
True

# Two tensors can be combined into one Dataset object.
features = tf.constant([[1, 3], [2, 1], [3, 3]]) # ==> 3x2 tensor
labels = tf.constant(['A', 'B', 'A']) # ==> 3x1 tensor
dataset = Dataset.from_tensor_slices((features, labels))
# Both the features and the labels tensors can be converted
# to a Dataset object separately and combined after.
features_dataset = Dataset.from_tensor_slices(features)
labels_dataset = Dataset.from_tensor_slices(labels)
dataset = Dataset.zip((features_dataset, labels_dataset))
# A batched feature and label set can be converted to a Dataset
# in similar fashion.
batched_features = tf.constant([[[1, 3], [2, 3]],
                                [[2, 1], [1, 2]],
                                [[3, 3], [3, 2]]], shape=(3, 2, 2))
batched_labels = tf.constant([['A', 'A'],
                              ['B', 'B'],
                              ['A', 'B']], shape=(3, 2, 1))
dataset = Dataset.from_tensor_slices((batched_features, batched_labels))
for element in dataset.as_numpy_iterator():
  print(element)
(array([[1, 3],
       [2, 3]], dtype=int32), array([[b'A'],
       [b'A']], dtype=object))
(array([[2, 1],
       [1, 2]], dtype=int32), array([[b'B'],
       [b'B']], dtype=object))
(array([[3, 3],
       [3, 2]], dtype=int32), array([[b'A'],
       [b'B']], dtype=object))
 Note that if tensors contains a NumPy array, and eager execution is not enabled, the values will be embedded in the graph as one or more tf.constant operations. For large datasets (> 1 GB), this can waste memory and run into byte limits of graph serialization. If tensors contains one or more large NumPy arrays, consider the alternative described in this guide.

 Args
  tensors   A dataset element, with each component having the same size in the first dimension.

 Returns
  Dataset   A Dataset.    from_tensors View source
@staticmethod
from_tensors(
    tensors
)
 Creates a Dataset with a single element, comprising the given tensors. from_tensors produces a dataset containing only a single element. To slice the input tensor into multiple elements, use from_tensor_slices instead.
dataset = tf.data.Dataset.from_tensors([1, 2, 3])
list(dataset.as_numpy_iterator())
[array([1, 2, 3], dtype=int32)]
dataset = tf.data.Dataset.from_tensors(([1, 2, 3], 'A'))
list(dataset.as_numpy_iterator())
[(array([1, 2, 3], dtype=int32), b'A')]

# You can use `from_tensors` to produce a dataset which repeats
# the same example many times.
example = tf.constant([1,2,3])
dataset = tf.data.Dataset.from_tensors(example).repeat(2)
list(dataset.as_numpy_iterator())
[array([1, 2, 3], dtype=int32), array([1, 2, 3], dtype=int32)]
 Note that if tensors contains a NumPy array, and eager execution is not enabled, the values will be embedded in the graph as one or more tf.constant operations. For large datasets (> 1 GB), this can waste memory and run into byte limits of graph serialization. If tensors contains one or more large NumPy arrays, consider the alternative described in this guide.

 Args
  tensors   A dataset element.

 Returns
  Dataset   A Dataset.    interleave View source
interleave(
    map_func, cycle_length=None, block_length=None, num_parallel_calls=None,
    deterministic=None
)
 Maps map_func across this dataset, and interleaves the results. For example, you can use Dataset.interleave() to process many input files concurrently:
# Preprocess 4 files concurrently, and interleave blocks of 16 records
# from each file.
filenames = ["/var/data/file1.txt", "/var/data/file2.txt",
             "/var/data/file3.txt", "/var/data/file4.txt"]
dataset = tf.data.Dataset.from_tensor_slices(filenames)
def parse_fn(filename):
  return tf.data.Dataset.range(10)
dataset = dataset.interleave(lambda x:
    tf.data.TextLineDataset(x).map(parse_fn, num_parallel_calls=1),
    cycle_length=4, block_length=16)
 The cycle_length and block_length arguments control the order in which elements are produced. cycle_length controls the number of input elements that are processed concurrently. If you set cycle_length to 1, this transformation will handle one input element at a time, and will produce identical results to tf.data.Dataset.flat_map. In general, this transformation will apply map_func to cycle_length input elements, open iterators on the returned Dataset objects, and cycle through them producing block_length consecutive elements from each iterator, and consuming the next input element each time it reaches the end of an iterator. For example:
dataset = Dataset.range(1, 6)  # ==> [ 1, 2, 3, 4, 5 ]
# NOTE: New lines indicate "block" boundaries.
dataset = dataset.interleave(
    lambda x: Dataset.from_tensors(x).repeat(6),
    cycle_length=2, block_length=4)
list(dataset.as_numpy_iterator())
[1, 1, 1, 1,
 2, 2, 2, 2,
 1, 1,
 2, 2,
 3, 3, 3, 3,
 4, 4, 4, 4,
 3, 3,
 4, 4,
 5, 5, 5, 5,
 5, 5]

Note: The order of elements yielded by this transformation is deterministic, as long as map_func is a pure function and deterministic=True. If map_func contains any stateful operations, the order in which that state is accessed is undefined.
 Performance can often be improved by setting num_parallel_calls so that interleave will use multiple threads to fetch elements. If determinism isn't required, it can also improve performance to set deterministic=False.
filenames = ["/var/data/file1.txt", "/var/data/file2.txt",
             "/var/data/file3.txt", "/var/data/file4.txt"]
dataset = tf.data.Dataset.from_tensor_slices(filenames)
dataset = dataset.interleave(lambda x: tf.data.TFRecordDataset(x),
    cycle_length=4, num_parallel_calls=tf.data.AUTOTUNE,
    deterministic=False)

 Args
  map_func   A function mapping a dataset element to a dataset.
  cycle_length   (Optional.) The number of input elements that will be processed concurrently. If not set, the tf.data runtime decides what it should be based on available CPU. If num_parallel_calls is set to tf.data.AUTOTUNE, the cycle_length argument identifies the maximum degree of parallelism.
  block_length   (Optional.) The number of consecutive elements to produce from each input element before cycling to another input element. If not set, defaults to 1.
  num_parallel_calls   (Optional.) If specified, the implementation creates a threadpool, which is used to fetch inputs from cycle elements asynchronously and in parallel. The default behavior is to fetch inputs from cycle elements synchronously with no parallelism. If the value tf.data.AUTOTUNE is used, then the number of parallel calls is set dynamically based on available CPU.
  deterministic   (Optional.) A boolean controlling whether determinism should be traded for performance by allowing elements to be produced out of order. If deterministic is None, the tf.data.Options.experimental_deterministic dataset option (True by default) is used to decide whether to produce elements deterministically.

 Returns
  Dataset   A Dataset.    list_files View source
@staticmethod
list_files(
    file_pattern, shuffle=None, seed=None
)
 A dataset of all files matching one or more glob patterns. The file_pattern argument should be a small number of glob patterns. If your filenames have already been globbed, use Dataset.from_tensor_slices(filenames) instead, as re-globbing every filename with list_files may result in poor performance with remote storage systems.
Note: The default behavior of this method is to return filenames in a non-deterministic random shuffled order. Pass a seed or shuffle=False to get results in a deterministic order.
 Example: If we had the following files on our filesystem:  /path/to/dir/a.txt /path/to/dir/b.py /path/to/dir/c.py  If we pass "/path/to/dir/*.py" as the directory, the dataset would produce:  /path/to/dir/b.py /path/to/dir/c.py

 Args
  file_pattern   A string, a list of strings, or a tf.Tensor of string type (scalar or vector), representing the filename glob (i.e. shell wildcard) pattern(s) that will be matched.
  shuffle   (Optional.) If True, the file names will be shuffled randomly. Defaults to True.
  seed   (Optional.) A tf.int64 scalar tf.Tensor, representing the random seed that will be used to create the distribution. See tf.random.set_seed for behavior.

 Returns
  Dataset   A Dataset of strings corresponding to file names.    make_initializable_iterator View source
make_initializable_iterator(
    shared_name=None
)
 Creates an iterator for elements of this dataset. (deprecated) Warning: THIS FUNCTION IS DEPRECATED. It will be removed in a future version. Instructions for updating: This is a deprecated API that should only be used in TF 1 graph mode and legacy TF 2 graph mode available through tf.compat.v1. In all other situations -- namely, eager mode and inside tf.function -- you can consume dataset elements using for elem in dataset: ... or by explicitly creating iterator via iterator = iter(dataset) and fetching its elements via values = next(iterator). Furthermore, this API is not available in TF 2. During the transition from TF 1 to TF 2 you can use tf.compat.v1.data.make_initializable_iterator(dataset) to create a TF 1 graph mode style iterator for a dataset created through TF 2 APIs. Note that this should be a transient state of your code base as there are in general no guarantees about the interoperability of TF 1 and TF 2 code.
Note: The returned iterator will be in an uninitialized state, and you must run the iterator.initializer operation before using it:

# Building graph ...
dataset = ...
iterator = dataset.make_initializable_iterator()
next_value = iterator.get_next()  # This is a Tensor.

# ... from within a session ...
sess.run(iterator.initializer)
try:
  while True:
    value = sess.run(next_value)
    ...
except tf.errors.OutOfRangeError:
    pass

 Args
  shared_name   (Optional.) If non-empty, the returned iterator will be shared under the given name across multiple sessions that share the same devices (e.g. when using a remote server).

 Returns   A tf.data.Iterator for elements of this dataset.

 Raises
  RuntimeError   If eager execution is enabled.    make_one_shot_iterator View source
make_one_shot_iterator()
 Creates an iterator for elements of this dataset. (deprecated) Warning: THIS FUNCTION IS DEPRECATED. It will be removed in a future version. Instructions for updating: This is a deprecated API that should only be used in TF 1 graph mode and legacy TF 2 graph mode available through tf.compat.v1. In all other situations -- namely, eager mode and inside tf.function -- you can consume dataset elements using for elem in dataset: ... or by explicitly creating iterator via iterator = iter(dataset) and fetching its elements via values = next(iterator). Furthermore, this API is not available in TF 2. During the transition from TF 1 to TF 2 you can use tf.compat.v1.data.make_one_shot_iterator(dataset) to create a TF 1 graph mode style iterator for a dataset created through TF 2 APIs. Note that this should be a transient state of your code base as there are in general no guarantees about the interoperability of TF 1 and TF 2 code.
Note: The returned iterator will be initialized automatically. A "one-shot" iterator does not currently support re-initialization. For that see make_initializable_iterator.
 Example: # Building graph ...
dataset = ...
next_value = dataset.make_one_shot_iterator().get_next()

# ... from within a session ...
try:
  while True:
    value = sess.run(next_value)
    ...
except tf.errors.OutOfRangeError:
    pass

 Returns   An tf.data.Iterator for elements of this dataset.
 map View source
map(
    map_func, num_parallel_calls=None, deterministic=None
)
 Maps map_func across the elements of this dataset. This transformation applies map_func to each element of this dataset, and returns a new dataset containing the transformed elements, in the same order as they appeared in the input. map_func can be used to change both the values and the structure of a dataset's elements. For example, adding 1 to each element, or projecting a subset of element components.
dataset = Dataset.range(1, 6)  # ==> [ 1, 2, 3, 4, 5 ]
dataset = dataset.map(lambda x: x + 1)
list(dataset.as_numpy_iterator())
[2, 3, 4, 5, 6]
 The input signature of map_func is determined by the structure of each element in this dataset.
dataset = Dataset.range(5)
# `map_func` takes a single argument of type `tf.Tensor` with the same
# shape and dtype.
result = dataset.map(lambda x: x + 1)

# Each element is a tuple containing two `tf.Tensor` objects.
elements = [(1, "foo"), (2, "bar"), (3, "baz")]
dataset = tf.data.Dataset.from_generator(
    lambda: elements, (tf.int32, tf.string))
# `map_func` takes two arguments of type `tf.Tensor`. This function
# projects out just the first component.
result = dataset.map(lambda x_int, y_str: x_int)
list(result.as_numpy_iterator())
[1, 2, 3]

# Each element is a dictionary mapping strings to `tf.Tensor` objects.
elements =  ([{"a": 1, "b": "foo"},
              {"a": 2, "b": "bar"},
              {"a": 3, "b": "baz"}])
dataset = tf.data.Dataset.from_generator(
    lambda: elements, {"a": tf.int32, "b": tf.string})
# `map_func` takes a single argument of type `dict` with the same keys
# as the elements.
result = dataset.map(lambda d: str(d["a"]) + d["b"])
 The value or values returned by map_func determine the structure of each element in the returned dataset.
dataset = tf.data.Dataset.range(3)
# `map_func` returns two `tf.Tensor` objects.
def g(x):
  return tf.constant(37.0), tf.constant(["Foo", "Bar", "Baz"])
result = dataset.map(g)
result.element_spec
(TensorSpec(shape=(), dtype=tf.float32, name=None), TensorSpec(shape=(3,), dtype=tf.string, name=None))
# Python primitives, lists, and NumPy arrays are implicitly converted to
# `tf.Tensor`.
def h(x):
  return 37.0, ["Foo", "Bar"], np.array([1.0, 2.0], dtype=np.float64)
result = dataset.map(h)
result.element_spec
(TensorSpec(shape=(), dtype=tf.float32, name=None), TensorSpec(shape=(2,), dtype=tf.string, name=None), TensorSpec(shape=(2,), dtype=tf.float64, name=None))
# `map_func` can return nested structures.
def i(x):
  return (37.0, [42, 16]), "foo"
result = dataset.map(i)
result.element_spec
((TensorSpec(shape=(), dtype=tf.float32, name=None),
  TensorSpec(shape=(2,), dtype=tf.int32, name=None)),
 TensorSpec(shape=(), dtype=tf.string, name=None))
 map_func can accept as arguments and return any type of dataset element. Note that irrespective of the context in which map_func is defined (eager vs. graph), tf.data traces the function and executes it as a graph. To use Python code inside of the function you have a few options: 1) Rely on AutoGraph to convert Python code into an equivalent graph computation. The downside of this approach is that AutoGraph can convert some but not all Python code. 2) Use tf.py_function, which allows you to write arbitrary Python code but will generally result in worse performance than 1). For example:
d = tf.data.Dataset.from_tensor_slices(['hello', 'world'])
# transform a string tensor to upper case string using a Python function
def upper_case_fn(t: tf.Tensor):
  return t.numpy().decode('utf-8').upper()
d = d.map(lambda x: tf.py_function(func=upper_case_fn,
          inp=[x], Tout=tf.string))
list(d.as_numpy_iterator())
[b'HELLO', b'WORLD']
 3) Use tf.numpy_function, which also allows you to write arbitrary Python code. Note that tf.py_function accepts tf.Tensor whereas tf.numpy_function accepts numpy arrays and returns only numpy arrays. For example:
d = tf.data.Dataset.from_tensor_slices(['hello', 'world'])
def upper_case_fn(t: np.ndarray):
  return t.decode('utf-8').upper()
d = d.map(lambda x: tf.numpy_function(func=upper_case_fn,
          inp=[x], Tout=tf.string))
list(d.as_numpy_iterator())
[b'HELLO', b'WORLD']
 Note that the use of tf.numpy_function and tf.py_function in general precludes the possibility of executing user-defined transformations in parallel (because of Python GIL). Performance can often be improved by setting num_parallel_calls so that map will use multiple threads to process elements. If deterministic order isn't required, it can also improve performance to set deterministic=False.
dataset = Dataset.range(1, 6)  # ==> [ 1, 2, 3, 4, 5 ]
dataset = dataset.map(lambda x: x + 1,
    num_parallel_calls=tf.data.AUTOTUNE,
    deterministic=False)

 Args
  map_func   A function mapping a dataset element to another dataset element.
  num_parallel_calls   (Optional.) A tf.int32 scalar tf.Tensor, representing the number elements to process asynchronously in parallel. If not specified, elements will be processed sequentially. If the value tf.data.AUTOTUNE is used, then the number of parallel calls is set dynamically based on available CPU.
  deterministic   (Optional.) A boolean controlling whether determinism should be traded for performance by allowing elements to be produced out of order. If deterministic is None, the tf.data.Options.experimental_deterministic dataset option (True by default) is used to decide whether to produce elements deterministically.

 Returns
  Dataset   A Dataset.    map_with_legacy_function View source
map_with_legacy_function(
    map_func, num_parallel_calls=None, deterministic=None
)
 Maps map_func across the elements of this dataset. (deprecated) Warning: THIS FUNCTION IS DEPRECATED. It will be removed in a future version. Instructions for updating: Use `tf.data.Dataset.map()
Note: This is an escape hatch for existing uses of map that do not work with V2 functions. New uses are strongly discouraged and existing uses should migrate to map as this method will be removed in V2.

 Args
  map_func   A function mapping a nested structure of tensors (having shapes and types defined by self.output_shapes and self.output_types) to another nested structure of tensors.
  num_parallel_calls   (Optional.) A tf.int32 scalar tf.Tensor, representing the number elements to process asynchronously in parallel. If not specified, elements will be processed sequentially. If the value tf.data.AUTOTUNE is used, then the number of parallel calls is set dynamically based on available CPU.
  deterministic   (Optional.) A boolean controlling whether determinism should be traded for performance by allowing elements to be produced out of order. If deterministic is None, the tf.data.Options.experimental_deterministic dataset option (True by default) is used to decide whether to produce elements deterministically.

 Returns
  Dataset   A Dataset.    options View source
options()
 Returns the options for this dataset and its inputs.

 Returns   A tf.data.Options object representing the dataset options.
 padded_batch View source
padded_batch(
    batch_size, padded_shapes=None, padding_values=None, drop_remainder=False
)
 Combines consecutive elements of this dataset into padded batches. This transformation combines multiple consecutive elements of the input dataset into a single element. Like tf.data.Dataset.batch, the components of the resulting element will have an additional outer dimension, which will be batch_size (or N % batch_size for the last element if batch_size does not divide the number of input elements N evenly and drop_remainder is False). If your program depends on the batches having the same outer dimension, you should set the drop_remainder argument to True to prevent the smaller batch from being produced. Unlike tf.data.Dataset.batch, the input elements to be batched may have different shapes, and this transformation will pad each component to the respective shape in padded_shapes. The padded_shapes argument determines the resulting shape for each dimension of each component in an output element:  If the dimension is a constant, the component will be padded out to that length in that dimension. If the dimension is unknown, the component will be padded out to the maximum length of all elements in that dimension.
A = (tf.data.Dataset
     .range(1, 5, output_type=tf.int32)
     .map(lambda x: tf.fill([x], x)))
# Pad to the smallest per-batch size that fits all elements.
B = A.padded_batch(2)
for element in B.as_numpy_iterator():
  print(element)
[[1 0]
 [2 2]]
[[3 3 3 0]
 [4 4 4 4]]
# Pad to a fixed size.
C = A.padded_batch(2, padded_shapes=5)
for element in C.as_numpy_iterator():
  print(element)
[[1 0 0 0 0]
 [2 2 0 0 0]]
[[3 3 3 0 0]
 [4 4 4 4 0]]
# Pad with a custom value.
D = A.padded_batch(2, padded_shapes=5, padding_values=-1)
for element in D.as_numpy_iterator():
  print(element)
[[ 1 -1 -1 -1 -1]
 [ 2  2 -1 -1 -1]]
[[ 3  3  3 -1 -1]
 [ 4  4  4  4 -1]]
# Components of nested elements can be padded independently.
elements = [([1, 2, 3], [10]),
            ([4, 5], [11, 12])]
dataset = tf.data.Dataset.from_generator(
    lambda: iter(elements), (tf.int32, tf.int32))
# Pad the first component of the tuple to length 4, and the second
# component to the smallest size that fits.
dataset = dataset.padded_batch(2,
    padded_shapes=([4], [None]),
    padding_values=(-1, 100))
list(dataset.as_numpy_iterator())
[(array([[ 1,  2,  3, -1], [ 4,  5, -1, -1]], dtype=int32),
  array([[ 10, 100], [ 11,  12]], dtype=int32))]
# Pad with a single value and multiple components.
E = tf.data.Dataset.zip((A, A)).padded_batch(2, padding_values=-1)
for element in E.as_numpy_iterator():
  print(element)
(array([[ 1, -1],
       [ 2,  2]], dtype=int32), array([[ 1, -1],
       [ 2,  2]], dtype=int32))
(array([[ 3,  3,  3, -1],
       [ 4,  4,  4,  4]], dtype=int32), array([[ 3,  3,  3, -1],
       [ 4,  4,  4,  4]], dtype=int32))
 See also tf.data.experimental.dense_to_sparse_batch, which combines elements that may have different shapes into a tf.sparse.SparseTensor.

 Args
  batch_size   A tf.int64 scalar tf.Tensor, representing the number of consecutive elements of this dataset to combine in a single batch.
  padded_shapes   (Optional.) A nested structure of tf.TensorShape or tf.int64 vector tensor-like objects representing the shape to which the respective component of each input element should be padded prior to batching. Any unknown dimensions will be padded to the maximum size of that dimension in each batch. If unset, all dimensions of all components are padded to the maximum size in the batch. padded_shapes must be set if any component has an unknown rank.
  padding_values   (Optional.) A nested structure of scalar-shaped tf.Tensor, representing the padding values to use for the respective components. None represents that the nested structure should be padded with default values. Defaults are 0 for numeric types and the empty string for string types. The padding_values should have the same structure as the input dataset. If padding_values is a single element and the input dataset has multiple components, then the same padding_values will be used to pad every component of the dataset. If padding_values is a scalar, then its value will be broadcasted to match the shape of each component.
  drop_remainder   (Optional.) A tf.bool scalar tf.Tensor, representing whether the last batch should be dropped in the case it has fewer than batch_size elements; the default behavior is not to drop the smaller batch.

 Returns
  Dataset   A Dataset.

 Raises
  ValueError   If a component has an unknown rank, and the padded_shapes argument is not set.    prefetch View source
prefetch(
    buffer_size
)
 Creates a Dataset that prefetches elements from this dataset. Most dataset input pipelines should end with a call to prefetch. This allows later elements to be prepared while the current element is being processed. This often improves latency and throughput, at the cost of using additional memory to store prefetched elements.
Note: Like other Dataset methods, prefetch operates on the elements of the input dataset. It has no concept of examples vs. batches. examples.prefetch(2) will prefetch two elements (2 examples), while examples.batch(20).prefetch(2) will prefetch 2 elements (2 batches, of 20 examples each).

dataset = tf.data.Dataset.range(3)
dataset = dataset.prefetch(2)
list(dataset.as_numpy_iterator())
[0, 1, 2]

 Args
  buffer_size   A tf.int64 scalar tf.Tensor, representing the maximum number of elements that will be buffered when prefetching.

 Returns
  Dataset   A Dataset.    range View source
@staticmethod
range(
    *args, **kwargs
)
 Creates a Dataset of a step-separated range of values.
list(Dataset.range(5).as_numpy_iterator())
[0, 1, 2, 3, 4]
list(Dataset.range(2, 5).as_numpy_iterator())
[2, 3, 4]
list(Dataset.range(1, 5, 2).as_numpy_iterator())
[1, 3]
list(Dataset.range(1, 5, -2).as_numpy_iterator())
[]
list(Dataset.range(5, 1).as_numpy_iterator())
[]
list(Dataset.range(5, 1, -2).as_numpy_iterator())
[5, 3]
list(Dataset.range(2, 5, output_type=tf.int32).as_numpy_iterator())
[2, 3, 4]
list(Dataset.range(1, 5, 2, output_type=tf.float32).as_numpy_iterator())
[1.0, 3.0]

 Args
  *args   follows the same semantics as python's xrange. len(args) == 1 -> start = 0, stop = args[0], step = 1. len(args) == 2 -> start = args[0], stop = args[1], step = 1. len(args) == 3 -> start = args[0], stop = args[1], step = args[2].
  **kwargs    output_type: Its expected dtype. (Optional, default: tf.int64).

 Returns
  Dataset   A RangeDataset.

 Raises
  ValueError   if len(args) == 0.    reduce View source
reduce(
    initial_state, reduce_func
)
 Reduces the input dataset to a single element. The transformation calls reduce_func successively on every element of the input dataset until the dataset is exhausted, aggregating information in its internal state. The initial_state argument is used for the initial state and the final state is returned as the result.
tf.data.Dataset.range(5).reduce(np.int64(0), lambda x, _: x + 1).numpy()
5
tf.data.Dataset.range(5).reduce(np.int64(0), lambda x, y: x + y).numpy()
10

 Args
  initial_state   An element representing the initial state of the transformation.
  reduce_func   A function that maps (old_state, input_element) to new_state. It must take two arguments and return a new element The structure of new_state must match the structure of initial_state.

 Returns   A dataset element corresponding to the final state of the transformation.
 repeat View source
repeat(
    count=None
)
 Repeats this dataset so each original value is seen count times.
dataset = tf.data.Dataset.from_tensor_slices([1, 2, 3])
dataset = dataset.repeat(3)
list(dataset.as_numpy_iterator())
[1, 2, 3, 1, 2, 3, 1, 2, 3]

Note: If this dataset is a function of global state (e.g. a random number generator), then different repetitions may produce different elements.

 Args
  count   (Optional.) A tf.int64 scalar tf.Tensor, representing the number of times the dataset should be repeated. The default behavior (if count is None or -1) is for the dataset be repeated indefinitely.

 Returns
  Dataset   A Dataset.    shard View source
shard(
    num_shards, index
)
 Creates a Dataset that includes only 1/num_shards of this dataset. shard is deterministic. The Dataset produced by A.shard(n, i) will contain all elements of A whose index mod n = i.
A = tf.data.Dataset.range(10)
B = A.shard(num_shards=3, index=0)
list(B.as_numpy_iterator())
[0, 3, 6, 9]
C = A.shard(num_shards=3, index=1)
list(C.as_numpy_iterator())
[1, 4, 7]
D = A.shard(num_shards=3, index=2)
list(D.as_numpy_iterator())
[2, 5, 8]
 This dataset operator is very useful when running distributed training, as it allows each worker to read a unique subset. When reading a single input file, you can shard elements as follows: d = tf.data.TFRecordDataset(input_file)
d = d.shard(num_workers, worker_index)
d = d.repeat(num_epochs)
d = d.shuffle(shuffle_buffer_size)
d = d.map(parser_fn, num_parallel_calls=num_map_threads)
 Important caveats:  Be sure to shard before you use any randomizing operator (such as shuffle). Generally it is best if the shard operator is used early in the dataset pipeline. For example, when reading from a set of TFRecord files, shard before converting the dataset to input samples. This avoids reading every file on every worker. The following is an example of an efficient sharding strategy within a complete pipeline:  d = Dataset.list_files(pattern)
d = d.shard(num_workers, worker_index)
d = d.repeat(num_epochs)
d = d.shuffle(shuffle_buffer_size)
d = d.interleave(tf.data.TFRecordDataset,
                 cycle_length=num_readers, block_length=1)
d = d.map(parser_fn, num_parallel_calls=num_map_threads)

 Args
  num_shards   A tf.int64 scalar tf.Tensor, representing the number of shards operating in parallel.
  index   A tf.int64 scalar tf.Tensor, representing the worker index.

 Returns
  Dataset   A Dataset.

 Raises
  InvalidArgumentError   if num_shards or index are illegal values.
Note: error checking is done on a best-effort basis, and errors aren't guaranteed to be caught upon dataset creation. (e.g. providing in a placeholder tensor bypasses the early checking, and will instead result in an error during a session.run call.)

   shuffle View source
shuffle(
    buffer_size, seed=None, reshuffle_each_iteration=None
)
 Randomly shuffles the elements of this dataset. This dataset fills a buffer with buffer_size elements, then randomly samples elements from this buffer, replacing the selected elements with new elements. For perfect shuffling, a buffer size greater than or equal to the full size of the dataset is required. For instance, if your dataset contains 10,000 elements but buffer_size is set to 1,000, then shuffle will initially select a random element from only the first 1,000 elements in the buffer. Once an element is selected, its space in the buffer is replaced by the next (i.e. 1,001-st) element, maintaining the 1,000 element buffer. reshuffle_each_iteration controls whether the shuffle order should be different for each epoch. In TF 1.X, the idiomatic way to create epochs was through the repeat transformation:
dataset = tf.data.Dataset.range(3)
dataset = dataset.shuffle(3, reshuffle_each_iteration=True)
dataset = dataset.repeat(2)  # doctest: +SKIP
[1, 0, 2, 1, 2, 0]

dataset = tf.data.Dataset.range(3)
dataset = dataset.shuffle(3, reshuffle_each_iteration=False)
dataset = dataset.repeat(2)  # doctest: +SKIP
[1, 0, 2, 1, 0, 2]
 In TF 2.0, tf.data.Dataset objects are Python iterables which makes it possible to also create epochs through Python iteration:
dataset = tf.data.Dataset.range(3)
dataset = dataset.shuffle(3, reshuffle_each_iteration=True)
list(dataset.as_numpy_iterator())  # doctest: +SKIP
[1, 0, 2]
list(dataset.as_numpy_iterator())  # doctest: +SKIP
[1, 2, 0]

dataset = tf.data.Dataset.range(3)
dataset = dataset.shuffle(3, reshuffle_each_iteration=False)
list(dataset.as_numpy_iterator())  # doctest: +SKIP
[1, 0, 2]
list(dataset.as_numpy_iterator())  # doctest: +SKIP
[1, 0, 2]

 Args
  buffer_size   A tf.int64 scalar tf.Tensor, representing the number of elements from this dataset from which the new dataset will sample.
  seed   (Optional.) A tf.int64 scalar tf.Tensor, representing the random seed that will be used to create the distribution. See tf.random.set_seed for behavior.
  reshuffle_each_iteration   (Optional.) A boolean, which if true indicates that the dataset should be pseudorandomly reshuffled each time it is iterated over. (Defaults to True.)

 Returns
  Dataset   A Dataset.    skip View source
skip(
    count
)
 Creates a Dataset that skips count elements from this dataset.
dataset = tf.data.Dataset.range(10)
dataset = dataset.skip(7)
list(dataset.as_numpy_iterator())
[7, 8, 9]

 Args
  count   A tf.int64 scalar tf.Tensor, representing the number of elements of this dataset that should be skipped to form the new dataset. If count is greater than the size of this dataset, the new dataset will contain no elements. If count is -1, skips the entire dataset.

 Returns
  Dataset   A Dataset.    take View source
take(
    count
)
 Creates a Dataset with at most count elements from this dataset.
dataset = tf.data.Dataset.range(10)
dataset = dataset.take(3)
list(dataset.as_numpy_iterator())
[0, 1, 2]

 Args
  count   A tf.int64 scalar tf.Tensor, representing the number of elements of this dataset that should be taken to form the new dataset. If count is -1, or if count is greater than the size of this dataset, the new dataset will contain all elements of this dataset.

 Returns
  Dataset   A Dataset.    unbatch View source
unbatch()
 Splits elements of a dataset into multiple elements. For example, if elements of the dataset are shaped [B, a0, a1, ...], where B may vary for each input element, then for each element in the dataset, the unbatched dataset will contain B consecutive elements of shape [a0, a1, ...].
elements = [ [1, 2, 3], [1, 2], [1, 2, 3, 4] ]
dataset = tf.data.Dataset.from_generator(lambda: elements, tf.int64)
dataset = dataset.unbatch()
list(dataset.as_numpy_iterator())
[1, 2, 3, 1, 2, 1, 2, 3, 4]

Note: unbatch requires a data copy to slice up the batched tensor into smaller, unbatched tensors. When optimizing performance, try to avoid unnecessary usage of unbatch.

 Returns   A Dataset.
 window View source
window(
    size, shift=None, stride=1, drop_remainder=False
)
 Combines (nests of) input elements into a dataset of (nests of) windows. A "window" is a finite dataset of flat elements of size size (or possibly fewer if there are not enough input elements to fill the window and drop_remainder evaluates to False). The shift argument determines the number of input elements by which the window moves on each iteration. If windows and elements are both numbered starting at 0, the first element in window k will be element k * shift of the input dataset. In particular, the first element of the first window will always be the first element of the input dataset. The stride argument determines the stride of the input elements, and the shift argument determines the shift of the window. For example:
dataset = tf.data.Dataset.range(7).window(2)
for window in dataset:
  print(list(window.as_numpy_iterator()))
[0, 1]
[2, 3]
[4, 5]
[6]
dataset = tf.data.Dataset.range(7).window(3, 2, 1, True)
for window in dataset:
  print(list(window.as_numpy_iterator()))
[0, 1, 2]
[2, 3, 4]
[4, 5, 6]
dataset = tf.data.Dataset.range(7).window(3, 1, 2, True)
for window in dataset:
  print(list(window.as_numpy_iterator()))
[0, 2, 4]
[1, 3, 5]
[2, 4, 6]
 Note that when the window transformation is applied to a dataset of nested elements, it produces a dataset of nested windows.
nested = ([1, 2, 3, 4], [5, 6, 7, 8])
dataset = tf.data.Dataset.from_tensor_slices(nested).window(2)
for window in dataset:
  def to_numpy(ds):
    return list(ds.as_numpy_iterator())
  print(tuple(to_numpy(component) for component in window))
([1, 2], [5, 6])
([3, 4], [7, 8])

dataset = tf.data.Dataset.from_tensor_slices({'a': [1, 2, 3, 4]})
dataset = dataset.window(2)
for window in dataset:
  def to_numpy(ds):
    return list(ds.as_numpy_iterator())
  print({'a': to_numpy(window['a'])})
{'a': [1, 2]}
{'a': [3, 4]}

 Args
  size   A tf.int64 scalar tf.Tensor, representing the number of elements of the input dataset to combine into a window. Must be positive.
  shift   (Optional.) A tf.int64 scalar tf.Tensor, representing the number of input elements by which the window moves in each iteration. Defaults to size. Must be positive.
  stride   (Optional.) A tf.int64 scalar tf.Tensor, representing the stride of the input elements in the sliding window. Must be positive. The default value of 1 means "retain every input element".
  drop_remainder   (Optional.) A tf.bool scalar tf.Tensor, representing whether the last windows should be dropped if their size is smaller than size.

 Returns
  Dataset   A Dataset of (nests of) windows -- a finite datasets of flat elements created from the (nests of) input elements.    with_options View source
with_options(
    options
)
 Returns a new tf.data.Dataset with the given options set. The options are "global" in the sense they apply to the entire dataset. If options are set multiple times, they are merged as long as different options do not use different non-default values.
ds = tf.data.Dataset.range(5)
ds = ds.interleave(lambda x: tf.data.Dataset.range(5),
                   cycle_length=3,
                   num_parallel_calls=3)
options = tf.data.Options()
# This will make the interleave order non-deterministic.
options.experimental_deterministic = False
ds = ds.with_options(options)

 Args
  options   A tf.data.Options that identifies the options the use.

 Returns
  Dataset   A Dataset with the given options.

 Raises
  ValueError   when an option is set more than once to a non-default value    zip View source
@staticmethod
zip(
    datasets
)
 Creates a Dataset by zipping together the given datasets. This method has similar semantics to the built-in zip() function in Python, with the main difference being that the datasets argument can be an arbitrary nested structure of Dataset objects.
# The nested structure of the `datasets` argument determines the
# structure of elements in the resulting dataset.
a = tf.data.Dataset.range(1, 4)  # ==> [ 1, 2, 3 ]
b = tf.data.Dataset.range(4, 7)  # ==> [ 4, 5, 6 ]
ds = tf.data.Dataset.zip((a, b))
list(ds.as_numpy_iterator())
[(1, 4), (2, 5), (3, 6)]
ds = tf.data.Dataset.zip((b, a))
list(ds.as_numpy_iterator())
[(4, 1), (5, 2), (6, 3)]

# The `datasets` argument may contain an arbitrary number of datasets.
c = tf.data.Dataset.range(7, 13).batch(2)  # ==> [ [7, 8],
                                           #       [9, 10],
                                           #       [11, 12] ]
ds = tf.data.Dataset.zip((a, b, c))
for element in ds.as_numpy_iterator():
  print(element)
(1, 4, array([7, 8]))
(2, 5, array([ 9, 10]))
(3, 6, array([11, 12]))

# The number of elements in the resulting dataset is the same as
# the size of the smallest dataset in `datasets`.
d = tf.data.Dataset.range(13, 15)  # ==> [ 13, 14 ]
ds = tf.data.Dataset.zip((a, d))
list(ds.as_numpy_iterator())
[(1, 13), (2, 14)]

 Args
  datasets   A nested structure of datasets.

 Returns
  Dataset   A Dataset.    __bool__ View source
__bool__()
 __iter__ View source
__iter__()
 Creates an iterator for elements of this dataset. The returned iterator implements the Python Iterator protocol.

 Returns   An tf.data.Iterator for the elements of this dataset.

 Raises
  RuntimeError   If not inside of tf.function and not executing eagerly.    __len__ View source
__len__()
 Returns the length of the dataset if it is known and finite. This method requires that you are running in eager mode, and that the length of the dataset is known and non-infinite. When the length may be unknown or infinite, or if you are running in graph mode, use tf.data.Dataset.cardinality instead.

 Returns   An integer representing the length of the dataset.

 Raises
  RuntimeError   If the dataset length is unknown or infinite, or if eager execution is not enabled.    __nonzero__ View source
__nonzero__()


Module: tf.compat.v1.debugging Public API for tf.debugging namespace. Modules experimental module: Public API for tf.debugging.experimental namespace. Functions Assert(...): Asserts that the given condition is true. assert_all_finite(...): Assert that the tensor does not contain any NaN's or Inf's. assert_equal(...): Assert the condition x == y holds element-wise. assert_greater(...): Assert the condition x > y holds element-wise. assert_greater_equal(...): Assert the condition x >= y holds element-wise. assert_integer(...): Assert that x is of integer dtype. assert_less(...): Assert the condition x < y holds element-wise. assert_less_equal(...): Assert the condition x <= y holds element-wise. assert_near(...): Assert the condition x and y are close element-wise. assert_negative(...): Assert the condition x < 0 holds element-wise. assert_non_negative(...): Assert the condition x >= 0 holds element-wise. assert_non_positive(...): Assert the condition x <= 0 holds element-wise. assert_none_equal(...): Assert the condition x != y holds element-wise. assert_positive(...): Assert the condition x > 0 holds element-wise. assert_proper_iterable(...): Static assert that values is a "proper" iterable. assert_rank(...): Assert x has rank equal to rank. assert_rank_at_least(...): Assert x has rank equal to rank or higher. assert_rank_in(...): Assert x has rank in ranks. assert_same_float_dtype(...): Validate and return float type based on tensors and dtype. assert_scalar(...): Asserts that the given tensor is a scalar (i.e. zero-dimensional). assert_shapes(...): Assert tensor shapes and dimension size relationships between tensors. assert_type(...): Statically asserts that the given Tensor is of the specified type. check_numerics(...): Checks a tensor for NaN and Inf values. disable_check_numerics(...): Disable the eager/graph unified numerics checking mechanism. enable_check_numerics(...): Enable tensor numerics checking in an eager/graph unified fashion. get_log_device_placement(...): Get if device placements are logged. is_finite(...): Returns which elements of x are finite. is_inf(...): Returns which elements of x are Inf. is_nan(...): Returns which elements of x are NaN. is_non_decreasing(...): Returns True if x is non-decreasing. is_numeric_tensor(...): Returns True if the elements of tensor are numbers. is_strictly_increasing(...): Returns True if x is strictly increasing. set_log_device_placement(...): Set if device placements should be logged.


tf.compat.v1.debugging.assert_shapes Assert tensor shapes and dimension size relationships between tensors.
tf.compat.v1.debugging.assert_shapes(
    shapes, data=None, summarize=None, message=None, name=None
)
 This Op checks that a collection of tensors shape relationships satisfies given constraints. Example:
n = 10
q = 3
d = 7
x = tf.zeros([n,q])
y = tf.ones([n,d])
param = tf.Variable([1.0, 2.0, 3.0])
scalar = 1.0
tf.debugging.assert_shapes([
 (x, ('N', 'Q')),
 (y, ('N', 'D')),
 (param, ('Q',)),
 (scalar, ()),
])

tf.debugging.assert_shapes([
  (x, ('N', 'D')),
  (y, ('N', 'D'))
])
Traceback (most recent call last):

ValueError: ...
 Example of adding a dependency to an operation: with tf.control_dependencies([tf.assert_shapes(shapes)]):
  output = tf.matmul(x, y, transpose_a=True)
 If x, y, param or scalar does not have a shape that satisfies all specified constraints, message, as well as the first summarize entries of the first encountered violating tensor are printed, and InvalidArgumentError is raised. Size entries in the specified shapes are checked against other entries by their hash, except:  a size entry is interpreted as an explicit size if it can be parsed as an integer primitive. a size entry is interpreted as any size if it is None or '.'.  If the first entry of a shape is ... (type Ellipsis) or '*' that indicates a variable number of outer dimensions of unspecified size, i.e. the constraint applies to the inner-most dimensions only. Scalar tensors and specified shapes of length zero (excluding the 'inner-most' prefix) are both treated as having a single dimension of size one.

 Args
  shapes   A list of (Tensor, shape) tuples, wherein shape is the expected shape of Tensor. See the example code above. The shape must be an iterable. Each element of the iterable can be either a concrete integer value or a string that abstractly represents the dimension. For example,
('N', 'Q') specifies a 2D shape wherein the first and second dimensions of shape may or may not be equal.
('N', 'N', 'Q') specifies a 3D shape wherein the first and second dimensions are equal.
(1, 'N') specifies a 2D shape wherein the first dimension is exactly 1 and the second dimension can be any value. Note that the abstract dimension letters take effect across different tuple elements of the list. For example, tf.debugging.assert_shapes([(x, ('N', 'A')), (y, ('N', 'B'))] asserts that both x and y are rank-2 tensors and their first dimensions are equal (N). shape can also be a tf.TensorShape.

  data   The tensors to print out if the condition is False. Defaults to error message and first few entries of the violating tensor.
  summarize   Print this many entries of the tensor.
  message   A string to prefix to the default message.
  name   A name for this operation (optional). Defaults to "assert_shapes".

 Returns   Op raising InvalidArgumentError unless all shape constraints are satisfied. If static checks determine all constraints are satisfied, a no_op is returned.

 Raises
  ValueError   If static checks determine any shape constraint is violated.


Module: tf.compat.v1.debugging.experimental Public API for tf.debugging.experimental namespace. Functions disable_dump_debug_info(...): Disable the currently-enabled debugging dumping. enable_dump_debug_info(...): Enable dumping debugging information from a TensorFlow program.


tf.compat.v1.decode_csv Convert CSV records to tensors. Each column maps to one tensor.  View aliases  Compat aliases for migration
See Migration guide for more details. tf.compat.v1.io.decode_csv
tf.compat.v1.decode_csv(
    records, record_defaults, field_delim=',', use_quote_delim=True,
    name=None, na_value='', select_cols=None
)
 RFC 4180 format is expected for the CSV records. (https://tools.ietf.org/html/rfc4180) Note that we allow leading and trailing spaces with int or float field.

 Args
  records   A Tensor of type string. Each string is a record/row in the csv and all records should have the same format.
  record_defaults   A list of Tensor objects with specific types. Acceptable types are float32, float64, int32, int64, string. One tensor per column of the input record, with either a scalar default value for that column or an empty vector if the column is required.
  field_delim   An optional string. Defaults to ",". char delimiter to separate fields in a record.
  use_quote_delim   An optional bool. Defaults to True. If false, treats double quotation marks as regular characters inside of the string fields (ignoring RFC 4180, Section 2, Bullet 5).
  name   A name for the operation (optional).
  na_value   Additional string to recognize as NA/NaN.
  select_cols   Optional sorted list of column indices to select. If specified, only this subset of columns will be parsed and returned.

 Returns   A list of Tensor objects. Has the same type as record_defaults. Each tensor will have the same shape as records.

 Raises
  ValueError   If any of the arguments is malformed.


tf.compat.v1.decode_raw Convert raw byte strings into tensors. (deprecated arguments)  View aliases  Compat aliases for migration
See Migration guide for more details. tf.compat.v1.io.decode_raw
tf.compat.v1.decode_raw(
    input_bytes=None, out_type=None, little_endian=True, name=None, bytes=None
)
 Warning: SOME ARGUMENTS ARE DEPRECATED: (bytes). They will be removed in a future version. Instructions for updating: bytes is deprecated, use input_bytes instead

 Args
  input_bytes   Each element of the input Tensor is converted to an array of bytes.
  out_type   DType of the output. Acceptable types are half, float, double, int32, uint16, uint8, int16, int8, int64.
  little_endian   Whether the input_bytes data is in little-endian format. Data will be converted into host byte order if necessary.
  name   A name for the operation (optional).
  bytes   Deprecated parameter. Use input_bytes instead.

 Returns   A Tensor object storing the decoded bytes.


tf.compat.v1.delete_session_tensor Delete the tensor for the given tensor handle.
tf.compat.v1.delete_session_tensor(
    handle, name=None
)
 This is EXPERIMENTAL and subject to change. Delete the tensor of a given tensor handle. The tensor is produced in a previous run() and stored in the state of the session.

 Args
  handle   The string representation of a persistent tensor handle.
  name   Optional name prefix for the return tensor.

 Returns   A pair of graph elements. The first is a placeholder for feeding a tensor handle and the second is a deletion operation.


tf.compat.v1.depth_to_space DepthToSpace for tensors of type T.  View aliases  Compat aliases for migration
See Migration guide for more details. tf.compat.v1.nn.depth_to_space
tf.compat.v1.depth_to_space(
    input, block_size, name=None, data_format='NHWC'
)
 Rearranges data from depth into blocks of spatial data. This is the reverse transformation of SpaceToDepth. More specifically, this op outputs a copy of the input tensor where values from the depth dimension are moved in spatial blocks to the height and width dimensions. The attr block_size indicates the input block size and how the data is moved.  Chunks of data of size block_size * block_size from depth are rearranged into non-overlapping blocks of size block_size x block_size
 The width the output tensor is input_depth * block_size, whereas the height is input_height * block_size. The Y, X coordinates within each block of the output image are determined by the high order component of the input channel index. The depth of the input tensor must be divisible by block_size * block_size.  The data_format attr specifies the layout of the input and output tensors with the following options: "NHWC": [ batch, height, width, channels ] "NCHW": [ batch, channels, height, width ] "NCHW_VECT_C": qint8 [ batch, channels / 4, height, width, 4 ] It is useful to consider the operation as transforming a 6-D Tensor. e.g. for data_format = NHWC, Each element in the input tensor can be specified via 6 coordinates, ordered by decreasing memory layout significance as: n,iY,iX,bY,bX,oC (where n=batch index, iX, iY means X or Y coordinates within the input image, bX, bY means coordinates within the output block, oC means output channels). The output would be the input transposed to the following layout: n,iY,bY,iX,bX,oC This operation is useful for resizing the activations between convolutions (but keeping all data), e.g. instead of pooling. It is also useful for training purely convolutional models. For example, given an input of shape [1, 1, 1, 4], data_format = "NHWC" and block_size = 2: x = [[[[1, 2, 3, 4]]]]

 This operation will output a tensor of shape [1, 2, 2, 1]: [[[[1], [2]],
  [[3], [4]]]]
 Here, the input has a batch of 1 and each batch element has shape [1, 1, 4], the corresponding output will have 2x2 elements and will have a depth of 1 channel (1 = 4 / (block_size * block_size)). The output element shape is [2, 2, 1]. For an input tensor with larger depth, here of shape [1, 1, 1, 12], e.g. x = [[[[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]]]]
 This operation, for block size of 2, will return the following tensor of shape [1, 2, 2, 3] [[[[1, 2, 3], [4, 5, 6]],
  [[7, 8, 9], [10, 11, 12]]]]

 Similarly, for the following input of shape [1 2 2 4], and a block size of 2: x =  [[[[1, 2, 3, 4],
       [5, 6, 7, 8]],
      [[9, 10, 11, 12],
       [13, 14, 15, 16]]]]
 the operator will return the following tensor of shape [1 4 4 1]: x = [[[ [1],   [2],  [5],  [6]],
      [ [3],   [4],  [7],  [8]],
      [ [9],  [10], [13],  [14]],
      [ [11], [12], [15],  [16]]]]

 Args
  input   A Tensor.
  block_size   An int that is >= 2. The size of the spatial block, same as in Space2Depth.
  data_format   An optional string from: "NHWC", "NCHW", "NCHW_VECT_C". Defaults to "NHWC".
  name   A name for the operation (optional).

 Returns   A Tensor. Has the same type as input.


tf.compat.v1.device Wrapper for Graph.device() using the default graph.
tf.compat.v1.device(
    device_name_or_function
)
 See tf.Graph.device for more details.

 Args
  device_name_or_function   The device name or function to use in the context.

 Returns   A context manager that specifies the default device to use for newly created ops.

 Raises
  RuntimeError   If eager execution is enabled and a function is passed in.


tf.compat.v1.DeviceSpec Represents a (possibly partial) specification for a TensorFlow device. Inherits From: DeviceSpec
tf.compat.v1.DeviceSpec(
    job=None, replica=None, task=None, device_type=None, device_index=None
)
 DeviceSpecs are used throughout TensorFlow to describe where state is stored and computations occur. Using DeviceSpec allows you to parse device spec strings to verify their validity, merge them or compose them programmatically. Example: # Place the operations on device "GPU:0" in the "ps" job.
device_spec = DeviceSpec(job="ps", device_type="GPU", device_index=0)
with tf.device(device_spec.to_string()):
  # Both my_var and squared_var will be placed on /job:ps/device:GPU:0.
  my_var = tf.Variable(..., name="my_variable")
  squared_var = tf.square(my_var)
 With eager execution disabled (by default in TensorFlow 1.x and by calling disable_eager_execution() in TensorFlow 2.x), the following syntax can be used: tf.compat.v1.disable_eager_execution()

# Same as previous
device_spec = DeviceSpec(job="ps", device_type="GPU", device_index=0)
# No need of .to_string() method.
with tf.device(device_spec):
  my_var = tf.Variable(..., name="my_variable")
  squared_var = tf.square(my_var)
 ```

If a `DeviceSpec` is partially specified, it will be merged with other
`DeviceSpec`s according to the scope in which it is defined. `DeviceSpec`
components defined in inner scopes take precedence over those defined in
outer scopes.

```python
gpu0_spec = DeviceSpec(job="ps", device_type="GPU", device_index=0)
with tf.device(DeviceSpec(job="train").to_string()):
  with tf.device(gpu0_spec.to_string()):
    # Nodes created here will be assigned to /job:ps/device:GPU:0.
  with tf.device(DeviceSpec(device_type="GPU", device_index=1).to_string()):
    # Nodes created here will be assigned to /job:train/device:GPU:1.
 A DeviceSpec consists of 5 components -- each of which is optionally specified:  Job: The job name. Replica: The replica index. Task: The task index. Device type: The device type string (e.g. "CPU" or "GPU"). Device index: The device index.

 Args
  job   string. Optional job name.
  replica   int. Optional replica index.
  task   int. Optional task index.
  device_type   Optional device type string (e.g. "CPU" or "GPU")
  device_index   int. Optional device index. If left unspecified, device represents 'any' device_index.

 Attributes
  device_index

  device_type

  job

  replica

  task
   Methods from_string View source
@classmethod
from_string(
    spec
)
 Construct a DeviceSpec from a string.

 Args
  spec   a string of the form /job:/replica:/task:/device:CPU: or /job:/replica:/task:/device:GPU: as cpu and gpu are mutually exclusive. All entries are optional.

 Returns   A DeviceSpec.
 make_merged_spec View source
make_merged_spec(
    dev
)
 Returns a new DeviceSpec which incorporates dev. When combining specs, dev will take precedence over the current spec. So for instance: first_spec = tf.DeviceSpec(job=0, device_type="CPU")
second_spec = tf.DeviceSpec(device_type="GPU")
combined_spec = first_spec.make_merged_spec(second_spec)
 is equivalent to: combined_spec = tf.DeviceSpec(job=0, device_type="GPU")

 Args
  dev   a DeviceSpec

 Returns   A new DeviceSpec which combines self and dev
 merge_from View source
merge_from(
    dev
)
 Merge the properties of "dev" into this DeviceSpec.
Note: Will be removed in TensorFlow 2.x since DeviceSpecs will become immutable.

 Args
  dev   a DeviceSpec.    parse_from_string View source
parse_from_string(
    spec
)
 Parse a DeviceSpec name into its components. 2.x behavior change: In TensorFlow 1.x, this function mutates its own state and returns itself. In 2.x, DeviceSpecs are immutable, and this function will return a DeviceSpec which contains the spec. Recommended: ```
# my_spec and my_updated_spec are unrelated.
my_spec = tf.DeviceSpec.from_string("/CPU:0")
my_updated_spec = tf.DeviceSpec.from_string("/GPU:0")
with tf.device(my_updated_spec):
  ...
```
 Will work in 1.x and 2.x (though deprecated in 2.x): ```
my_spec = tf.DeviceSpec.from_string("/CPU:0")
my_updated_spec = my_spec.parse_from_string("/GPU:0")
with tf.device(my_updated_spec):
  ...
```
 Will NOT work in 2.x: ```
my_spec = tf.DeviceSpec.from_string("/CPU:0")
my_spec.parse_from_string("/GPU:0")  # <== Will not update my_spec
with tf.device(my_spec):
  ...
```
 In general, DeviceSpec.from_string should completely replace DeviceSpec.parse_from_string, and DeviceSpec.replace should completely replace setting attributes directly.

 Args
  spec   an optional string of the form /job:/replica:/task:/device:CPU: or /job:/replica:/task:/device:GPU: as cpu and gpu are mutually exclusive. All entries are optional.

 Returns   The DeviceSpec.

 Raises
  ValueError   if the spec was not valid.    replace View source
replace(
    **kwargs
)
 Convenience method for making a new DeviceSpec by overriding fields. For instance: my_spec = DeviceSpec=(job="my_job", device="CPU")
my_updated_spec = my_spec.replace(device="GPU")
my_other_spec = my_spec.replace(device=None)

 Args
  **kwargs   This method takes the same args as the DeviceSpec constructor

 Returns   A DeviceSpec with the fields specified in kwargs overridden.
 to_string View source
to_string()
 Return a string representation of this DeviceSpec.

 Returns   a string of the form /job:/replica:/task:/device::.

 __eq__ View source
__eq__(
    other
)
 Checks if the other DeviceSpec is same as the current instance, eg have same value for all the internal fields.

 Args
  other   Another DeviceSpec

 Returns   Return True if other is also a DeviceSpec instance and has same value as the current instance. Return False otherwise.


tf.compat.v1.Dimension Represents the value of one dimension in a TensorShape.
tf.compat.v1.Dimension(
    value
)

 Attributes
  value   The value of this dimension, or None if it is unknown.    Methods assert_is_compatible_with View source
assert_is_compatible_with(
    other
)
 Raises an exception if other is not compatible with this Dimension.

 Args
  other   Another Dimension.

 Raises
  ValueError   If self and other are not compatible (see is_compatible_with).    is_compatible_with View source
is_compatible_with(
    other
)
 Returns true if other is compatible with this Dimension. Two known Dimensions are compatible if they have the same value. An unknown Dimension is compatible with all other Dimensions.

 Args
  other   Another Dimension.

 Returns   True if this Dimension and other are compatible.
 merge_with View source
merge_with(
    other
)
 Returns a Dimension that combines the information in self and other. Dimensions are combined as follows: tf.compat.v1.Dimension(n)   .merge_with(tf.compat.v1.Dimension(n))     ==
tf.compat.v1.Dimension(n)
tf.compat.v1.Dimension(n)   .merge_with(tf.compat.v1.Dimension(None))  ==
tf.compat.v1.Dimension(n)
tf.compat.v1.Dimension(None).merge_with(tf.compat.v1.Dimension(n))     ==
tf.compat.v1.Dimension(n)
# equivalent to tf.compat.v1.Dimension(None)
tf.compat.v1.Dimension(None).merge_with(tf.compat.v1.Dimension(None))

# raises ValueError for n != m
tf.compat.v1.Dimension(n)   .merge_with(tf.compat.v1.Dimension(m))

 Args
  other   Another Dimension.

 Returns   A Dimension containing the combined information of self and other.

 Raises
  ValueError   If self and other are not compatible (see is_compatible_with).    __add__ View source
__add__(
    other
)
 Returns the sum of self and other. Dimensions are summed as follows: tf.compat.v1.Dimension(m)    + tf.compat.v1.Dimension(n)     ==
tf.compat.v1.Dimension(m + n)
tf.compat.v1.Dimension(m)    + tf.compat.v1.Dimension(None)  # equiv. to
tf.compat.v1.Dimension(None)
tf.compat.v1.Dimension(None) + tf.compat.v1.Dimension(n)     # equiv. to
tf.compat.v1.Dimension(None)
tf.compat.v1.Dimension(None) + tf.compat.v1.Dimension(None)  # equiv. to
tf.compat.v1.Dimension(None)

 Args
  other   Another Dimension, or a value accepted by as_dimension.

 Returns   A Dimension whose value is the sum of self and other.
 __div__ View source
__div__(
    other
)
 DEPRECATED: Use __floordiv__ via x // y instead. This function exists only for backwards compatibility purposes; new code should use __floordiv__ via the syntax x // y. Using x // y communicates clearly that the result rounds down, and is forward compatible to Python 3.

 Args
  other   Another Dimension.

 Returns   A Dimension whose value is the integer quotient of self and other.
 __eq__ View source
__eq__(
    other
)
 Returns true if other has the same known value as this Dimension. __floordiv__ View source
__floordiv__(
    other
)
 Returns the quotient of self and other rounded down. Dimensions are divided as follows: tf.compat.v1.Dimension(m)    // tf.compat.v1.Dimension(n)     ==
tf.compat.v1.Dimension(m // n)
tf.compat.v1.Dimension(m)    // tf.compat.v1.Dimension(None)  # equiv. to
tf.compat.v1.Dimension(None)
tf.compat.v1.Dimension(None) // tf.compat.v1.Dimension(n)     # equiv. to
tf.compat.v1.Dimension(None)
tf.compat.v1.Dimension(None) // tf.compat.v1.Dimension(None)  # equiv. to
tf.compat.v1.Dimension(None)

 Args
  other   Another Dimension, or a value accepted by as_dimension.

 Returns   A Dimension whose value is the integer quotient of self and other.
 __ge__ View source
__ge__(
    other
)
 Returns True if self is known to be greater than or equal to other. Dimensions are compared as follows: (tf.compat.v1.Dimension(m)    >= tf.compat.v1.Dimension(n))    == (m >= n)
(tf.compat.v1.Dimension(m)    >= tf.compat.v1.Dimension(None)) == None
(tf.compat.v1.Dimension(None) >= tf.compat.v1.Dimension(n))    == None
(tf.compat.v1.Dimension(None) >= tf.compat.v1.Dimension(None)) == None

 Args
  other   Another Dimension.

 Returns   The value of self.value >= other.value if both are known, otherwise None.
 __gt__ View source
__gt__(
    other
)
 Returns True if self is known to be greater than other. Dimensions are compared as follows: (tf.compat.v1.Dimension(m)    > tf.compat.v1.Dimension(n))    == (m > n)
(tf.compat.v1.Dimension(m)    > tf.compat.v1.Dimension(None)) == None
(tf.compat.v1.Dimension(None) > tf.compat.v1.Dimension(n))    == None
(tf.compat.v1.Dimension(None) > tf.compat.v1.Dimension(None)) == None

 Args
  other   Another Dimension.

 Returns   The value of self.value > other.value if both are known, otherwise None.
 __le__ View source
__le__(
    other
)
 Returns True if self is known to be less than or equal to other. Dimensions are compared as follows: (tf.compat.v1.Dimension(m)    <= tf.compat.v1.Dimension(n))    == (m <= n)
(tf.compat.v1.Dimension(m)    <= tf.compat.v1.Dimension(None)) == None
(tf.compat.v1.Dimension(None) <= tf.compat.v1.Dimension(n))    == None
(tf.compat.v1.Dimension(None) <= tf.compat.v1.Dimension(None)) == None

 Args
  other   Another Dimension.

 Returns   The value of self.value <= other.value if both are known, otherwise None.
 __lt__ View source
__lt__(
    other
)
 Returns True if self is known to be less than other. Dimensions are compared as follows: (tf.compat.v1.Dimension(m)    < tf.compat.v1.Dimension(n))    == (m < n)
(tf.compat.v1.Dimension(m)    < tf.compat.v1.Dimension(None)) == None
(tf.compat.v1.Dimension(None) < tf.compat.v1.Dimension(n))    == None
(tf.compat.v1.Dimension(None) < tf.compat.v1.Dimension(None)) == None

 Args
  other   Another Dimension.

 Returns   The value of self.value < other.value if both are known, otherwise None.
 __mod__ View source
__mod__(
    other
)
 Returns self modulo other. Dimension modulo are computed as follows: tf.compat.v1.Dimension(m)    % tf.compat.v1.Dimension(n)     ==
tf.compat.v1.Dimension(m % n)
tf.compat.v1.Dimension(m)    % tf.compat.v1.Dimension(None)  # equiv. to
tf.compat.v1.Dimension(None)
tf.compat.v1.Dimension(None) % tf.compat.v1.Dimension(n)     # equiv. to
tf.compat.v1.Dimension(None)
tf.compat.v1.Dimension(None) % tf.compat.v1.Dimension(None)  # equiv. to
tf.compat.v1.Dimension(None)

 Args
  other   Another Dimension, or a value accepted by as_dimension.

 Returns   A Dimension whose value is self modulo other.
 __mul__ View source
__mul__(
    other
)
 Returns the product of self and other. Dimensions are summed as follows: tf.compat.v1.Dimension(m)    * tf.compat.v1.Dimension(n)     ==
tf.compat.v1.Dimension(m * n)
tf.compat.v1.Dimension(m)    * tf.compat.v1.Dimension(None)  # equiv. to
tf.compat.v1.Dimension(None)
tf.compat.v1.Dimension(None) * tf.compat.v1.Dimension(n)     # equiv. to
tf.compat.v1.Dimension(None)
tf.compat.v1.Dimension(None) * tf.compat.v1.Dimension(None)  # equiv. to
tf.compat.v1.Dimension(None)

 Args
  other   Another Dimension, or a value accepted by as_dimension.

 Returns   A Dimension whose value is the product of self and other.
 __ne__ View source
__ne__(
    other
)
 Returns true if other has a different known value from self. __radd__ View source
__radd__(
    other
)
 Returns the sum of other and self.

 Args
  other   Another Dimension, or a value accepted by as_dimension.

 Returns   A Dimension whose value is the sum of self and other.
 __rdiv__ View source
__rdiv__(
    other
)
 Use __floordiv__ via x // y instead. This function exists only to have a better error message. Instead of: TypeError: unsupported operand type(s) for /: 'int' and 'Dimension', this function will explicitly call for usage of // instead.

 Args
  other   Another Dimension.

 Raises   TypeError.
 __rfloordiv__ View source
__rfloordiv__(
    other
)
 Returns the quotient of other and self rounded down.

 Args
  other   Another Dimension, or a value accepted by as_dimension.

 Returns   A Dimension whose value is the integer quotient of self and other.
 __rmod__ View source
__rmod__(
    other
)
 Returns other modulo self.

 Args
  other   Another Dimension, or a value accepted by as_dimension.

 Returns   A Dimension whose value is other modulo self.
 __rmul__ View source
__rmul__(
    other
)
 Returns the product of self and other.

 Args
  other   Another Dimension, or a value accepted by as_dimension.

 Returns   A Dimension whose value is the product of self and other.
 __rsub__ View source
__rsub__(
    other
)
 Returns the subtraction of self from other.

 Args
  other   Another Dimension, or a value accepted by as_dimension.

 Returns   A Dimension whose value is the subtraction of self from other.
 __rtruediv__ View source
__rtruediv__(
    other
)
 Use __floordiv__ via x // y instead. This function exists only to have a better error message. Instead of: TypeError: unsupported operand type(s) for /: 'int' and 'Dimension', this function will explicitly call for usage of // instead.

 Args
  other   Another Dimension.

 Raises   TypeError.
 __sub__ View source
__sub__(
    other
)
 Returns the subtraction of other from self. Dimensions are subtracted as follows: tf.compat.v1.Dimension(m)    - tf.compat.v1.Dimension(n)     ==
tf.compat.v1.Dimension(m - n)
tf.compat.v1.Dimension(m)    - tf.compat.v1.Dimension(None)  # equiv. to
tf.compat.v1.Dimension(None)
tf.compat.v1.Dimension(None) - tf.compat.v1.Dimension(n)     # equiv. to
tf.compat.v1.Dimension(None)
tf.compat.v1.Dimension(None) - tf.compat.v1.Dimension(None)  # equiv. to
tf.compat.v1.Dimension(None)

 Args
  other   Another Dimension, or a value accepted by as_dimension.

 Returns   A Dimension whose value is the subtraction of other from self.
 __truediv__ View source
__truediv__(
    other
)
 Use __floordiv__ via x // y instead. This function exists only to have a better error message. Instead of: TypeError: unsupported operand type(s) for /: 'Dimension' and 'int', this function will explicitly call for usage of // instead.

 Args
  other   Another Dimension.

 Raises   TypeError.


tf.compat.v1.disable_control_flow_v2 Opts out of control flow v2.
tf.compat.v1.disable_control_flow_v2()

Note: v2 control flow is always enabled inside of tf.function. Calling this function has no effect in that case.
 If your code needs tf.disable_control_flow_v2() to be called to work properly please file a bug.


tf.compat.v1.disable_eager_execution Disables eager execution.
tf.compat.v1.disable_eager_execution()
 This function can only be called before any Graphs, Ops, or Tensors have been created. It can be used at the beginning of the program for complex migration projects from TensorFlow 1.x to 2.x.


tf.compat.v1.disable_resource_variables Opts out of resource variables. (deprecated)
tf.compat.v1.disable_resource_variables()
 Warning: THIS FUNCTION IS DEPRECATED. It will be removed in a future version. Instructions for updating: non-resource variables are not supported in the long term If your code needs tf.disable_resource_variables() to be called to work properly please file a bug.


tf.compat.v1.disable_tensor_equality Compare Tensors by their id and be hashable.
tf.compat.v1.disable_tensor_equality()
 This is a legacy behaviour of TensorFlow and is highly discouraged.


tf.compat.v1.disable_v2_behavior Disables TensorFlow 2.x behaviors.
tf.compat.v1.disable_v2_behavior()
 This function can be called at the beginning of the program (before Tensors, Graphs or other structures have been created, and before devices have been initialized. It switches all global behaviors that are different between TensorFlow 1.x and 2.x to behave as intended for 1.x. User can call this function to disable 2.x behavior during complex migrations.


tf.compat.v1.disable_v2_tensorshape Disables the V2 TensorShape behavior and reverts to V1 behavior.
tf.compat.v1.disable_v2_tensorshape()
 See docstring for enable_v2_tensorshape for details about the new behavior.


Module: tf.compat.v1.distribute Library for running a computation across multiple devices. The intent of this library is that you can write an algorithm in a stylized way and it will be usable with a variety of different tf.distribute.Strategy implementations. Each descendant will implement a different strategy for distributing the algorithm across multiple devices/machines. Furthermore, these changes can be hidden inside the specific layers and other library classes that need special treatment to run in a distributed setting, so that most users' model definition code can run unchanged. The tf.distribute.Strategy API works the same way with eager and graph execution. Guides  TensorFlow v2.x TensorFlow v1.x  Tutorials
Distributed Training Tutorials The tutorials cover how to use tf.distribute.Strategy to do distributed training with native Keras APIs, custom training loops, and Esitmator APIs. They also cover how to save/load model when using tf.distribute.Strategy.
  Glossary
Data parallelism is where we run multiple copies of the model on different slices of the input data. This is in contrast to model parallelism where we divide up a single copy of a model across multiple devices. Note: we only support data parallelism for now, but hope to add support for model parallelism in the future. A device is a CPU or accelerator (e.g. GPUs, TPUs) on some machine that TensorFlow can run operations on (see e.g. tf.device). You may have multiple devices on a single machine, or be connected to devices on multiple machines. Devices used to run computations are called worker devices. Devices used to store variables are parameter devices. For some strategies, such as tf.distribute.MirroredStrategy, the worker and parameter devices will be the same (see mirrored variables below). For others they will be different. For example, tf.distribute.experimental.CentralStorageStrategy puts the variables on a single device (which may be a worker device or may be the CPU), and tf.distribute.experimental.ParameterServerStrategy puts the variables on separate machines called parameter servers (see below). A replica is one copy of the model, running on one slice of the input data. Right now each replica is executed on its own worker device, but once we add support for model parallelism a replica may span multiple worker devices. A host is the CPU device on a machine with worker devices, typically used for running input pipelines. A worker is defined to be the physical machine(s) containing the physical devices (e.g. GPUs, TPUs) on which the replicated computation is executed. A worker may contain one or more replicas, but contains at least one replica. Typically one worker will correspond to one machine, but in the case of very large models with model parallelism, one worker may span multiple machines. We typically run one input pipeline per worker, feeding all the replicas on that worker.
Synchronous, or more commonly sync, training is where the updates from each replica are aggregated together before updating the model variables. This is in contrast to asynchronous, or async training, where each replica updates the model variables independently. You may also have replicas partitioned into groups which are in sync within each group but async between groups. Parameter servers: These are machines that hold a single copy of parameters/variables, used by some strategies (right now just tf.distribute.experimental.ParameterServerStrategy). All replicas that want to operate on a variable retrieve it at the beginning of a step and send an update to be applied at the end of the step. These can in priniciple support either sync or async training, but right now we only have support for async training with parameter servers. Compare to tf.distribute.experimental.CentralStorageStrategy, which puts all variables on a single device on the same machine (and does sync training), and tf.distribute.MirroredStrategy, which mirrors variables to multiple devices (see below).
Replica context vs. Cross-replica context vs Update context A replica context applies when you execute the computation function that was called with strategy.run. Conceptually, you're in replica context when executing the computation function that is being replicated. An update context is entered in a tf.distribute.StrategyExtended.update call. An cross-replica context is entered when you enter a strategy.scope. This is useful for calling tf.distribute.Strategy methods which operate across the replicas (like reduce_to()). By default you start in a replica context (the "default single replica context") and then some methods can switch you back and forth.

Distributed value: Distributed value is represented by the base class tf.distribute.DistributedValues. tf.distribute.DistributedValues is useful to represent values on multiple devices, and it contains a map from replica id to values. Two representative kinds of tf.distribute.DistributedValues are "PerReplica" and "Mirrored" values. "PerReplica" values exist on the worker devices, with a different value for each replica. They are produced by iterating through a distributed dataset returned by tf.distribute.Strategy.experimental_distribute_dataset and tf.distribute.Strategy.distribute_datasets_from_function. They are also the typical result returned by tf.distribute.Strategy.run. "Mirrored" values are like "PerReplica" values, except we know that the value on all replicas are the same. We can safely read a "Mirrored" value in a cross-replica context by using the value on any replica.
 Unwrapping and merging: Consider calling a function fn on multiple replicas, like strategy.run(fn, args=[w]) with an argument w that is a tf.distribute.DistributedValues. This means w will have a map taking replica id 0 to w0, replica id 1 to w1, etc. strategy.run() unwraps w before calling fn, so it calls fn(w0) on device d0, fn(w1) on device d1, etc. It then merges the return values from fn(), which leads to one common object if the returned values are the same object from every replica, or a DistributedValues object otherwise. Reductions and all-reduce: A reduction is a method of aggregating multiple values into one value, like "sum" or "mean". If a strategy is doing sync training, we will perform a reduction on the gradients to a parameter from all replicas before applying the update. All-reduce is an algorithm for performing a reduction on values from multiple devices and making the result available on all of those devices. Mirrored variables: These are variables that are created on multiple devices, where we keep the variables in sync by applying the same updates to every copy. Mirrored variables are created with tf.Variable(...synchronization=tf.VariableSynchronization.ON_WRITE...). Normally they are only used in synchronous training.
SyncOnRead variables SyncOnRead variables are created by tf.Variable(...synchronization=tf.VariableSynchronization.ON_READ...), and they are created on multiple devices. In replica context, each component variable on the local replica can perform reads and writes without synchronization with each other. When the SyncOnRead variable is read in cross-replica context, the values from component variables are aggregated and returned. SyncOnRead variables bring a lot of custom configuration difficulty to the underlying logic, so we do not encourage users to instantiate and use SyncOnRead variable on their own. We have mainly used SyncOnRead variables for use cases such as batch norm and metrics. For performance reasons, we often don't need to keep these statistics in sync every step and they can be accumulated on each replica independently. The only time we want to sync them is reporting or checkpointing, which typically happens in cross-replica context. SyncOnRead variables are also often used by advanced users who want to control when variable values are aggregated. For example, users sometimes want to maintain gradients independently on each replica for a couple of steps without aggregation.

Distribute-aware layers Layers are generally called in a replica context, except when defining a Keras functional model. tf.distribute.in_cross_replica_context will let you determine which case you are in. If in a replica context, the tf.distribute.get_replica_context function will return the default replica context outside a strategy scope, None within a strategy scope, and a tf.distribute.ReplicaContext object inside a strategy scope and within a tf.distribute.Strategy.run function. The ReplicaContext object has an all_reduce method for aggregating across all replicas.
  Note that we provide a default version of tf.distribute.Strategy that is used when no other strategy is in scope, that provides the same API with reasonable default behavior. Modules cluster_resolver module: Library imports for ClusterResolvers. experimental module: Public API for tf.distribute.experimental namespace. Classes class CrossDeviceOps: Base class for cross-device reduction and broadcasting algorithms. class HierarchicalCopyAllReduce: Hierarchical copy all-reduce implementation of CrossDeviceOps. class InputContext: A class wrapping information needed by an input function. class InputReplicationMode: Replication mode for input function. class MirroredStrategy: Synchronous training across multiple replicas on one machine. class NcclAllReduce: NCCL all-reduce implementation of CrossDeviceOps. class OneDeviceStrategy: A distribution strategy for running on a single device. class ReduceOp: Indicates how a set of values should be reduced. class ReductionToOneDevice: A CrossDeviceOps implementation that copies values to one device to reduce. class ReplicaContext: A class with a collection of APIs that can be called in a replica context. class RunOptions: Run options for strategy.run. class Server: An in-process TensorFlow server, for use in distributed training. class Strategy: A list of devices with a state & compute distribution policy. class StrategyExtended: Additional APIs for algorithms that need to be distribution-aware. Functions experimental_set_strategy(...): Set a tf.distribute.Strategy as current without with strategy.scope(). get_loss_reduction(...): tf.distribute.ReduceOp corresponding to the last loss reduction. get_replica_context(...): Returns the current tf.distribute.ReplicaContext or None. get_strategy(...): Returns the current tf.distribute.Strategy object. has_strategy(...): Return if there is a current non-default tf.distribute.Strategy. in_cross_replica_context(...): Returns True if in a cross-replica context.


Module: tf.compat.v1.distribute.cluster_resolver Library imports for ClusterResolvers. This library contains all implementations of ClusterResolvers. ClusterResolvers are a way of specifying cluster information for distributed execution. Built on top of existing ClusterSpec framework, ClusterResolvers are a way for TensorFlow to communicate with various cluster management systems (e.g. GCE, AWS, etc...). Classes class ClusterResolver: Abstract class for all implementations of ClusterResolvers. class GCEClusterResolver: ClusterResolver for Google Compute Engine. class KubernetesClusterResolver: ClusterResolver for Kubernetes. class SimpleClusterResolver: Simple implementation of ClusterResolver that accepts all attributes. class SlurmClusterResolver: ClusterResolver for system with Slurm workload manager. class TFConfigClusterResolver: Implementation of a ClusterResolver which reads the TF_CONFIG EnvVar. class TPUClusterResolver: Cluster Resolver for Google Cloud TPUs. class UnionResolver: Performs a union on underlying ClusterResolvers.


Module: tf.compat.v1.distribute.experimental Public API for tf.distribute.experimental namespace. Classes class CentralStorageStrategy: A one-machine strategy that puts all variables on a single device. class CollectiveCommunication: Cross device communication implementation. class CollectiveHints: Hints for collective operations like AllReduce. class CommunicationImplementation: Cross device communication implementation. class CommunicationOptions: Options for cross device communications like All-reduce. class MultiWorkerMirroredStrategy: A distribution strategy for synchronous training on multiple workers. class ParameterServerStrategy: An asynchronous multi-worker parameter server tf.distribute strategy. class TPUStrategy: TPU distribution strategy implementation.