How can I remove the first element of a tensor in keras as a layer?

How can I remove the first element of a tensor in keras as a layer? For example:

layer = Input(input_shape=(100,),name='input')
layer = Conv1D(97,kernel_size=10,strides=10)(layer)
layer = >something that removes the first element<(layer)
layer = Flaten()(layer)
model = Model(input,layer)

      

This model would have outputs 97*9

. 97

from the Conv layer, and each conv filter will output nodes 10

, but the first of those nodes will be removed with the layer I'm looking for. Since the conv layer is shaped (batch_size,10,97)

, I'm looking for a way to remove the first element axis=1

.

How should I do it? I've tried using a Lambda layer, but I can't figure out how to do it.

Edit: I am asking this question because I want to do if I have a shape layer (batch_size, x, y)

I want to convert it to a shape (batch_size, 0.5x, 2y)

in such a way that if x

, for example 10

, the elements are 0,2,4,6,8

and 1,3,5,7,9

are stacked on top of each other. Right now I am doing this with the help Maxpooling1D(pool_size=1, strides=2)

to generate 0,2,4,6,8

. To generate 1,3,5,7,9

, I have to delete one element from the beginning in the manner described above before applying the maxpooling layer. Thank you so much for your time!

+3


source to share


3 answers


Because @NadavB wants to know the answer:

layer = Input(input_shape=(100,),name='input')
layer = Conv1D(97,kernel_size=10,strides=10)(layer)
layer = Lambda(lambda x : x[:,1:,:])(layer)
layer = Flaten()(layer)
model = Model(input,layer)

      



Hope this helps you :)

+1


source


If your only goal is to have 9 values ​​instead of 10 from the convolution, why don't you try:

layer = Conv1D (97, kernel_size = 11, strides = 11) (layer)



? Because if you remove the first element it means you don't need the first 10 values ​​of your sequence, so you can also use sequences of 90 values ​​instead of 100 ... If you like those 10 first values ​​and just want to print less, and then use a larger kernel :-)

Does it help? Otherwise, we can compute a lambda layer that does the trick

+1


source


If it's a timing sequence, I do this:

def firstElementRemoved(inputTensor):
    return inputTensor[:, 1:]

LSTMMinusFirstElement  = Lambda(firstElementRemoved) (LSTM)

      

0


source







All Articles