TensorFlow | How to use tf.data.Dataset.repeat() method in TensorFlow

  • This code snippet is using TensorFlow2.0, if you are using earlier versions of TensorFlow than enable eager execution to run the code.
  • repeat() method of tf.data.Dataset class is used for repeating the tensors in dataset.If repeat(None) is specified than it keeps on repeating tensors indefinitely.
  • 
      import tensorflow as tf
    
      print(tf.__version__)
      
      # Create Tensor
      tensor1 = tf.range(5)
      
      #Create dataset, this will return object of TensorSliceDataset
      dataset = tf.data.Dataset.from_tensor_slices(tensor1)
      print(dataset)
      for i in dataset:
          print(i)
      
      
      ===== Output =====
      2.0.0
      <TensorSliceDataset shapes: (), types: tf.int32>
      tf.Tensor(0, shape=(), dtype=int32)
      tf.Tensor(1, shape=(), dtype=int32)
      tf.Tensor(2, shape=(), dtype=int32)
      tf.Tensor(3, shape=(), dtype=int32)
      tf.Tensor(4, shape=(), dtype=int32)
      
      
    

    Using repeat in dataset

    There are 5 tensors in dataset, by using repeat tensors in a dataset can be repeated, refer below output.If repeat is having argument as None, it will keep on repeating the records indefinitely.

    
      dataset = dataset.repeat(3)
      print(dataset)
      for i in dataset:
          print(i)
      
      ===== Output =====
      <RepeatDataset shapes: (), types: tf.int32>
      tf.Tensor(0, shape=(), dtype=int32)
      tf.Tensor(1, shape=(), dtype=int32)
      tf.Tensor(2, shape=(), dtype=int32)
      tf.Tensor(3, shape=(), dtype=int32)
      tf.Tensor(4, shape=(), dtype=int32)
      tf.Tensor(0, shape=(), dtype=int32)
      tf.Tensor(1, shape=(), dtype=int32)
      tf.Tensor(2, shape=(), dtype=int32)
      tf.Tensor(3, shape=(), dtype=int32)
      tf.Tensor(4, shape=(), dtype=int32)
      tf.Tensor(0, shape=(), dtype=int32)
      tf.Tensor(1, shape=(), dtype=int32)
      tf.Tensor(2, shape=(), dtype=int32)
      tf.Tensor(3, shape=(), dtype=int32)
      tf.Tensor(4, shape=(), dtype=int32)