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

2024-05-05 01:48:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图用TensorFlow2.0为Keras模型编写一个自定义的损失函数。我按照一个类似的答案,让输入层进入损耗函数

这里

Keras custom loss function: Accessing current input pattern

这里呢

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”对象没有属性“numpy”

X=一些np.随机阵列 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_模型.拟合()建立最小化函数f(x,a)+v(x)的神经网络。在


Tags: 函数in模型buildmodelreturntfdef