Convert numpy arrays to tensors in TensorFlow

This post explains how to convert numpy arrays, Python Lists and Python scalars to to Tensor objects in TensorFlow. TensorFlow provides tf.convert_to_tensor method to convert Python objects to Tensor objects.

tf.convert_to_tensor Syntax

   
    tf.convert_to_tensor(
        value, dtype=None, dtype_hint=None, name=None
    )
     

tf.convert_to_tensor Examples

Convert numpy arrays to Tensors using tf.convert_to_tensor
   
    import tensorflow as tf
    import numpy as np
    
    np_array = np.array([[1, 2, 3], [4, 5, 6]])
    print("numpy array")
    print(np_array)
    
    
    tensor_1 = tf.convert_to_tensor(np_array, dtype=tf.int32)
    print("tensor from numpy array")
    print(tensor_np)
     
Output
   
    numpy array
    [[1 2 3]
        [4 5 6]]
    tensor from numpy array
    tf.Tensor(
    [[1 2 3]
        [4 5 6]], shape=(2, 3), dtype=int32)
     
Convert Python List to Tensor using tf.convert_to_tensor
   
    import tensorflow as tf
    import numpy as np

    py_list = [1, 3, 4, 5, 6, 7]
    print("python list")
    print(py_list)

    tensor_2 = tf.convert_to_tensor(py_list, dtype=tf.int32)
    print("tensor from python list")
    print(tensor_2)
     
Output
   
    python list
    [1, 3, 4, 5, 6, 7]
    tensor from python list
    tf.Tensor([1 3 4 5 6 7], shape=(6,), dtype=int32)
     
Convert Python integer to Tensor using tf.convert_to_tensor
   
        import tensorflow as tf
        import numpy as np

        py_scalar = 10
        print("python integer")
        print(py_scalar)

        tensor_3 = tf.convert_to_tensor(py_scalar, dtype=tf.int32)
        print("tensor from python integer")
        print(tensor_3)
     
Output
   
    python integer
    10
    tensor from python integer
    tf.Tensor(10, shape=(), dtype=int32)
     

Category: TensorFlow