0
0
TensorFlowml~15 mins

Tensor creation (constant, variable, zeros, ones) in TensorFlow - ML Experiment: Train & Evaluate

Choose your learning style9 modes available
Experiment - Tensor creation (constant, variable, zeros, ones)
Problem:You want to create different types of tensors in TensorFlow to understand how to initialize data for machine learning models.
Current Metrics:No metrics yet, this is a foundational skill for building models.
Issue:You are unsure how to create constant tensors, variable tensors, and tensors filled with zeros or ones.
Your Task
Create four tensors: a constant tensor with fixed values, a variable tensor that can change, a tensor filled with zeros, and a tensor filled with ones. Print each tensor and its type.
Use TensorFlow functions only.
Do not use any deprecated TensorFlow APIs.
Ensure tensors have shape (3, 3).
Hint 1
Hint 2
Hint 3
Hint 4
Solution
TensorFlow
import tensorflow as tf

# Create a constant tensor
constant_tensor = tf.constant([[1, 2, 3], [4, 5, 6], [7, 8, 9]])

# Create a variable tensor
variable_tensor = tf.Variable([[1, 1, 1], [2, 2, 2], [3, 3, 3]])

# Create a tensor filled with zeros
zeros_tensor = tf.zeros((3, 3))

# Create a tensor filled with ones
ones_tensor = tf.ones((3, 3))

# Print tensors and their types
print("Constant Tensor:\n", constant_tensor)
print("Type:", type(constant_tensor))

print("\nVariable Tensor:\n", variable_tensor)
print("Type:", type(variable_tensor))

print("\nZeros Tensor:\n", zeros_tensor)
print("Type:", type(zeros_tensor))

print("\nOnes Tensor:\n", ones_tensor)
print("Type:", type(ones_tensor))
Added code to create a constant tensor with fixed values.
Added code to create a variable tensor that can be updated.
Added code to create tensors filled with zeros and ones.
Printed each tensor and its Python type to verify creation.
Results Interpretation

Before: No tensors created, unsure how to initialize data.

After: Successfully created and printed four types of tensors with shape (3, 3): constant, variable, zeros, and ones.

This experiment shows how to initialize different types of tensors in TensorFlow, which is essential for setting up data and model parameters in machine learning.
Bonus Experiment
Try creating tensors of shape (2, 4) with random values using TensorFlow.
💡 Hint
Use tf.random.uniform() or tf.random.normal() to create tensors with random values.