# Tensorflow 2 – How to Reverse a Tensor

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:**

- Tensorflow 2 – One Hot Encoding Examples
- Tensorflow 2 – Removing all Single Dimensions from a Tensor
- Tensorflow 2 – Get the Indices of Min and Max in a Tensor
- Tensorflow 2: Convert Arrays to Tensors (2 Examples)

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

Subscribe

0 Comments