How To Convert Numpy Array To Tensor
We are given a NumPy array, and our task is to convert it into a TensorFlow tensor. This is useful when integrating NumPy-based data with TensorFlow pipelines, which support acceleration using GPU and TPU. For example, converting [[1, 2], [3, 4]] results in a TensorFlow object that looks like:
<tf.Tensor: shape=(2, 2), dtype=int64, numpy=
array([[1, 2],
[3, 4]])>
TensorFlow provides multiple ways to convert a NumPy array to a tensor, each with its own flexibility and use cases.
Syntax of tf.convert_to_tensor()
tf.convert_to_tensor( value, dtype=None, dtype_hint=None, name=None)
Parameters:
- value : The type of an object with a registered Tensor conversion function.
- dtype: by default it is None. The returned tensor's element type is optional. If the type isn't specified, the type is inferred from the value type.
- dtype_hint: by default None. When dtype is None, this is an optional component type for the returned tensor. When converting to a tensor, a caller may not have a datatype in mind, hence dtype hint can be used as a preference. This parameter has no effect if the conversion to dtype hint is not possible.
- name : by default None. If a new Tensor is produced, this is an optional name to use.
Using tf.convert_to_tensor()
This method directly converts a NumPy array into a TensorFlow tensor while inferring the data type.
import tensorflow as tf
import numpy as np
#create numpy_array
arr = np.array([[1, 2], [3, 4]])
# convert it to tensorflow
t1 = tf.convert_to_tensor(arr)
print(t1)
Output:
tf.Tensor(
[[1 2]
[3 4]], shape=(2, 2), dtype=int64)
Using tf.convert_to_tensor() with dtype and name
You can manually specify the data type and assign a name to the tensor for easier debugging.
import tensorflow as tf
import numpy as np
#create numpy_array
arr = np.array([[1, 2], [3, 4]])
# convert it to tensorflow
t2 = tf.convert_to_tensor(arr, dtype=tf.float32, name='tensor1')
print(t2)
Output:
<tf.Tensor: shape=(2, 2), dtype=float32, numpy=
array([[1., 2.],
[3., 4.]], dtype=float32)>
Using tf.Variable()
This method wraps the NumPy array as a Variable, which is mutable and trainable—useful during model training.
import tensorflow as tf
import numpy as np
# create numpy_array
arr = np.array([[1, 2], [3, 4]])
# convert it to tensorflow
t3 = tf.Variable(arr, dtype=tf.float32, name='tensor1')
print(t3)
Output:
<tf.Variable 'tensor1:0' shape=(2, 2) dtype=float32, numpy=
array([[1., 2.],
[3., 4.]], dtype=float32)>
Using tf.constant()
This is a convenient method to create immutable tensors from NumPy arrays.
import tensorflow as tf
import numpy as np
# create numpy_array
arr = np.array([[10, 20], [30, 40]])
# convert it to tensorflow
t4 = tf.constant(arr, dtype=tf.int32)
print(t4)
Output:
<tf.Tensor: shape=(2, 2), dtype=int32, numpy=
array([[10, 20],
[30, 40]])>