Convert features to the dtype expected by a layer or computation.
Model preprocessing
TensorFlow · Function
Casts a tensor to a new numeric dtype. It supports dense, sparse, and indexed-slice inputs while preserving their shape and structure.
The operation converts a Tensor, or the values inside a SparseTensor or IndexedSlices, to the requested destination dtype. The result preserves the input structure and shape while using the destination type; conversions can lose precision.
tf.cast(x, dtype, name=None)| Name | Type | Description |
|---|---|---|
x | Tensor | SparseTensor | IndexedSlices | A Tensor, SparseTensor, or IndexedSlices of a supported numeric type. |
dtype | DType | The destination type; it must be one of the supported types for x. |
name | string | Optional name for the operation. |
A Tensor, SparseTensor, or IndexedSlices with the same shape as x and the same type as dtype.
tf.cast to change a tensor's numeric dtype.dtype specifies the type of the returned values.name argument gives the operation an explicit graph name.import tensorflow as tf
x = tf.constant([1.8, 2.2], dtype=tf.float32)
y = tf.cast(x, tf.int32)
print(y) # [1 2]Converts the floating-point tensor to int32, truncating the fractional parts.
Model preprocessing
Label preparation
Mixed-dtype arithmetic
tf.cast do for dense and sparse-like inputs?tf.cast converts a tensor to a specified destination dtype. For a Tensor it casts the tensor directly; for a SparseTensor or IndexedSlices, it casts their values while preserving the structure and shape.
Follow-up: How would you avoid overflow during conversion? Use tf.dtypes.saturate_cast, which clamps values before casting when overflow or underflow is possible.
tf.cast?The signature is tf.cast(x, dtype, name=None). x is the numeric input, dtype is the destination type, and name optionally names the operation.
Follow-up: Which types can be used? The documentation lists unsigned and signed integer types, floating-point types, complex types, and bfloat16.
The output has the same shape as x and the same structural kind—Tensor, SparseTensor, or IndexedSlices—but uses dtype. Converting numeric values may discard precision.
Follow-up: What happens with an unsupported conversion? TensorFlow raises TypeError when x cannot be cast to the requested dtype.
tf.dtypes.saturate_casttf.bitcasttf.convert_to_tensor