簡體   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