Normalize operation inputs
A custom Python operation receives lists, scalars, or NumPy arrays and needs a consistent Tensor input.
TensorFlow · Function
Converts supported Python and array-like values into a Tensor. The element type is inferred unless dtype is supplied, while dtype_hint provides a fallback preference.
The function uses TensorFlow's registered conversion for the supplied value and returns a Tensor. It infers the element type unless dtype is provided; dtype_hint supplies a fallback preference only when dtype is omitted and conversion to that type is possible.
tf.convert_to_tensor(value, dtype=None, dtype_hint=None, name=None) -> tf.Tensor| Name | Type | Description |
|---|---|---|
value | Any | An object with a registered Tensor conversion function. |
dtype | tf.DType | Optional element type for the returned Tensor; if omitted, it is inferred from value. |
dtype_hint | tf.DType | Optional element type used as a soft preference when dtype is None. |
name | string | Optional name used if a new Tensor is created. |
A Tensor based on value.
import tensorflow as tf
values = tf.convert_to_tensor([1, 2, 3], dtype=tf.float32)
print(values)
Converts a Python list into a float32 Tensor that can be passed to TensorFlow operations.
A custom Python operation receives lists, scalars, or NumPy arrays and needs a consistent Tensor input.
Data must enter a TensorFlow computation with a specified element type.
An operation should accept tensor-like values without requiring callers to construct Tensors first.
It converts supported Python values, NumPy arrays, lists, scalars, and existing Tensor objects into a Tensor. TensorFlow operations use this behavior so many operations can accept tensor-like inputs.
Follow-up: What happens when the input type is unsupported? TensorFlow raises TypeError if no conversion function is registered for the value and requested dtype.
dtype explicitly specifies the returned tensor's element type. If dtype is absent, TensorFlow infers the type from value.
Follow-up: How does dtype_hint differ? It is used only when dtype is None and acts as a soft preference rather than a required type.
The function returns a Tensor based on value. The name argument can provide a name when TensorFlow creates a new Tensor.
Follow-up: What other failures can occur? A registered converter returning an invalid result raises RuntimeError, while an incompatible tensor dtype can raise ValueError in graph mode.
tf.casttf.constanttf.Tensortf.convert_to_tensor_v2