6

Given a 3D input tensor (let's say (8,32,100)) I'm trying to implement a Lambda Layer in Keras to select a slice of such input vector.

If I always wanted the same slice (e.g. all inputs between located between the position 2 and 4 in the second dimension), I think this would work:

Lambda(lambda x: x[:,2:4,:], output_shape=(3,100,), name="lambda_layer")(input)

But in my case, for each training sample I'm interested in accessing different slices to then connect them to a Dense layer. I tried the option below these lines, but I cannot feed a scalar (i and j) to the model, since they will be considered tuples (and defining shape=(1) is not valid).

i = Input(shape=(1,), dtype="int32") j = Input(shape=(1,), dtype="int32") Lambda(lambda x: x[:,i:j,:], output_shape=(3,100,), name="lambda_layer")([input,i,j])

Aghie
  • 81
  • 1
  • 7

1 Answers1

3

You should be able to do something like this:

F = Lambda(lambda x, i, j: x[:,i:j,:], output_shape=(3,100,), name="lambda_layer")  # Define your lambda layer
F.arguments = {'i': 2, 'j':4}  # Update extra arguments to F
F(x)  # Call F

You can see how that arguments as passed in as kwargs to your function in here: https://github.com/fchollet/keras/blob/bcef86fad4227dcf9a7bb111cb6a81e29fba26c6/keras/layers/core.py#L651

iga
  • 3,571
  • 1
  • 12
  • 22
  • I had a similar problem and this does work magically. Is there any other syntax that would work as well ? For me, all F(x,2,4) or F(x, i =2, j = 4), or F(x, {'i': 2, 'j':4}) give an error. – Mike Azatov Mar 08 '22 at 14:26