Perm. Questiin
Perm. Questiin

Reputation: 429

How do I flip a Tensor in Keras?

For example: I have a tensor with shape (5,10) and I want back a tensor with shape (5,10) but the first element should now be the last element. so [1,2,3,4,5]becomes [5,4,3,2,1] and [[1,2,3,4,5],[2,3,4,5,6]] becomes [[2,3,4,5,6],[1,2,3,4,5]].

If it matter, I am using tensorflow backend.

Upvotes: 4

Views: 6646

Answers (1)

Daniel Möller
Daniel Möller

Reputation: 86600

Using the Keras backend, there is the reverse function.

import keras.backend as K

flipped = K.reverse(x,axes=0)

For using it in a layer, you can create a Lambda layer:

from keras.layers import *
layer = Lambda(lambda x: K.reverse(x,axes=0),output_shape=(shape of x))

(If it's a sequential layer, model.add(layer), if a functional API model, output = layer(input)

Upvotes: 8

Related Questions