简体   繁体   中英

Keras: Lambda layer function with multiple parameters

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?

Just use

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

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

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

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

worked!

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM