2

Let's say I have a tensor (None, 2, 56, 56, 256). Now I want to have my tensor with shape (None, 2, 55, 55, 256) by dropping last col and last row. How can I acheive this using Keras/Tensorflow?

donto
  • 141
  • 1
  • 12
  • Possible duplicate of [Slicing a tensor by using indices in Tensorflow](https://stackoverflow.com/questions/41715511/slicing-a-tensor-by-using-indices-in-tensorflow) – Sharky Jun 09 '19 at 13:17

1 Answers1

2

In tensorflow we can slice tensors using python slice notation. SO, given a tensor X with shape (20,2,56,56,256) say (as you have described but with a batch size of 20), we can easily slice it taking all but the last 'row' in the 2nd and 3rd dimension as follows:

X[:,:,:-1,:-1,:]

Note the use of :-1 to denote "everything before the last 'row'".

Given this know-how about slicing the tensor in tensorflow we just need to adapt it for keras. We could, of course, write a full blown custom layer implementing this (or possibly even find one out there someone else has written - I've not looked but slicing is pretty common so suspect someone has written something somewhere!).

However, for something as simple as this, I'd advocate just using a Lambda layer which we can define as follows:

my_slicing_layer = Lambda(lambda x: x[:,:,:-1,:-1,:], name='slice')

And can use in our keras models as normal:

my_model = Sequential([
    Activation('relu', input_shape=(2,56,56,256)),
    my_slicing_layer
])
Stewart_R
  • 13,764
  • 11
  • 60
  • 106