How to use from_tensor_slices in tf.data.Dataset| TensorFlow

from_tensors method of tf.data.Dataset creates a Dataset with single element. There is no slicing operation along first dimesion as it is done in method from_tensor_slices . Lets understand use of from_tensors with some examples.

Create 1D tensor and use tf.data.Dataset.from_tensors on it.


import tensorflow as tf
t1_1D = tf.constant(value = [3,6,7])
print(t1_1D.shape)
dataset = tf.data.Dataset.from_tensors(t1_1D)
print(list(dataset))

Example Output:
Note there is no change in shape of produced tensor


(3,)
[<tf.Tensor: shape=(3,), dtype=int32, numpy=array([3, 6, 7], dtype=int32)>]

Create 2D tensor and use tf.data.Dataset.from_tensors


import tensorflow as tf
t2_2D = tf.constant(value = [[2,3,4], [4,5,6]])
print(t2_2D.shape)
dataset = tf.data.Dataset.from_tensors(t2_2D)
print(list(dataset))

Example Output:
Note there is no change in shape of produced tensor


(2, 3)
[<tf.Tensor: shape=(2, 3), dtype=int32, numpy=
array([[2, 3, 4],
       [4, 5, 6]], dtype=int32)>]

Create 3D tensor and use tf.data.Dataset.from_tensors on this tensor


import tensorflow as tf
t3_3D = tf.constant(value = [[[2,3,4]], [[4,5,6]]])
print(t3_3D.shape)
dataset = tf.data.Dataset.from_tensors(t3_3D)
print(list(dataset))

Example Output:
Note there is no change in shape of produced tensor


(2, 1, 3)
[<tf.Tensor: shape=(2, 1, 3), dtype=int32, numpy=
array([[[2, 3, 4]],

       [[4, 5, 6]]], dtype=int32)>]


Follow US on Twitter: