0
0
TensorFlowml~5 mins

Type casting in TensorFlow

Choose your learning style9 modes available
Introduction
Type casting changes data from one type to another so the computer can process it correctly.
When your model needs inputs in a specific data type like float32 instead of int.
When you want to save memory by converting data to a smaller type.
When combining tensors of different types and you need them to match.
When preparing data for functions that require a certain type.
When fixing errors caused by incompatible data types.
Syntax
TensorFlow
tf.cast(x, dtype)
x is the tensor you want to convert.
dtype is the target data type, like tf.float32 or tf.int32.
Examples
Converts integer tensor x to float32 tensor y.
TensorFlow
x = tf.constant([1, 2, 3])
y = tf.cast(x, tf.float32)
Converts float tensor x to integer tensor y by dropping decimals.
TensorFlow
x = tf.constant([1.5, 2.5, 3.5])
y = tf.cast(x, tf.int32)
Converts boolean tensor x to integers 1 and 0.
TensorFlow
x = tf.constant([True, False, True])
y = tf.cast(x, tf.int32)
Sample Model
This program shows how to convert a tensor from int32 to float32 and back to int32 using tf.cast.
TensorFlow
import tensorflow as tf

# Create a tensor of integers
x = tf.constant([10, 20, 30])
print('Original tensor:', x)
print('Original dtype:', x.dtype)

# Cast to float32
x_float = tf.cast(x, tf.float32)
print('After casting to float32:', x_float)
print('New dtype:', x_float.dtype)

# Cast float tensor back to int32
x_int = tf.cast(x_float, tf.int32)
print('After casting back to int32:', x_int)
print('New dtype:', x_int.dtype)
OutputSuccess
Important Notes
Casting from float to int drops the decimal part; it does not round.
Always check the data type after casting to avoid unexpected errors.
Use tf.cast to ensure tensors have the correct type before model input.
Summary
Type casting changes the data type of tensors to match model needs.
Use tf.cast(tensor, dtype) to convert types in TensorFlow.
Casting helps avoid errors and optimize memory during training.