NumPy Array To Tensorflow Tensor And Back

 

NumPy Array To Tensorflow Tensor And Back

Convert a NumPy array to a Tensorflow Tensor as well as convert a TensorFlow Tensor to a NumPy array.

Instructor: Finbarr Timbers

Duration:     1:30

Technologies:   Python, TensorFlow, NumPy


Transcript:

Today, we’re going to learn how to convert between NumPy arrays and TensorFlow tensors and back.


We’re going to begin by creating a file: numpy-arrays-to-tensorflow-tensors-and-back.py.

# command line
e numpy-arrays-to-tensorflow-tensors-and-back.py


We’re going to import TensorFlow as tf, that’s the standard, and import NumPy as np.

# numpy-arrays-to-tensorflow-tensors-and-back.py file
import tensorflow as tf
import numpy as np


We’re going to begin by generating a NumPy array by using the random.rand method to generate a 3 by 2 random matrix using NumPy.

# numpy-arrays-to-tensorflow-tensors-and-back.py file
# ...
np_array = np.random.rand(3, 2)


If we run the code, we can see that it’s just a standard NumPy array.

# command line
python numpy-arrays-to-tensorflow-tensors-and-back.py


But then I’m going to create a standard TensorFlow session using the tf.Session method.

# numpy-arrays-to-tensorflow-tensors-and-back.py file
# ...
sess = tf.Session()


We’re then going to use a session to convert the NumPy array into TensorFlow tensor using the tf.constant method.

# numpy-arrays-to-tensorflow-tensors-and-back.py file
# ...
with sess.as_default():
    tensor = tf.constant(np_array)


And then we’re going to print that tensor

# numpy-arrays-to-tensorflow-tensors-and-back.py file
# ...
    print(tensor)


so you’re going to see that it actually is a TensorFlow tensor.

# command line
python numpy-arrays-to-tensorflow-tensors-and-back.py

As you see, it is a tensor.


Finally, we’re going to convert it back by using the tensor.eval method.

# numpy-arrays-to-tensorflow-tensors-and-back.py file
# ...
    numpy_array_2 = tensor.eval()
    print(numpy_array_2)


As you can see, we’ve got our original NumPy array back.

# command line
python numpy-arrays-to-tensorflow-tensors-and-back.py



Full Source Code For Lesson

# numpy-arrays-to-tensorflow-tensors-and-back.py
#
# to run
# python numpy-arrays-to-tensorflow-tensors-and-back.py
#
import tensorflow as tf
import numpy as np

np_array = np.random.rand(3, 2)
print(np_array)

sess = tf.Session()
with sess.as_default():
    tensor = tf.constant(np_array)
    print(tensor)
    numpy_array_2 = tensor.eval()
    print(numpy_array_2)

Back