TensorFlow is open-source Python library designed by Google to develop Machine Learning models and deep learning neural networks.
ensure_shape() is used to update and check the shape of Tensor.
Syntax: tensorflow.ensure_shape( x, shape, name)
Parameters:
- x: It is input Tensor.
- shape: It is TensorShape which represents the shape of input Tensor.
- name(optional): It defines the name for the operation.
Returns:
It returns a Tensor same as x or raise tf.errors.InvalidArgumentError if shapes are incompatible.
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.ensure_shape(x, ( 2 , 3 ))
# 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, 3), dtype=int32)
Example 2: In this example shape is incompatible with shape of x so error is raised.
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.ensure_shape(x, ( 2 , 4 ))
# Printing the result print ( 'res: ' , res)
|
Output:
x: tf.Tensor( [[ 2 3 6] [ 4 8 15]], shape=(2, 3), dtype=int32) --------------------------------------------------------------------------- InvalidArgumentError Traceback (most recent call last) <ipython-input-1-ab1be364fadb> in <module>() 9 10 # Calculating result ---> 11 res = tf.ensure_shape(x, (2, 4)) 12 13 # Printing the result 3 frames /usr/local/lib/python3.6/dist-packages/six.py in raise_from(value, from_value) InvalidArgumentError: Shape of tensor dummy_input [2, 3] is not compatible with expected shape [2, 4]. [Op:EnsureShape]