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

Python Keras-在`compile()之后修改lambda层`,python,lambda,keras,keras-layer,Python,Lambda,Keras,Keras Layer,在Keras中,在编译模型后如何更改lambda层 更具体地说,假设我想要一个lambda层,它计算y=a*x+b,并且a和b每一个历元都会改变 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

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

更具体地说,假设我想要一个lambda层,它计算
y=a*x+b
,并且
a
b
每一个历元都会改变

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)
这将返回两次
loss:5.2914
,其中应返回一次
loss:5.2914
,然后返回
loss:562.0562

据我所知,这似乎是一个问题,可以通过编写自定义层来解决,但我还没有让它正常工作


欢迎您提供任何指导。

如果您将
a
b
用作张量,则即使在编译后也可以更改其值

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

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\u value(a,[newNumber])

在另一种方法中(我不知道是否有优势,但……听起来至少组织得更好),您可以将
a
b
作为模型的输入:

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])
您可以使用与另一种方法相同的方法设置
a
b
的值

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])