Tensorflow 2: Convert Arrays to Tensors (2 Examples)

Last updated on August 17, 2021 A Goodman Loading... Post a comment

A tensor is a multi-dimensional array with a uniform type. It is the standard data format used in Tensorflow. Below are a few examples of creating tensors from Numpy arrays by using tf.convert_to_tensor and tf.constant functions.

Example 1: Using tf.convert_to_tensor

The code:

import tensorflow as tf
import numpy as np

np_array = np.random.randint(low=0, high=100, size=(3, 4, 5))
tf_tensor = tf.convert_to_tensor(np_array, dtype=tf.float32)
print(tf_tensor)

Output:

tf.Tensor(
[[[40. 68. 54. 50.  9.]
  [28. 80.  9. 43.  6.]
  [89. 11. 69. 23. 19.]
  [45. 30. 33. 39. 64.]]

 [[65. 91. 16. 76. 93.]
  [33. 22. 84. 79. 25.]
  [37.  2. 28.  5. 66.]
  [87. 76.  8. 86. 21.]]

 [[84. 83. 27. 13. 62.]
  [89. 58. 49. 93. 57.]
  [69. 89. 75.  2. 74.]
  [47. 91. 48. 79. 64.]]], shape=(3, 4, 5), dtype=float32)

Example 2: Using tf.constant

The code:

import tensorflow as tf
import numpy as np

# A normal Python list
x = [
     [4., 3., 2.],
     [1., 2., 5.],
     [11., 9., 0.]
]

# Turn the Python list into a Numpy array
np_arr = np.asarray(x, np.float32)

# Convert the Numpy array to a tensor
tensor = tf.constant(np_arr, np.float32)

print(tensor)

Output:

tf.Tensor(
[[ 4.  3.  2.]
 [ 1.  2.  5.]
 [11.  9.  0.]], shape=(3, 3), dtype=float32)

Hope these examples can help you in some way. Happy coding.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

You May Also Like