Understand TensorFlow tf.reverse():Reverse a Tensor Based on Axis – TensorFlow Tutorial

By | June 28, 2020

TensorFlow tf.reverse() function allows us to reverse a tensor based on aixs. In this tutorial, we will use some examples to illustrate you how to use this function correctly.

Syntax

tf.reverse(
    tensor,
    axis,
    name=None
)

Reverses specific dimensions of a tensor.

You should make axis is a list, otherwise, you will get a value error.

Fix TensorFlow tf.reverse() ValueError: Shape must be rank 1 but is rank 0

We will use some examples to show how to use this function.

Create a tensor with 2*3*4 shape

import tensorflow as tf
import numpy as np

x = tf.Variable(np.array(range(24)), dtype = np.float32, name = 'x')
x = tf.reshape(x, [2, 3, 4])

Here x is:

[[[ 0.  1.  2.  3.]
  [ 4.  5.  6.  7.]
  [ 8.  9. 10. 11.]]

 [[12. 13. 14. 15.]
  [16. 17. 18. 19.]
  [20. 21. 22. 23.]]]

Reverse tensor x based on axis = [0]

x1 = tf.reverse(x, axis = [0])

Then you will find x1 is:

[[[12. 13. 14. 15.]
  [16. 17. 18. 19.]
  [20. 21. 22. 23.]]

 [[ 0.  1.  2.  3.]
  [ 4.  5.  6.  7.]
  [ 8.  9. 10. 11.]]]

Reverse tensor x based on axis = [1]

x2 = tf.reverse(x, axis = [1])

The x2 will be:

[[[ 8.  9. 10. 11.]
  [ 4.  5.  6.  7.]
  [ 0.  1.  2.  3.]]

 [[20. 21. 22. 23.]
  [16. 17. 18. 19.]
  [12. 13. 14. 15.]]]

Reverse tensor x based on axis = [2]

x3 = tf.reverse(x, axis = [2])

x3 will be:

[[[ 3.  2.  1.  0.]
  [ 7.  6.  5.  4.]
  [11. 10.  9.  8.]]

 [[15. 14. 13. 12.]
  [19. 18. 17. 16.]
  [23. 22. 21. 20.]]]

Leave a Reply