How To Convert Numpy Array To Tensor?
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( value, dtype=None, dtype_hint=None, name=None)
- 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.
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.
tf.Tensor( [[1 2] [3 4]], shape=(2, 2), dtype=int64)
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.
<tf.Tensor: shape=(2, 2), dtype=float32, numpy= array([[1., 2.], [3., 4.]], dtype=float32)>
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.
<tf.Variable 'tensor1:0' shape=(2, 2) dtype=float32, numpy= array([[1., 2.], [3., 4.]], dtype=float32)>