Tensorflow 2 – How to Reverse a Tensor

Last updated on September 13, 2021 The Plumber Loading... Post a comment

The examples below show you a couple of different ways to reverse a tensor in Tensorflow 2.

Using the tf.reverse() function

The tf.reverse() function can be used to flip specific dimensions of a tensor.

Example:

import tensorflow as tf

a = tf.constant([0, 1, 1, 2, 3, 5])
b = tf.constant([
                 [1, 2, 3],
                 [4, 5, 6],
                 [7, 8, 9]
])



a_reversed = tf.reverse(a, axis=[0])
b_reversed = tf.reverse(b, axis=[0, 1])

tf.print(a_reversed)
tf.print(b_reversed)

Output:

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

Using [::-1]

Example:

import tensorflow as tf

x = tf.constant([1, 2, 3, 4, 5, 6])
y = x[::-1]
tf.print(y)

Output:

[6 5 4 3 2 1]

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