0
0
TensorFlowml~5 mins

Tensor creation (constant, variable, zeros, ones) in TensorFlow

Choose your learning style9 modes available
Introduction

Tensors are like containers for numbers. We create them to hold data for machine learning models.

When you want to store fixed data that does not change during training.
When you need a tensor that can change values during training, like model weights.
When you want to create a tensor filled with zeros to initialize data.
When you want to create a tensor filled with ones for bias or masks.
When you want to quickly create tensors of specific shapes for experiments.
Syntax
TensorFlow
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.

Examples
Creates a constant tensor with values 1, 2, 3.
TensorFlow
tf.constant([1, 2, 3])
Creates a variable tensor with a 2x2 shape.
TensorFlow
tf.Variable([[1.0, 2.0], [3.0, 4.0]])
Creates a 3x2 tensor filled with zeros.
TensorFlow
tf.zeros([3, 2])
Creates a 1D tensor of length 4 filled with ones.
TensorFlow
tf.ones([4])
Sample Model

This program shows how to create different types of tensors and prints them.

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

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.

Summary

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.