Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Slice tensor with variable indexes with Lambda Layer in Keras

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])

like image 736
Aghie Avatar asked Nov 16 '17 20:11

Aghie


1 Answers

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

like image 161
iga Avatar answered Oct 18 '22 14:10

iga