Keras - 在 `compile()` 之后修改 lambda 层

Keras - Modifying lambda layer after `compile()`

在 Keras 中,如何在模型编译后更改 lambda 层?

更具体地说,假设我想要一个计算 y=a*x+b 的 lambda 层,每个时期都更改 ab

import keras
from keras.layers import Input, Lambda, Dense
import numpy as np


np.random.seed(seed=42)

a = 1
b = 2

def f(x, a, b):
    return a * x + b

inputs = keras.layers.Input(shape=(3,))
lam = Lambda(f, arguments={"a": a, "b": b})(inputs)
out = keras.layers.Dense(5)(lam)

model = keras.models.Model(inputs, out)
model.trainable = False
model.compile(optimizer='rmsprop', loss='mse')

x1 = np.random.random((10, 3))
x2 = np.random.random((10, 5))

model.fit(x1, x2, epochs=1)

print("Updating. But that won't work")
a = 10
b = 20
model.fit(x1, x2, epochs=1)

这个 return 两次 loss: 5.2914 它应该 return 一次 loss: 5.2914 然后 loss: 562.0562

据我所知,这似乎是一个 open issue可以 通过编写自定义层来补救,但我还没有做过有用。

欢迎任何指导。

如果您使用 ab 作为张量,您甚至可以在编译后更改它们的值。

有两种方法。在一种情况下,您将 ab 视为全局变量并从函数外部获取它们:

import keras.backend as K

a = K.variable([1])
b = K.variable([2])

def f(x):
    return a*x + b #see the vars coming from outside here

#....

lam = Lambda(f)(inputs)

您可以随时手动调用K.set_value(a,[newNumber])

K.set_value(a,[10])
K.set_value(b,[20])
model.fit(x1,x2,epochs=1)

在另一种方法中(我不知道是否有优势,但......听起来至少更有条理)你可以将 ab 作为模型的输入:

a = K.variable([1])
b = K.variable([2])
aInput = Input(tensor=a)
bInput = Input(tensor=b)

def f(x):
    return x[0]*x[1] + x[2] #here, we input all tensors in the function

#.....

lam = Lambda(f)([inputs,aInput,bInput])

您设置 ab 的值的方式与其他方法相同。