Tensorflow 2 – Removing all Single Dimensions from a Tensor

Last updated on September 2, 2021 Guest Contributor Loading... Post a comment

In Tensorflow 2, you can remove all size 1 dimensions from a given tensor by using the tf.squeeze function.

Example:

import tensorflow as tf

a = tf.constant([[[[
                    [1, 2],
                    [3, 4]
]]]])

b = tf.squeeze(a)
tf.print('Shape Before:', a.shape)
tf.print('Shape After:', b.shape)

Output:

Shape Before: TensorShape([1, 1, 1, 2, 2])
Shape After: TensorShape([2, 2])

You can find more information about the mentioned function in Tensorflow’s official docs.

Further reading:

You can also check out our Machine Learning category page or Python category page for more tutorials and examples.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

You May Also Like