In this article, we will be looking at the approach to load Numpy data in Tensorflow in the Python programming language.
Using tf.data.Dataset.from_tensor_slices() function
Under this approach, we are loading a Numpy array with the use of tf.data.Dataset.from_tensor_slices() method, we can get the slices of an array in the form of objects by using tf.data.Dataset.from_tensor_slices() method from the TensorFlow module.
Syntax : tf.data.Dataset.from_tensor_slices(list)
Return : Return the objects of sliced elements.
Example 1:
In this example, we are using tf.data.Dataset.from_tensor_slices() method, to get the slices of the 2D-array and then load this to a variable gfg.
Python3
# import modules import tensorflow as tf import numpy as np # Creating data arr = np.array([[ 1 , 2 , 3 , 4 ], [ 4 , 5 , 6 , 0 ], [ 2 , 0 , 7 , 8 ], [ 3 , 7 , 4 , 2 ]]) # using tf.data.Dataset.from_tensor_slices() # method gfg = tf.data.Dataset.from_tensor_slices(arr) for i in gfg: print (i.numpy()) |
Output:
[1 2 3 4] [4 5 6 0] [2 0 7 8] [3 7 4 2]
Example 2:
In this example, we will load the NumPy list of the variable gfg using the tf.data.Dataset.from_tensor_slices() function from the TensorFlow library in the Python programming language.
Python3
# import modules import tensorflow as tf import numpy as np # Creating data list = [[ 5 , 10 ], [ 3 , 6 ], [ 1 , 2 ], [ 5 , 0 ]] # using tf.data.Dataset.from_tensor_slices() # method gfg = tf.data.Dataset.from_tensor_slices( list ) for i in gfg: print (i.numpy()) |
Output:
[ 5 10] [3 6] [1 2] [5 0]