Skip to content

Instantly share code, notes, and snippets.

@meetmakwana7396
Last active January 1, 2025 09:37
Show Gist options
  • Select an option

  • Save meetmakwana7396/b0ceb25776bd81ff8d65f9350f17e080 to your computer and use it in GitHub Desktop.

Select an option

Save meetmakwana7396/b0ceb25776bd81ff8d65f9350f17e080 to your computer and use it in GitHub Desktop.

Intro to Tensor using TensorFlow

Type of Tensors

  1. Varibale -> Elements can be changed later
  2. Constant -> Elements cannot be changed later
  3. Placeholder
  4. SparseTensor
import tensorflow as tf

tensor1 = tf.constant([1, 2, 3])
tensor2 = tf.constant([[1, 2], [3, 4], [4, 5]])  # 2D tensor/matrix

# Rank/Degree of a tensor is deepest level of nested list
rank0_tensor = tf.Variable("This is Rank 0 tensor.", tf.string)  # Rank 0 Tensor
rank1_tensor = tf.Variable(["a", "b"], tf.string)  # Rank 1 Tensor
rank2_tensor = tf.Variable([["a", "b"], ["c", "d"]], tf.string)  # Rank 2 Tensor
rank3_tensor = tf.Variable([[["a"], ["b"]], [["c"], ["d"]]], tf.string)  # Rank 2 Tensor

# Rank of Tensor
print(tf.rank(rank0_tensor))  # tf.Tensor(0, shape=(), dtype=int32)
print(tf.rank(rank1_tensor))  # tf.Tensor(1, shape=(), dtype=int32)
print(tf.rank(rank2_tensor))  # tf.Tensor(2, shape=(), dtype=int32)
print(tf.rank(rank3_tensor))  # tf.Tensor(3, shape=(), dtype=int32)

# Shape of Tensor
print((rank0_tensor).shape)  # () -> means we don't have list, just a single element
print((rank1_tensor).shape)  # (2,) -> means we have 2 element in one list
print((rank2_tensor).shape)  # (2, 2) ->  means we have 2 lists containing 2 elements
print(
    (rank3_tensor).shape
)  # (2, 2, 1) -> means we have 2 lists containing another 2 lists with 1 element in each of it

# Reshape Tensors
t = tf.zeros([5, 5, 5, 5]) # Will create nested tensor with given values of nesting filled with zeros
t = tf.reshape(t, [5, -1]) # Will reshape the Tensor in 5 list with equally distributed elemetns in it (When given -1)
print(t)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment