TensorFlow Tensors
Hands-on practice for tensor creation, shapes, math operations, and manipulation.
Creating Tensors
import tensorflow as tf
scalar = tf.constant(7)
vector = tf.constant([10, 10])
matrix = tf.constant([[1,2],[3,4]])
tensor = tf.constant([
[[1,2],[3,4]],
[[5,6],[7,8]]
])
Key idea:
Rank = number of dimensions
Shape = size of each dimension
Rank = number of dimensions
Shape = size of each dimension
tf.Variable vs tf.constant
changeable = tf.Variable([10,7])
unchangeable = tf.constant([10,7])
changeable[0].assign(7) # Works
# unchangeable[0].assign(7) Error
Random Tensors
random_1 = tf.random.Generator.from_seed(42).normal((3,2))
random_2 = tf.random.Generator.from_seed(42).normal((3,2))
Tensor Shapes & Indexing
rank_4 = tf.zeros([2,3,4,5])
rank_4.shape
rank_4.ndim
tf.size(rank_4)
rank_4[:1,:1,:1,:]
Math Operations
tensor = tf.constant([[10,7],[3,4]])
tensor + 10
tensor * 10
tf.matmul(tensor, tensor)
Aggregation
E = tf.constant(np.random.randint(0,100,50))
tf.reduce_min(E)
tf.reduce_max(E)
tf.reduce_mean(E)
tf.reduce_sum(E)
One-Hot Encoding
indices = [0,1,2,3]
tf.one_hot(indices, depth=4)
Exercises
1. Create scalar, vector, matrix, tensor
2. Find shape, rank, size
3. Create random tensors [5,300]
4. Matrix multiply them
5. One-hot encode a tensor