Introduction
Tensors are like containers for numbers. We create them to hold data for machine learning models.
Jump into concepts and practice - no test required
Tensors are like containers for numbers. We create them to hold data for machine learning models.
tf.constant(value, dtype=None, shape=None) tf.Variable(initial_value, dtype=None) tf.zeros(shape, dtype=tf.float32) tf.ones(shape, dtype=tf.float32)
tf.constant creates a tensor with fixed values.
tf.Variable creates a tensor that can change during training.
tf.constant([1, 2, 3])
tf.Variable([[1.0, 2.0], [3.0, 4.0]])
tf.zeros([3, 2])
tf.ones([4])This program shows how to create different types of tensors and prints them.
import tensorflow as tf # Create a constant tensor const_tensor = tf.constant([[1, 2], [3, 4]]) # Create a variable tensor var_tensor = tf.Variable([[5.0, 6.0], [7.0, 8.0]]) # Create a zeros tensor zeros_tensor = tf.zeros([2, 3]) # Create a ones tensor ones_tensor = tf.ones([3]) print("Constant Tensor:") print(const_tensor) print("Variable Tensor:") print(var_tensor) print("Zeros Tensor:") print(zeros_tensor) print("Ones Tensor:") print(ones_tensor)
Use tf.constant for data that should not change.
Use tf.Variable for data that will update during training.
tf.zeros and tf.ones help quickly create tensors with default values.
Tensors hold data for machine learning.
tf.constant creates fixed tensors.
tf.Variable creates changeable tensors.
tf.zeros and tf.ones create tensors filled with zeros or ones.
tf.constant creates tensors with fixed values that cannot be changed after creation.tf.Variable creates tensors that can be changed, while tf.zeros and tf.ones create tensors filled with zeros or ones but are also constants by default.tf.Variable(5) creates a variable tensor with initial value 5.tf.constant(5) creates a constant, not a variable. tf.zeros(5) and tf.ones(5) create tensors of shape 5, not a single value 5.import tensorflow as tf x = tf.zeros((2, 3)) print(x.numpy())
.numpy() converts tensor to numpy array, showing zeros in 2x3 shape.import tensorflow as tf x = tf.ones(3, 4) print(x)
tf.ones expects a single shape argument as a tuple, e.g., (3, 4), not two separate integers.tf.eye(3) creates a 3x3 identity matrix with ones on the diagonal and zeros elsewhere.tf.Variable makes this tensor changeable during training or updates.tf.ones and tf.zeros create all ones or zeros, not identity. tf.constant(3) creates scalar 3, not matrix.