【问题标题】:Keras - Modifying lambda layer after `compile()`Keras - 在`compile()`之后修改lambda层
【发布时间】:2018-04-30 07:03:47
【问题描述】:

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

这会返回两次loss: 5.2914,它应该返回一次loss: 5.2914,然后是loss: 562.0562

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

欢迎任何指导。

【问题讨论】:

    标签: python lambda keras keras-layer


    【解决方案1】:

    如果您使用 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 的值的方式与其他方法相同。

    【讨论】:

      猜你喜欢
      • 2019-03-19
      • 1970-01-01
      • 2019-01-01
      • 2020-02-02
      • 2017-03-31
      • 1970-01-01
      • 1970-01-01
      • 2019-08-21
      • 2017-07-27
      相关资源
      最近更新 更多