繁体   English   中英

将输入层与另一个顺序模型一起传递到自定义损失函数中

[英]passing input layer along with another sequential model into a custom loss function

我正在尝试使用 TensorFlow 2.0 为 Keras 模型编写自定义损失函数。 我按照类似答案中的说明将输入层放入损失函数中,例如

这里

Keras 自定义损失函数:访问当前输入模式

和这里

https://datascience.stackexchange.com/questions/25029/custom-loss-function-with-additional-parameter-in-keras

但我还想将第二个模型的输出添加到损失函数中。

该错误似乎来自 v.predict(x)。 起初 TensorFlow 会给出类似 ValueError 的错误:当使用数据张量作为模型的输入时,您应该指定steps参数。

所以我尝试添加步骤 arg v.predict(x,steps=n) ,其中 n 是一些整数,我得到 AttributeError: 'Tensor' object has no attribute 'numpy'

X = 一些 np.random 数组 Y = X 的一些函数加噪声

def build_model():
    il = tf.keras.Input(shape=(2,),dtype=tf.float32)
    outl = kl.Dense(100,activation='relu')(il)
    outl = kl.Dense(50,activation='relu')(outl)
    outl = kl.Dense(1)(outl)
    return il,outl

def f(X,a):
    return (X[:,0:1] + theta*a)*a

def F(x,a):
    eps = tf.random.normal(tf.shape(x),mean=loc,stddev=scale)[:,0:1]
    z = tf.stack([x[:,0:1] + theta*a + eps,x[:,1:] - a],axis=1)[:,:,0]
    return z

def c_loss(x=None,v=None):
    def loss(y_true,y_pred):
        xp = F(x,y_pred)
        return kb.mean(f(x,y_pred) + v.predict(xp)) 
    return loss

v_in,v_out = build_model()
v_model = tf.keras.Model(inputs=v_in,outputs=v_out)
v_model.compile(tf.keras.optimizers.Adam(),loss='mean_squared_error')
v_model.fit(x=X,y=Y)

c_in,c_out = build_model()
c_model = tf.keras.Model(inputs=c_in,outputs=c_out)
c_model.compile(tf.keras.optimizers.Adam(),loss=c_loss(x=c_in,v=v_model))
c_model.fit(x=X,y=Y_dummy)

理想情况下,我只希望调用 c_model.fit() 来构建神经网络以最小化函数 f(x,a) + v(x)。

我在这里找到了答案。 我有“步骤”错误,但实际问题是“numpy”错误。 我在程序的开头添加了tf.enable_eager_execution()以处理它。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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