Skip to content

Instantly share code, notes, and snippets.

@gSrikar
Last active March 3, 2021 07:07
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gSrikar/06f8152f2ade3f7dfc3bc0ede99b87b5 to your computer and use it in GitHub Desktop.
Save gSrikar/06f8152f2ade3f7dfc3bc0ede99b87b5 to your computer and use it in GitHub Desktop.
Tensors with different ranks shapes are created and printed out to the output. Tensor Ranks and Tensor Shapes are explained in detail at http://gsrikar.blogspot.com/2017/06/what-is-tensor-rank-and-tensor-shape.html
'''
Class creates tensors of different ranks and shapes
'''
import tensorflow as tf
def main():
'''
Main method
'''
# Rank 0 tensor with 0-D shape and type float
scalar = tf.constant(48.3)
print('Scalar: ', scalar) # Scalar: Tensor("Const:0", shape=(), dtype=float32)
# Rank 1 tensor with 1-D shape and type int
vector = tf.constant([1, 9, -6, 7, 0])
print('Vector: ', vector) # Vector: Tensor("Const_1:0", shape=(5,), dtype=int32)
# Rank 2 tensor with 2-D shape and type float
matrix = tf.constant([[2.4, 5.1], [3.3, 7.9], [8.5, 6.1]])
print('Matrix: ', matrix) # Matrix: Tensor("Const_2:0", shape=(3, 2), dtype=float32)
# Rank 3 tensor with 3-D shape and type int
tensor = tf.constant([[[2, 5, 6], [5, 3, 3], [6, 7, 8]],
[[0, 0, 1], [9, 7, 9], [2, 3, 6]],
[[4, 8, 2], [1, 0, 8], [4, 4, 0]]])
print('Tensor: ', tensor) # Tensor: Tensor("Const_3:0", shape=(3, 3, 3), dtype=int32)
# Start the session
with tf.Session() as sess:
# Print the values
print('Scalar value: ', sess.run(scalar)) # Scalar value: 48.3
print('Vector value: ', sess.run(vector)) # Vector value: [ 1 9 -6 7 0]
print('Matrix value: ', sess.run(matrix)) # Matrix value: [[ 2.4000001 5.0999999 ]
# [ 3.29999995 7.9000001 ]
# [ 8.5 6.0999999 ]]
print('Tensor value: ', sess.run(tensor)) # Tensor value: [[[2 5 6]
# [5 3 3]
# [6 7 8]]
#
# [[0 0 1]
# [9 7 9]
# [2 3 6]]
#
# [[4 8 2]
# [1 0 8]
# [4 4 0]]]
# Print the ranks
print('Scalar Rank: ', sess.run(tf.rank(scalar))) # Scalar Rank: 0
print('Vector Rank: ', sess.run(tf.rank(vector))) # Vector Rank: 1
print('Matrix Rank: ', sess.run(tf.rank(matrix))) # Matrix Rank: 2
print('Tensor Rank: ', sess.run(tf.rank(tensor))) # Tensor Rank: 3
# Print the shapes
print('Scalar Shape: ', sess.run(tf.shape(scalar))) # Scalar Shape: []
print('Vector Shape: ', sess.run(tf.shape(vector))) # Vector Shape: [5]
print('Matrix Shape: ', sess.run(tf.shape(matrix))) # Matrix Shape: [3 2]
print('Tensor Shape: ', sess.run(tf.shape(tensor))) # Tensor Shape: [3 3 3]
if __name__ == '__main__':
'''
Starting point
'''
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment