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

标签 python lambda keras keras-layer

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

更具体地说,假设我想要一个 lambda 层来计算 y=a*x+b,其中 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)

这将返回两次 loss: 5.2914,而它应该返回一次 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 的值。

关于python - Keras - 在 `compile()` 之后修改 lambda 层,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47334788/

相关文章:

python - 如何在 Jinja2 的子模板中设置变量?

c# - 如何将表达式传递到 Entity Framework LINQ 查询 OrderBy 子句中

javascript - 如何用Java编写立即函数调用?提供的 JavaScript 示例

python - 通过梯度下降在每一步更新的自定义损失函数

python - 如何修复属性错误: module 'tensorflow' has no attribute 'reset_default_graph'

python - 尝试在 ubuntu 上安装 pygame 出现错误

python - 以 png 格式保存图像的 2 channel 像素

java - 使用带有参数的方法引用

theano - Keras:如果数据大小不能被batch_size整除怎么办?

java - cloudfoundry 中有多个构建包