| View source on GitHub | 
Converts the given value to a Tensor.
tf.convert_to_tensor(
    value, dtype=None, dtype_hint=None, name=None
)
  This function converts Python objects of various types to Tensor objects. It accepts Tensor objects, numpy arrays, Python lists, and Python scalars.
import numpy as np def my_func(arg): arg = tf.convert_to_tensor(arg, dtype=tf.float32) return arg
# The following calls are equivalent. value_1 = my_func(tf.constant([[1.0, 2.0], [3.0, 4.0]])) print(value_1) tf.Tensor( [[1. 2.] [3. 4.]], shape=(2, 2), dtype=float32) value_2 = my_func([[1.0, 2.0], [3.0, 4.0]]) print(value_2) tf.Tensor( [[1. 2.] [3. 4.]], shape=(2, 2), dtype=float32) value_3 = my_func(np.array([[1.0, 2.0], [3.0, 4.0]], dtype=np.float32)) print(value_3) tf.Tensor( [[1. 2.] [3. 4.]], shape=(2, 2), dtype=float32)
This function can be useful when composing a new operation in Python (such as my_func in the example above). All standard Python op constructors apply this function to each of their Tensor-valued inputs, which allows those ops to accept numpy arrays, Python lists, and scalars in addition to Tensor objects.
Note: This function diverges from default Numpy behavior forfloatandstringtypes whenNoneis present in a Python list or scalar. Rather than silently convertingNonevalues, an error will be thrown.
| Args | |
|---|---|
| value | An object whose type has a registered Tensorconversion function. | 
| dtype | Optional element type for the returned tensor. If missing, the type is inferred from the type of value. | 
| dtype_hint | Optional element type for the returned tensor, used when dtype is None. In some cases, a caller may not have a dtype in mind when converting to a tensor, so dtype_hint can be used as a soft preference. If the conversion to dtype_hintis not possible, this argument has no effect. | 
| name | Optional name to use if a new Tensoris created. | 
| Returns | |
|---|---|
| A Tensorbased onvalue. | 
| Raises | |
|---|---|
| TypeError | If no conversion function is registered for valuetodtype. | 
| RuntimeError | If a registered conversion function returns an invalid value. | 
| ValueError | If the valueis a tensor not of givendtypein graph mode. | 
    © 2022 The TensorFlow Authors. All rights reserved.
Licensed under the Creative Commons Attribution License 4.0.
Code samples licensed under the Apache 2.0 License.
    https://www.tensorflow.org/versions/r2.9/api_docs/python/tf/convert_to_tensor