Tensors are like containers that hold numbers in machine learning. Knowing how to create them, check their shape, and type helps us organize and use data correctly.
Tensor basics (creation, shapes, dtypes) in TensorFlow
import tensorflow as tf # Create a tensor tensor = tf.constant([1, 2, 3], dtype=tf.int32) # Check shape shape = tensor.shape # Check data type dtype = tensor.dtype
tf.constant creates a tensor from data you give it.
shape tells you the size and dimensions of the tensor.
dtype tells you the data type of the tensor.
tensor1 = tf.constant(5) # A scalar (single number)
tensor2 = tf.constant([1, 2, 3]) # A 1D tensor (vector)
tensor3 = tf.constant([[1, 2], [3, 4]]) # A 2D tensor (matrix)
tensor4 = tf.constant([1.0, 2.0, 3.0], dtype=tf.float32) # Tensor with float data type
This program creates four tensors of different shapes and types, then prints their shapes and data types to show how to check these properties.
import tensorflow as tf # Create different tensors scalar = tf.constant(10) vector = tf.constant([1, 2, 3]) matrix = tf.constant([[1, 2], [3, 4]]) float_tensor = tf.constant([1.5, 2.5, 3.5], dtype=tf.float32) # Print shapes print('Scalar shape:', scalar.shape) print('Vector shape:', vector.shape) print('Matrix shape:', matrix.shape) print('Float tensor shape:', float_tensor.shape) # Print data types print('Scalar dtype:', scalar.dtype) print('Vector dtype:', vector.dtype) print('Matrix dtype:', matrix.dtype) print('Float tensor dtype:', float_tensor.dtype)
A scalar tensor has no dimensions, shown as an empty shape ().
Use tf.constant to create tensors from Python lists or numbers.
Data types like tf.int32 or tf.float32 tell TensorFlow how to store numbers.
Tensors hold data in machine learning and can have different shapes like scalars, vectors, or matrices.
You can create tensors using tf.constant and specify their data type.
Checking a tensor's shape and data type helps you understand and use your data correctly.