0

Suppose I have the input of form [a,b,c] and I want to produce the output [a * b, b * c]

I thus would try something like this:

input = Input((3,))
output = Lambda(lambda x: [x[0]*x[1], x[1]*x[2]], output_shape = (2,))(input) 
model = Model(input, output)

However, it seems to not work. When I print the summary I get:

shape(input) = (None,3)
shape(output) = [(3,),(3,)] ## shouldn't this be (None,2)?

1 Answer 1

1

Input tensor x in your case has shape (None,3) so x[0] is first sample in batch and not a first feature. You should use x[:,0] instead. Also returing list of tensors from layers means that layers has multiple outputs (not single output with multiple features) so you will need to stack them with tf.stack.

Here is sample code:

input = Input((3,))
output = Lambda(lambda x: tf.stack([x[:,0]*x[:,1], x[:,1]*x[:,2]], axis=1))(input) 

Results

input.shape # TensorShape([None, 3])
output.shape # TensorShape([None, 2])
Sign up to request clarification or add additional context in comments.

1 Comment

Great answer. Would also add that you can golf the Lambda layer further by using a vectorized multiply: output = Lambda(lambda x: x[:,0:2]*x[:,1:3])(input)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.