Keras: Lambda layer function with multiple paramet

2020-06-09 06:27发布

问题:

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?

回答1:

Just use

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

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



回答2:

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

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

worked!



回答3:

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)