tf.compat.v1.cond Return true_fn() if the predicate pred is true else false_fn(). (deprecated arguments)
tf.compat.v1.cond(
    pred, true_fn=None, false_fn=None, strict=False, name=None, fn1=None, fn2=None
)
 Warning: SOME ARGUMENTS ARE DEPRECATED: (fn1, fn2). They will be removed in a future version. Instructions for updating: fn1/fn2 are deprecated in favor of the true_fn/false_fn arguments. true_fn and false_fn both return lists of output tensors. true_fn and false_fn must have the same non-zero number and type of outputs. Warning: Any Tensors or Operations created outside of true_fn and false_fn will be executed regardless of which branch is selected at runtime. Although this behavior is consistent with the dataflow model of TensorFlow, it has frequently surprised users who expected a lazier semantics. Consider the following simple program: z = tf.multiply(a, b)
result = tf.cond(x < y, lambda: tf.add(x, z), lambda: tf.square(y))
 If x < y, the tf.add operation will be executed and tf.square operation will not be executed. Since z is needed for at least one branch of the cond, the tf.multiply operation is always executed, unconditionally. Note that cond calls true_fn and false_fn exactly once (inside the call to cond, and not at all during Session.run()). cond stitches together the graph fragments created during the true_fn and false_fn calls with some additional graph nodes to ensure that the right branch gets executed depending on the value of pred. tf.cond supports nested structures as implemented in tensorflow.python.util.nest. Both true_fn and false_fn must return the same (possibly nested) value structure of lists, tuples, and/or named tuples. Singleton lists and tuples form the only exceptions to this: when returned by true_fn and/or false_fn, they are implicitly unpacked to single values. This behavior is disabled by passing strict=True.

 Args
  pred   A scalar determining whether to return the result of true_fn or false_fn.
  true_fn   The callable to be performed if pred is true.
  false_fn   The callable to be performed if pred is false.
  strict   A boolean that enables/disables 'strict' mode; see above.
  name   Optional name prefix for the returned tensors.

 Returns   Tensors returned by the call to either true_fn or false_fn. If the callables return a singleton list, the element is extracted from the list.

 Raises
  TypeError   if true_fn or false_fn is not callable.
  ValueError   if true_fn and false_fn do not return the same number of tensors, or return tensors of different types.    Example: x = tf.constant(2)
y = tf.constant(5)
def f1(): return tf.multiply(x, 17)
def f2(): return tf.add(y, 23)
r = tf.cond(tf.less(x, y), f1, f2)
# r is set to f1().
# Operations in f2 (e.g., tf.add) are not executed.


