Skip to content
Related Articles

Related Articles

How To Convert Numpy Array To Tensor?

View Discussion
Improve Article
Save Article
Like Article
  • Last Updated : 02 Mar, 2022

The tf.convert_to_tensor() method from the TensorFlow library is used to convert a NumPy array into a Tensor. The distinction between a NumPy array and a tensor is that tensors, unlike NumPy arrays, are supported by accelerator memory such as the GPU, they have a faster processing speed. there are a few other ways to achieve this task. 

tf.convert_to_tensor() function:

Syntax:

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.

Example 1:

Tensorflow and NumPy packages are imported. a NumPy array is created by using the np.array() method. The NumPy array is converted to tensor by using tf.convert_to_tensor() method. a tensor object is returned. 

Python3




# import packages
import tensorflow as tf
import numpy as np
 
#create numpy_array
numpy_array = np.array([[1,2],[3,4]])
 
# convert it to tensorflow
tensor1 = tf.convert_to_tensor(numpy_array)
print(tensor1)


 

 

Output:

 

tf.Tensor(
[[1 2]
 [3 4]], shape=(2, 2), dtype=int64)

 

Special Case:

 

If we want our tensor to be of a specific dtype we should specify the dtype bypassing the datatype. in the below example float is specified as the dtype.

 

Python3




# import packages
import tensorflow as tf
import numpy as np
 
# create numpy_array
numpy_array = np.array([[1, 2], [3, 4]])
 
# convert it to tensorflow
tensor1 = tf.convert_to_tensor(numpy_array, dtype=float, name='tensor1')
tensor1


Output:

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

Example 2:

We can also use the tf.Variable() method to convert a NumPy array to a Tensor. tf.Variable() function also has parameters dtype and name. They’re optional and we can specify them when needed.

Python3




# import packages
import tensorflow as tf
import numpy as np
 
# create numpy_array
numpy_array = np.array([[1, 2], [3, 4]])
 
# convert it to tensorflow
tensor1 = tf.Variable(numpy_array, dtype=float, name='tensor1')
tensor1


Output:

<tf.Variable 'tensor1:0' shape=(2, 2) dtype=float32, numpy=
array([[1., 2.],
       [3., 4.]], dtype=float32)>

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!