Skip to content
Related Articles

Related Articles

Improve Article

Python – tensorflow.expand_dims()

  • Last Updated : 21 Aug, 2021

TensorFlow is open-source Python library designed by Google to develop Machine Learning models and deep learning  neural networks. 

expand_dims() is used to insert an addition dimension in input Tensor.

Syntax: tensorflow.expand_dims( input, axis, name)

Parameters:

  • input: It is the input Tensor.
  • axis: It defines the index at which dimension should be inserted. If input has D dimensions then axis must have value in range  [-(D+1), D].
  • name(optional): It defines the name for the operation.

Returns: It returns a Tensor with expanded dimension.



Example 1:

Python3




# Importing the library
import tensorflow as tf
 
# Initializing the input
x = tf.constant([[2, 3, 6], [4, 8, 15]])
 
# Printing the input
print('x:', x)
 
# Calculating result
res = tf.expand_dims(x, 1)
 
# Printing the result
print('res: ', res)

Output:

x: tf.Tensor(
[[ 2  3  6]
 [ 4  8 15]], shape=(2, 3), dtype=int32)
res:  tf.Tensor(
[[[ 2  3  6]]

 [[ 4  8 15]]], shape=(2, 1, 3), dtype=int32)

# shape has changed from (2, 3) to (2, 1, 3)

Example 2:

Python3




# Importing the library
import tensorflow as tf
 
# Initializing the input
x = tf.constant([[2, 3, 6], [4, 8, 15]])
 
# Printing the input
print('x:', x)
 
# Calculating result
res = tf.expand_dims(x, 0)
 
# Printing the result
print('res: ', res)

Output:

x: tf.Tensor(
[[ 2  3  6]
 [ 4  8 15]], shape=(2, 3), dtype=int32)
res:  tf.Tensor(
[[[ 2  3  6]
  [ 4  8 15]]], shape=(1, 2, 3), dtype=int32)
  
# shape has changed from (2, 3) to (1, 2, 3)

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course




My Personal Notes arrow_drop_up
Recommended Articles
Page :