16

I am trying to write a Lambda layer in Keras which calls a function connection, that runs a loop for i in range(0,k) where k is fed in as an input to the function, connection(x,k). Now, when I try to call the function in the Functional API, I tried using:

k = 5
y = Lambda(connection)(x)

Also,

y = Lambda(connection)(x,k)

But neither of those approaches worked. How can I feed in the value of k without assigning it as a global parameter?

2
  • Is "k" a constant? Or is it calculated somewhere in the model? Is it an input to the model, as part of the input data? Commented Jul 5, 2017 at 20:42
  • 1
    k updates through the model. The value of k changes for different times I call the Lambda layer. But I found the solution here, in a Keras GitHub Issue. Using y = Lambda(connection, arguments={'k':k})(x) worked! Commented Jul 5, 2017 at 22:39

3 Answers 3

22

Just use

y = Lambda(connection)((x,k)) 

and then var[0], var[1] in connection method

Sign up to request clarification or add additional context in comments.

4 Comments

This is the correct solution which should have been accepted.
This will not work unless both x and k are Tensor objects (cf : Layer lambda_4 was called with an input that isn't a symbolic tensor. Received type: <class 'int'>. Full input: [8]. All inputs to the layer should be tensors.)
@ArthurAttout python variables can be passed to Lambda using local context
I throws error "connection missing 1 required positional argument k" in the newest tensorflow
15

Found the solution to the problem in this GitHub Pull Request. Using

y = Lambda(connection, arguments={'k':k})(x)

worked!

2 Comments

Note: by default model.save_weights() will not recognize k as part of the model.
Yes, this worked indeed. But for the other readers.. please know that the variable k here is already defined as some constant
4
Tmodel = Sequential()
x = layers.Input(shape=[1,])   # Lambda on single input
out1 = layers.Lambda(lambda x: x ** 2)(x)

y = layers.Input(shape=[1,])   # Lambda on multiple inputs
z = layers.Input(shape=[1,])
def conn(IP):
    return IP[0]+IP[1]
out2 = layers.Lambda(conn)([y,z])

Tmodel = tf.keras.Model(inputs=[x,y,z], outputs=[out1,out2],name='Tmodel')  # Define Model
Tmodel.summary()

# output
O1,O2 = Tmodel([2,15,10])
print(O1)   # tf.Tensor(4, shape=(), dtype=int32)
print(O2)   # tf.Tensor(25, shape=(), dtype=int32)

1 Comment

Please add some explanation for better clarity or reference documentation.

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.