TensorFlow | How to use tf.data.Dataset.from_tensor_slices()

This post explains how to use tf.data.Dataset.from_tensor_slices 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.
  • from_tensor_slices(tensor) creates a Dataset whose elements are slices of the given tensors.
  • Import tensorflow
    
    import tensorflow as tf
    
    print(tf.__version__)
    
    
    
    Create Tensor
    
    
    tensor1 = tf.range(12)
    
    
    
    Create dataset, this will return TensorSliceDataset object
    
    
    dataset = tf.data.Dataset.from_tensor_slices(tensor1)
    print(dataset)
    
    
    
    Iterate through dataset
    
    
      
    for i in dataset:
    	print(type(i))
    	print(i)
    
    
    
    Output
    
    
    2.0.0
    
    < TensorSliceDataset shapes: (), types: tf.int32 >
    
    <class 'tensorflow.python.framework.ops.EagerTensor'>
    tf.Tensor(0, shape=(), dtype=int32)
    <class 'tensorflow.python.framework.ops.EagerTensor'>
    tf.Tensor(1, shape=(), dtype=int32)
    <class 'tensorflow.python.framework.ops.EagerTensor'>
    tf.Tensor(2, shape=(), dtype=int32)
    <class 'tensorflow.python.framework.ops.EagerTensor'>
    tf.Tensor(3, shape=(), dtype=int32)
    <class 'tensorflow.python.framework.ops.EagerTensor'>
    tf.Tensor(4, shape=(), dtype=int32)
    <class 'tensorflow.python.framework.ops.EagerTensor'>
    tf.Tensor(5, shape=(), dtype=int32)
    <class 'tensorflow.python.framework.ops.EagerTensor'>
    tf.Tensor(6, shape=(), dtype=int32)
    <class 'tensorflow.python.framework.ops.EagerTensor'>
    tf.Tensor(7, shape=(), dtype=int32)
    <class 'tensorflow.python.framework.ops.EagerTensor'>
    tf.Tensor(8, shape=(), dtype=int32)
    <class 'tensorflow.python.framework.ops.EagerTensor'>
    tf.Tensor(9, shape=(), dtype=int32)
    <class 'tensorflow.python.framework.ops.EagerTensor'>
    tf.Tensor(10, shape=(), dtype=int32)
    <class 'tensorflow.python.framework.ops.EagerTensor'>
    tf.Tensor(11, shape=(), dtype=int32)