0
0
TensorFlowml~5 mins

Tensor basics (creation, shapes, dtypes) in TensorFlow

Choose your learning style9 modes available
Introduction

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.

When you want to store data like images or numbers for a machine learning model.
When you need to check the size or dimensions of your data before training.
When you want to make sure your data is the right type (like integers or decimals) for calculations.
When you want to create simple data examples to test your model.
When you want to convert lists or arrays into a format TensorFlow understands.
Syntax
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.

Examples
This creates a single number tensor, called a scalar.
TensorFlow
tensor1 = tf.constant(5)
# A scalar (single number)
This creates a list of numbers, which is a 1-dimensional tensor.
TensorFlow
tensor2 = tf.constant([1, 2, 3])
# A 1D tensor (vector)
This creates a 2-dimensional tensor like a table with rows and columns.
TensorFlow
tensor3 = tf.constant([[1, 2], [3, 4]])
# A 2D tensor (matrix)
This creates a tensor with decimal numbers (floats).
TensorFlow
tensor4 = tf.constant([1.0, 2.0, 3.0], dtype=tf.float32)
# Tensor with float data type
Sample Model

This program creates four tensors of different shapes and types, then prints their shapes and data types to show how to check these properties.

TensorFlow
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)
OutputSuccess
Important Notes

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.

Summary

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.