0
0
TensorFlowml~5 mins

Numpy interoperability in TensorFlow

Choose your learning style9 modes available
Introduction
TensorFlow can work smoothly with Numpy arrays, making it easy to use existing data and tools together.
You have data in Numpy arrays and want to use TensorFlow models.
You want to convert TensorFlow tensors to Numpy arrays for easy inspection or processing.
You want to use Numpy functions on TensorFlow data without extra copying.
You want to mix TensorFlow and Numpy code in the same project.
You want to debug or visualize TensorFlow data using Numpy tools.
Syntax
TensorFlow
import tensorflow as tf
import numpy as np

# Convert Numpy array to TensorFlow tensor
numpy_array = np.array([1, 2, 3])
tf_tensor = tf.convert_to_tensor(numpy_array)

# Convert TensorFlow tensor to Numpy array
numpy_array = tf_tensor.numpy()
TensorFlow tensors and Numpy arrays share memory when possible, so conversion is fast.
Use .numpy() only when eager execution is enabled (default in TensorFlow 2).
Examples
Convert a Numpy array to a TensorFlow tensor and print it.
TensorFlow
import tensorflow as tf
import numpy as np

np_array = np.array([1, 2, 3])
tf_tensor = tf.convert_to_tensor(np_array)
print(tf_tensor)
Convert a TensorFlow tensor to a Numpy array and print it.
TensorFlow
import tensorflow as tf

tf_tensor = tf.constant([4, 5, 6])
np_array = tf_tensor.numpy()
print(np_array)
Use a Numpy function on TensorFlow tensor data by converting it to Numpy first.
TensorFlow
import tensorflow as tf
import numpy as np

np_array = np.array([7, 8, 9])
tf_tensor = tf.convert_to_tensor(np_array)
# Use Numpy function on TensorFlow tensor by converting it first
result = np.sum(tf_tensor.numpy())
print(result)
Sample Model
This program shows how to convert a Numpy array to a TensorFlow tensor, perform a TensorFlow operation, and convert the result back to a Numpy array.
TensorFlow
import tensorflow as tf
import numpy as np

# Create a Numpy array
np_array = np.array([[1, 2], [3, 4]])
print("Original Numpy array:")
print(np_array)

# Convert Numpy array to TensorFlow tensor
tf_tensor = tf.convert_to_tensor(np_array)
print("\nTensorFlow tensor:")
print(tf_tensor)

# Perform a TensorFlow operation
tf_result = tf.math.square(tf_tensor)
print("\nTensorFlow tensor after squaring:")
print(tf_result)

# Convert result back to Numpy array
np_result = tf_result.numpy()
print("\nResult converted back to Numpy array:")
print(np_result)
OutputSuccess
Important Notes
TensorFlow 2 runs eagerly by default, so you can use .numpy() to get Numpy arrays easily.
Avoid unnecessary conversions in large programs to keep performance high.
TensorFlow tensors and Numpy arrays can share memory, so changes in one may affect the other if not careful.
Summary
TensorFlow and Numpy work well together by converting data back and forth.
Use tf.convert_to_tensor() to go from Numpy to TensorFlow.
Use .numpy() on a TensorFlow tensor to get a Numpy array.