tf.compat.v1.ConditionalAccumulator A conditional accumulator for aggregating gradients. Inherits From: ConditionalAccumulatorBase
tf.compat.v1.ConditionalAccumulator(
    dtype, shape=None, shared_name=None, name='conditional_accumulator',
    reduction_type='MEAN'
)
 Up-to-date gradients (i.e., time step at which gradient was computed is equal to the accumulator's time step) are added to the accumulator. Extraction of the average gradient is blocked until the required number of gradients has been accumulated.

 Args
  dtype   Datatype of the accumulated gradients.
  shape   Shape of the accumulated gradients.
  shared_name   Optional. If non-empty, this accumulator will be shared under the given name across multiple sessions.
  name   Optional name for the accumulator.
  reduction_type   Reduction type to use when taking the gradient.

 Attributes
  accumulator_ref   The underlying accumulator reference.
  dtype   The datatype of the gradients accumulated by this accumulator.
  name   The name of the underlying accumulator.    Methods apply_grad View source
apply_grad(
    grad, local_step=0, name=None
)
 Attempts to apply a gradient to the accumulator. The attempt is silently dropped if the gradient is stale, i.e., local_step is less than the accumulator's global time step.

 Args
  grad   The gradient tensor to be applied.
  local_step   Time step at which the gradient was computed.
  name   Optional name for the operation.

 Returns   The operation that (conditionally) applies a gradient to the accumulator.

 Raises
  ValueError   If grad is of the wrong shape    num_accumulated View source
num_accumulated(
    name=None
)
 Number of gradients that have currently been aggregated in accumulator.

 Args
  name   Optional name for the operation.

 Returns   Number of accumulated gradients currently in accumulator.
 set_global_step View source
set_global_step(
    new_global_step, name=None
)
 Sets the global time step of the accumulator. The operation logs a warning if we attempt to set to a time step that is lower than the accumulator's own time step.

 Args
  new_global_step   Value of new time step. Can be a variable or a constant
  name   Optional name for the operation.

 Returns   Operation that sets the accumulator's time step.
 take_grad View source
take_grad(
    num_required, name=None
)
 Attempts to extract the average gradient from the accumulator. The operation blocks until sufficient number of gradients have been successfully applied to the accumulator. Once successful, the following actions are also triggered:  Counter of accumulated gradients is reset to 0. Aggregated gradient is reset to 0 tensor. Accumulator's internal time step is incremented by 1.

 Args
  num_required   Number of gradients that needs to have been aggregated
  name   Optional name for the operation

 Returns   A tensor holding the value of the average gradient.

 Raises
  InvalidArgumentError   If num_required < 1


tf.compat.v1.ConditionalAccumulatorBase A conditional accumulator for aggregating gradients.
tf.compat.v1.ConditionalAccumulatorBase(
    dtype, shape, accumulator_ref
)
 Up-to-date gradients (i.e., time step at which gradient was computed is equal to the accumulator's time step) are added to the accumulator. Extraction of the average gradient is blocked until the required number of gradients has been accumulated.

 Args
  dtype   Datatype of the accumulated gradients.
  shape   Shape of the accumulated gradients.
  accumulator_ref   A handle to the conditional accumulator, created by sub- classes

 Attributes
  accumulator_ref   The underlying accumulator reference.
  dtype   The datatype of the gradients accumulated by this accumulator.
  name   The name of the underlying accumulator.    Methods num_accumulated View source
num_accumulated(
    name=None
)
 Number of gradients that have currently been aggregated in accumulator.

 Args
  name   Optional name for the operation.

 Returns   Number of accumulated gradients currently in accumulator.
 set_global_step View source
set_global_step(
    new_global_step, name=None
)
 Sets the global time step of the accumulator. The operation logs a warning if we attempt to set to a time step that is lower than the accumulator's own time step.

 Args
  new_global_step   Value of new time step. Can be a variable or a constant
  name   Optional name for the operation.

 Returns   Operation that sets the accumulator's time step.


Module: tf.compat.v1.config Public API for tf.config namespace. Modules experimental module: Public API for tf.config.experimental namespace. optimizer module: Public API for tf.config.optimizer namespace. threading module: Public API for tf.config.threading namespace. Classes class LogicalDevice: Abstraction for a logical device initialized by the runtime. class LogicalDeviceConfiguration: Configuration class for a logical devices. class PhysicalDevice: Abstraction for a locally visible physical device. Functions experimental_connect_to_cluster(...): Connects to the given cluster. experimental_connect_to_host(...): Connects to a single machine to enable remote execution on it. experimental_functions_run_eagerly(...): Returns the value of the experimental_run_functions_eagerly setting. (deprecated) experimental_run_functions_eagerly(...): Enables / disables eager execution of tf.functions. (deprecated) functions_run_eagerly(...): Returns the value of the run_functions_eagerly setting. get_logical_device_configuration(...): Get the virtual device configuration for a tf.config.PhysicalDevice. get_soft_device_placement(...): Get if soft device placement is enabled. get_visible_devices(...): Get the list of visible physical devices. list_logical_devices(...): Return a list of logical devices created by runtime. list_physical_devices(...): Return a list of physical devices visible to the host runtime. run_functions_eagerly(...): Enables / disables eager execution of tf.functions. set_logical_device_configuration(...): Set the logical device configuration for a tf.config.PhysicalDevice. set_soft_device_placement(...): Set if soft device placement is enabled. set_visible_devices(...): Set the list of visible devices.


Module: tf.compat.v1.config.experimental Public API for tf.config.experimental namespace. Classes class ClusterDeviceFilters: Represent a collection of device filters for the remote workers in cluster. class VirtualDeviceConfiguration: Configuration class for a logical devices. Functions disable_mlir_bridge(...): Disables experimental MLIR-Based TensorFlow Compiler Bridge. disable_mlir_graph_optimization(...): Disables experimental MLIR-Based TensorFlow Compiler Optimizations. enable_mlir_bridge(...): Enables experimental MLIR-Based TensorFlow Compiler Bridge. enable_mlir_graph_optimization(...): Enables experimental MLIR-Based TensorFlow Compiler Optimizations. enable_tensor_float_32_execution(...): Enable or disable the use of TensorFloat-32 on supported hardware. get_device_details(...): Returns details about a physical devices. get_device_policy(...): Gets the current device policy. get_memory_growth(...): Get if memory growth is enabled for a PhysicalDevice. get_memory_usage(...): Get the memory usage, in bytes, for the chosen device. get_synchronous_execution(...): Gets whether operations are executed synchronously or asynchronously. get_virtual_device_configuration(...): Get the virtual device configuration for a tf.config.PhysicalDevice. get_visible_devices(...): Get the list of visible physical devices. list_logical_devices(...): Return a list of logical devices created by runtime. list_physical_devices(...): Return a list of physical devices visible to the host runtime. set_device_policy(...): Sets the current thread device policy. set_memory_growth(...): Set if memory growth should be enabled for a PhysicalDevice. set_synchronous_execution(...): Specifies whether operations are executed synchronously or asynchronously. set_virtual_device_configuration(...): Set the logical device configuration for a tf.config.PhysicalDevice. set_visible_devices(...): Set the list of visible devices. tensor_float_32_execution_enabled(...): Returns whether TensorFloat-32 is enabled.


Module: tf.compat.v1.config.optimizer Public API for tf.config.optimizer namespace. Functions get_experimental_options(...): Get experimental optimizer options. get_jit(...): Get if JIT compilation is enabled. set_experimental_options(...): Set experimental optimizer options. set_jit(...): Set if JIT compilation is enabled.


Module: tf.compat.v1.config.threading Public API for tf.config.threading namespace. Functions get_inter_op_parallelism_threads(...): Get number of threads used for parallelism between independent operations. get_intra_op_parallelism_threads(...): Get number of threads used within an individual op for parallelism. set_inter_op_parallelism_threads(...): Set number of threads used for parallelism between independent operations. set_intra_op_parallelism_threads(...): Set number of threads used within an individual op for parallelism.


tf.compat.v1.ConfigProto A ProtocolMessage

 Attributes
  allow_soft_placement   bool allow_soft_placement
  cluster_def   ClusterDef cluster_def
  device_count   repeated DeviceCountEntry device_count
  device_filters   repeated string device_filters
  experimental   Experimental experimental
  gpu_options   GPUOptions gpu_options
  graph_options   GraphOptions graph_options
  inter_op_parallelism_threads   int32 inter_op_parallelism_threads
  intra_op_parallelism_threads   int32 intra_op_parallelism_threads
  isolate_session_state   bool isolate_session_state
  log_device_placement   bool log_device_placement
  operation_timeout_in_ms   int64 operation_timeout_in_ms
  placement_period   int32 placement_period
  rpc_options   RPCOptions rpc_options
  session_inter_op_thread_pool   repeated ThreadPoolOptionProto session_inter_op_thread_pool
  share_cluster_devices_in_session   bool share_cluster_devices_in_session
  use_per_session_threads   bool use_per_session_threads    Child Classes class DeviceCountEntry class Experimental


tf.compat.v1.ConfigProto.DeviceCountEntry A ProtocolMessage

 Attributes
  key   string key
  value   int32 value


tf.compat.v1.ConfigProto.Experimental A ProtocolMessage

 Attributes
  collective_deterministic_sequential_execution   bool collective_deterministic_sequential_execution
  collective_group_leader   string collective_group_leader
  collective_nccl   bool collective_nccl
  disable_output_partition_graphs   bool disable_output_partition_graphs
  disable_thread_spinning   bool disable_thread_spinning
  enable_mlir_bridge   bool enable_mlir_bridge
  enable_mlir_graph_optimization   bool enable_mlir_graph_optimization
  executor_type   string executor_type
  mlir_bridge_rollout   MlirBridgeRollout mlir_bridge_rollout
  optimize_for_static_graph   bool optimize_for_static_graph
  recv_buf_max_chunk   int32 recv_buf_max_chunk
  session_metadata   SessionMetadata session_metadata
  share_cluster_devices_in_session   bool share_cluster_devices_in_session
  share_session_state_in_clusterspec_propagation   bool share_session_state_in_clusterspec_propagation
  use_numa_affinity   bool use_numa_affinity
  xla_fusion_autotuner_thresh   int64 xla_fusion_autotuner_thresh

 Class Variables
  MLIR_BRIDGE_ROLLOUT_DISABLED   2
  MLIR_BRIDGE_ROLLOUT_ENABLED   1
  MLIR_BRIDGE_ROLLOUT_UNSPECIFIED   0
  MlirBridgeRollout


tf.compat.v1.confusion_matrix Computes the confusion matrix from predictions and labels.  View aliases  Compat aliases for migration
See Migration guide for more details. tf.compat.v1.math.confusion_matrix
tf.compat.v1.confusion_matrix(
    labels, predictions, num_classes=None, dtype=tf.dtypes.int32, name=None,
    weights=None
)
 The matrix columns represent the prediction labels and the rows represent the real labels. The confusion matrix is always a 2-D array of shape [n, n], where n is the number of valid labels for a given classification task. Both prediction and labels must be 1-D arrays of the same shape in order for this function to work. If num_classes is None, then num_classes will be set to one plus the maximum value in either predictions or labels. Class labels are expected to start at 0. For example, if num_classes is 3, then the possible labels would be [0, 1, 2]. If weights is not None, then each prediction contributes its corresponding weight to the total value of the confusion matrix cell. For example: tf.math.confusion_matrix([1, 2, 4], [2, 2, 4]) ==>
    [[0 0 0 0 0]
     [0 0 1 0 0]
     [0 0 1 0 0]
     [0 0 0 0 0]
     [0 0 0 0 1]]
 Note that the possible labels are assumed to be [0, 1, 2, 3, 4], resulting in a 5x5 confusion matrix.

 Args
  labels   1-D Tensor of real labels for the classification task.
  predictions   1-D Tensor of predictions for a given classification.
  num_classes   The possible number of labels the classification task can have. If this value is not provided, it will be calculated using both predictions and labels array.
  dtype   Data type of the confusion matrix.
  name   Scope name.
  weights   An optional Tensor whose shape matches predictions.

 Returns   A Tensor of type dtype with shape [n, n] representing the confusion matrix, where n is the number of possible labels in the classification task.

 Raises
  ValueError   If both predictions and labels are not 1-D vectors and have mismatched shapes, or if weights is not None and its shape doesn't match predictions.


tf.compat.v1.constant Creates a constant tensor.
tf.compat.v1.constant(
    value, dtype=None, shape=None, name='Const', verify_shape=False
)
 The resulting tensor is populated with values of type dtype, as specified by arguments value and (optionally) shape (see examples below). The argument value can be a constant value, or a list of values of type dtype. If value is a list, then the length of the list must be less than or equal to the number of elements implied by the shape argument (if specified). In the case where the list length is less than the number of elements specified by shape, the last element in the list will be used to fill the remaining entries. The argument shape is optional. If present, it specifies the dimensions of the resulting tensor. If not present, the shape of value is used. If the argument dtype is not specified, then the type is inferred from the type of value. For example: # Constant 1-D Tensor populated with value list.
tensor = tf.constant([1, 2, 3, 4, 5, 6, 7]) => [1 2 3 4 5 6 7]

# Constant 2-D tensor populated with scalar value -1.
tensor = tf.constant(-1.0, shape=[2, 3]) => [[-1. -1. -1.]
                                             [-1. -1. -1.]]
 tf.constant differs from tf.fill in a few ways:
tf.constant supports arbitrary constants, not just uniform scalar Tensors like tf.fill.
tf.constant creates a Const node in the computation graph with the exact value at graph construction time. On the other hand, tf.fill creates an Op in the graph that is expanded at runtime. Because tf.constant only embeds constant values in the graph, it does not support dynamic shapes based on other runtime Tensors, whereas tf.fill does.

 Args
  value   A constant value (or list) of output type dtype.
  dtype   The type of the elements of the resulting tensor.
  shape   Optional dimensions of resulting tensor.
  name   Optional name for the tensor.
  verify_shape   Boolean that enables verification of a shape of values.

 Returns   A Constant Tensor.

 Raises
  TypeError   if shape is incorrectly specified or unsupported.


tf.compat.v1.container Wrapper for Graph.container() using the default graph.
tf.compat.v1.container(
    container_name
)

 Args
  container_name   The container string to use in the context.

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


tf.compat.v1.control_flow_v2_enabled Returns True if v2 control flow is enabled.
tf.compat.v1.control_flow_v2_enabled()

Note: v2 control flow is always enabled inside of tf.function.


tf.compat.v1.convert_to_tensor Converts the given value to a Tensor.
tf.compat.v1.convert_to_tensor(
    value, dtype=None, name=None, preferred_dtype=None, dtype_hint=None
)
 This function converts Python objects of various types to Tensor objects. It accepts Tensor objects, numpy arrays, Python lists, and Python scalars. For example: import numpy as np

def my_func(arg):
  arg = tf.convert_to_tensor(arg, dtype=tf.float32)
  return tf.matmul(arg, arg) + arg

# The following calls are equivalent.
value_1 = my_func(tf.constant([[1.0, 2.0], [3.0, 4.0]]))
value_2 = my_func([[1.0, 2.0], [3.0, 4.0]])
value_3 = my_func(np.array([[1.0, 2.0], [3.0, 4.0]], dtype=np.float32))
 This function can be useful when composing a new operation in Python (such as my_func in the example above). All standard Python op constructors apply this function to each of their Tensor-valued inputs, which allows those ops to accept numpy arrays, Python lists, and scalars in addition to Tensor objects.
Note: This function diverges from default Numpy behavior for float and string types when None is present in a Python list or scalar. Rather than silently converting None values, an error will be thrown.

 Args
  value   An object whose type has a registered Tensor conversion function.
  dtype   Optional element type for the returned tensor. If missing, the type is inferred from the type of value.
  name   Optional name to use if a new Tensor is created.
  preferred_dtype   Optional element type for the returned tensor, used when dtype is None. In some cases, a caller may not have a dtype in mind when converting to a tensor, so preferred_dtype can be used as a soft preference. If the conversion to preferred_dtype is not possible, this argument has no effect.
  dtype_hint   same meaning as preferred_dtype, and overrides it.

 Returns   A Tensor based on value.

 Raises
  TypeError   If no conversion function is registered for value to dtype.
  RuntimeError   If a registered conversion function returns an invalid value.
  ValueError   If the value is a tensor not of given dtype in graph mode.


tf.compat.v1.convert_to_tensor_or_indexed_slices Converts the given object to a Tensor or an IndexedSlices.
tf.compat.v1.convert_to_tensor_or_indexed_slices(
    value, dtype=None, name=None
)
 If value is an IndexedSlices or SparseTensor it is returned unmodified. Otherwise, it is converted to a Tensor using convert_to_tensor().

 Args
  value   An IndexedSlices, SparseTensor, or an object that can be consumed by convert_to_tensor().
  dtype   (Optional.) The required DType of the returned Tensor or IndexedSlices.
  name   (Optional.) A name to use if a new Tensor is created.

 Returns   A Tensor, IndexedSlices, or SparseTensor based on value.

 Raises
  ValueError   If dtype does not match the element type of value.


tf.compat.v1.convert_to_tensor_or_sparse_tensor Converts value to a SparseTensor or Tensor.
tf.compat.v1.convert_to_tensor_or_sparse_tensor(
    value, dtype=None, name=None
)

 Args
  value   A SparseTensor, SparseTensorValue, or an object whose type has a registered Tensor conversion function.
  dtype   Optional element type for the returned tensor. If missing, the type is inferred from the type of value.
  name   Optional name to use if a new Tensor is created.

 Returns   A SparseTensor or Tensor based on value.

 Raises
  RuntimeError   If result type is incompatible with dtype.


tf.compat.v1.count_nonzero Computes number of nonzero elements across dimensions of a tensor. (deprecated arguments) (deprecated arguments)  View aliases  Compat aliases for migration
See Migration guide for more details. tf.compat.v1.math.count_nonzero
tf.compat.v1.count_nonzero(
    input_tensor=None, axis=None, keepdims=None, dtype=tf.dtypes.int64, name=None,
    reduction_indices=None, keep_dims=None, input=None
)
 Warning: SOME ARGUMENTS ARE DEPRECATED: (keep_dims). They will be removed in a future version. Instructions for updating: keep_dims is deprecated, use keepdims insteadWarning: SOME ARGUMENTS ARE DEPRECATED: (reduction_indices). They will be removed in a future version. Instructions for updating: reduction_indices is deprecated, use axis instead Reduces input_tensor along the dimensions given in axis. Unless keepdims is true, the rank of the tensor is reduced by 1 for each entry in axis. If keepdims is true, the reduced dimensions are retained with length 1. If axis has no entries, all dimensions are reduced, and a tensor with a single element is returned.
Note: Floating point comparison to zero is done by exact floating point equality check. Small values are not rounded to zero for purposes of the nonzero check.
 For example: x = tf.constant([[0, 1, 0], [1, 1, 0]])
tf.math.count_nonzero(x)  # 3
tf.math.count_nonzero(x, 0)  # [1, 2, 0]
tf.math.count_nonzero(x, 1)  # [1, 2]
tf.math.count_nonzero(x, 1, keepdims=True)  # [[1], [2]]
tf.math.count_nonzero(x, [0, 1])  # 3

Note: Strings are compared against zero-length empty string "". Any string with a size greater than zero is already considered as nonzero.
 For example: x = tf.constant(["", "a", "  ", "b", ""])
tf.math.count_nonzero(x) # 3, with "a", "  ", and "b" as nonzero strings.

 Args
  input_tensor   The tensor to reduce. Should be of numeric type, bool, or string.
  axis   The dimensions to reduce. If None (the default), reduces all dimensions. Must be in the range [-rank(input_tensor), rank(input_tensor)).
  keepdims   If true, retains reduced dimensions with length 1.
  dtype   The output dtype; defaults to tf.int64.
  name   A name for the operation (optional).
  reduction_indices   The old (deprecated) name for axis.
  keep_dims   Deprecated alias for keepdims.
  input   Overrides input_tensor. For compatibility.

 Returns   The reduced tensor (number of nonzero values).


tf.compat.v1.count_up_to Increments 'ref' until it reaches 'limit'. (deprecated)
tf.compat.v1.count_up_to(
    ref, limit, name=None
)
 Warning: THIS FUNCTION IS DEPRECATED. It will be removed in a future version. Instructions for updating: Prefer Dataset.range instead.

 Args
  ref   A Variable. Must be one of the following types: int32, int64. Should be from a scalar Variable node.
  limit   An int. If incrementing ref would bring it above limit, instead generates an 'OutOfRange' error.
  name   A name for the operation (optional).

 Returns   A Tensor. Has the same type as ref. A copy of the input before increment. If nothing else modifies the input, the values produced will all be distinct.


tf.compat.v1.create_partitioned_variables Create a list of partitioned variables according to the given slicing. (deprecated)
tf.compat.v1.create_partitioned_variables(
    shape, slicing, initializer, dtype=tf.dtypes.float32, trainable=True,
    collections=None, name=None, reuse=None
)
 Warning: THIS FUNCTION IS DEPRECATED. It will be removed in a future version. Instructions for updating: Use tf.get_variable with a partitioner set. Currently only one dimension of the full variable can be sliced, and the full variable can be reconstructed by the concatenation of the returned list along that dimension.

 Args
  shape   List of integers. The shape of the full variable.
  slicing   List of integers. How to partition the variable. Must be of the same length as shape. Each value indicate how many slices to create in the corresponding dimension. Presently only one of the values can be more than 1; that is, the variable can only be sliced along one dimension. For convenience, The requested number of partitions does not have to divide the corresponding dimension evenly. If it does not, the shapes of the partitions are incremented by 1 starting from partition 0 until all slack is absorbed. The adjustment rules may change in the future, but as you can save/restore these variables with different slicing specifications this should not be a problem.

  initializer   A Tensor of shape shape or a variable initializer function. If a function, it will be called once for each slice, passing the shape and data type of the slice as parameters. The function must return a tensor with the same shape as the slice.
  dtype   Type of the variables. Ignored if initializer is a Tensor.
  trainable   If True also add all the variables to the graph collection GraphKeys.TRAINABLE_VARIABLES.
  collections   List of graph collections keys to add the variables to. Defaults to [GraphKeys.GLOBAL_VARIABLES].
  name   Optional name for the full variable. Defaults to "PartitionedVariable" and gets uniquified automatically.
  reuse   Boolean or None; if True and name is set, it would reuse previously created variables. if False it will create new variables. if None, it would inherit the parent scope reuse.

 Returns   A list of Variables corresponding to the slicing.

 Raises
  ValueError   If any of the arguments is malformed.


Module: tf.compat.v1.data tf.data.Dataset API for input pipelines. See Importing Data for an overview. Modules experimental module: Experimental API for building input pipelines. Classes class Dataset: Represents a potentially large set of elements. class DatasetSpec: Type specification for tf.data.Dataset. class FixedLengthRecordDataset: A Dataset of fixed-length records from one or more binary files. class Iterator: Represents the state of iterating through a Dataset. class Options: Represents options for tf.data.Dataset. class TFRecordDataset: A Dataset comprising records from one or more TFRecord files. class TextLineDataset: A Dataset comprising lines from one or more text files. Functions get_output_classes(...): Returns the output classes for elements of the input dataset / iterator. get_output_shapes(...): Returns the output shapes for elements of the input dataset / iterator. get_output_types(...): Returns the output shapes for elements of the input dataset / iterator. make_initializable_iterator(...): Creates an iterator for elements of dataset. make_one_shot_iterator(...): Creates an iterator for elements of dataset.

 Other Members
  AUTOTUNE   -1
  INFINITE_CARDINALITY   -1
  UNKNOWN_CARDINALITY   -2


tf.compat.v1.data.Dataset Represents a potentially large set of elements. Inherits From: Dataset
tf.compat.v1.data.Dataset()
 A Dataset can be used to represent an input pipeline as a collection of elements and a "logical plan" of transformations that act on those elements.

 Args
  variant_tensor   A DT_VARIANT tensor that represents the dataset.

 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.data.experimental Experimental API for building input pipelines. This module contains experimental Dataset sources and transformations that can be used in conjunction with the tf.data.Dataset API. Note that the tf.data.experimental API is not subject to the same backwards compatibility guarantees as tf.data, but we will provide deprecation advice in advance of removing existing functionality. See Importing Data for an overview. Modules service module: API for using the tf.data service. Classes class AutoShardPolicy: Represents the type of auto-sharding we enable. class CheckpointInputPipelineHook: Checkpoints input pipeline state every N steps or seconds. class CsvDataset: A Dataset comprising lines from one or more CSV files. class DatasetStructure: Type specification for tf.data.Dataset. class DistributeOptions: Represents options for distributed data processing. class MapVectorizationOptions: Represents options for the MapVectorization optimization. class OptimizationOptions: Represents options for dataset optimizations. class Optional: Represents a value that may or may not be present. class OptionalStructure: Type specification for tf.experimental.Optional. class RandomDataset: A Dataset of pseudorandom values. class Reducer: A reducer is used for reducing a set of elements. class SqlDataset: A Dataset consisting of the results from a SQL query. class StatsAggregator: A stateful resource that aggregates statistics from one or more iterators. class StatsOptions: Represents options for collecting dataset stats using StatsAggregator. class Structure: Specifies a TensorFlow value type. class TFRecordWriter: Writes a dataset to a TFRecord file. class ThreadingOptions: Represents options for dataset threading. Functions Counter(...): Creates a Dataset that counts from start in steps of size step. RaggedTensorStructure(...): DEPRECATED FUNCTION SparseTensorStructure(...): DEPRECATED FUNCTION TensorArrayStructure(...): DEPRECATED FUNCTION TensorStructure(...): DEPRECATED FUNCTION assert_cardinality(...): Asserts the cardinality of the input dataset. bucket_by_sequence_length(...): A transformation that buckets elements in a Dataset by length. bytes_produced_stats(...): Records the number of bytes produced by each element of the input dataset. cardinality(...): Returns the cardinality of dataset, if known. choose_from_datasets(...): Creates a dataset that deterministically chooses elements from datasets. copy_to_device(...): A transformation that copies dataset elements to the given target_device. dense_to_ragged_batch(...): A transformation that batches ragged elements into tf.RaggedTensors. dense_to_sparse_batch(...): A transformation that batches ragged elements into tf.sparse.SparseTensors. enumerate_dataset(...): A transformation that enumerates the elements of a dataset. (deprecated) from_variant(...): Constructs a dataset from the given variant and structure. get_next_as_optional(...): Returns a tf.experimental.Optional with the next element of the iterator. (deprecated) get_single_element(...): Returns the single element in dataset as a nested structure of tensors. get_structure(...): Returns the type signature for elements of the input dataset / iterator. group_by_reducer(...): A transformation that groups elements and performs a reduction. group_by_window(...): A transformation that groups windows of elements by key and reduces them. ignore_errors(...): Creates a Dataset from another Dataset and silently ignores any errors. latency_stats(...): Records the latency of producing each element of the input dataset. make_batched_features_dataset(...): Returns a Dataset of feature dictionaries from Example protos. make_csv_dataset(...): Reads CSV files into a dataset. make_saveable_from_iterator(...): Returns a SaveableObject for saving/restoring iterator state using Saver. (deprecated) map_and_batch(...): Fused implementation of map and batch. (deprecated) map_and_batch_with_legacy_function(...): Fused implementation of map and batch. (deprecated) parallel_interleave(...): A parallel version of the Dataset.interleave() transformation. (deprecated) parse_example_dataset(...): A transformation that parses Example protos into a dict of tensors. prefetch_to_device(...): A transformation that prefetches dataset values to the given device. rejection_resample(...): A transformation that resamples a dataset to achieve a target distribution. sample_from_datasets(...): Samples elements at random from the datasets in datasets. scan(...): A transformation that scans a function across an input dataset. shuffle_and_repeat(...): Shuffles and repeats a Dataset, reshuffling with each repetition. (deprecated) snapshot(...): API to persist the output of the input dataset. take_while(...): A transformation that stops dataset iteration based on a predicate. to_variant(...): Returns a variant representing the given dataset. unbatch(...): Splits elements of a dataset into multiple elements on the batch dimension. (deprecated) unique(...): Creates a Dataset from another Dataset, discarding duplicates.

 Other Members
  AUTOTUNE   -1
  INFINITE_CARDINALITY   -1
  UNKNOWN_CARDINALITY   -2


tf.compat.v1.data.experimental.choose_from_datasets Creates a dataset that deterministically chooses elements from datasets.
tf.compat.v1.data.experimental.choose_from_datasets(
    datasets, choice_dataset
)
 For example, given the following datasets: datasets = [tf.data.Dataset.from_tensors("foo").repeat(),
            tf.data.Dataset.from_tensors("bar").repeat(),
            tf.data.Dataset.from_tensors("baz").repeat()]

# Define a dataset containing `[0, 1, 2, 0, 1, 2, 0, 1, 2]`.
choice_dataset = tf.data.Dataset.range(3).repeat(3)

result = tf.data.experimental.choose_from_datasets(datasets, choice_dataset)
 The elements of result will be: "foo", "bar", "baz", "foo", "bar", "baz", "foo", "bar", "baz"

 Args
  datasets   A list of tf.data.Dataset objects with compatible structure.
  choice_dataset   A tf.data.Dataset of scalar tf.int64 tensors between 0 and len(datasets) - 1.

 Returns   A dataset that interleaves elements from datasets according to the values of choice_dataset.

 Raises
  TypeError   If the datasets or choice_dataset arguments have the wrong type.


tf.compat.v1.data.experimental.Counter Creates a Dataset that counts from start in steps of size step.
tf.compat.v1.data.experimental.Counter(
    start=0, step=1, dtype=tf.dtypes.int64
)
 For example: Dataset.count() == [0, 1, 2, ...)
Dataset.count(2) == [2, 3, ...)
Dataset.count(2, 5) == [2, 7, 12, ...)
Dataset.count(0, -1) == [0, -1, -2, ...)
Dataset.count(10, -1) == [10, 9, ...)

 Args
  start   (Optional.) The starting value for the counter. Defaults to 0.
  step   (Optional.) The step size for the counter. Defaults to 1.
  dtype   (Optional.) The data type for counter elements. Defaults to tf.int64.

 Returns   A Dataset of scalar dtype elements.