1 回答

TA貢獻(xiàn)1796條經(jīng)驗(yàn) 獲得超10個贊
上面的代碼有幾個問題,但最值得注意的一個是你沒有返回lossfrom weighted_categorical_crossentropy。它應(yīng)該看起來更像:
? ? def weighted_categorical_crossentropy(self, weights):
? ? ? ? weights = K.variable(weights)
? ? ? ? def loss(y_true, y_pred):
? ? ? ? ? ? y_pred /= K.sum(y_pred, axis=-1, keepdims=True)
? ? ? ? ? ? y_pred = K.clip(y_pred, K.epsilon(), 1 - K.epsilon())
? ? ? ? ? ? loss = y_true * K.log(y_pred) * weights
? ? ? ? ? ? loss = -K.sum(loss, -1)
? ? ? ? ? ? return loss
? ? ? ? return loss # Return the callable function!
錯誤是ValueError: No gradients provided for any variable因?yàn)閘oss方法不返回任何東西,它返回None!如果您嘗試使用 擬合方法loss=None,模型將無法計(jì)算梯度,因此會拋出相同的錯誤。
接下來是您return_sequences = True在非循環(huán)層之前的層中使用的 。這會導(dǎo)致Dense在形狀錯誤的數(shù)據(jù)上調(diào)用該層,這僅適用于循環(huán)層。不要那樣使用它。
如果您有充分的理由使用return_sequences = True,那么您必須添加Dense如下層:
model.add(keras.layers.TimeDistributed(keras.layers.Dense(...)))
這將導(dǎo)致該層在每個時間步上分別Dense作用于輸出序列。這也意味著您的體形必須合適。y_true
您定義的自定義損失函數(shù)可能存在其他問題,但我無法推斷出輸入/輸出形狀,因此您必須運(yùn)行它并添加看看它是否有效??赡軙嬖诰仃嚦朔ㄐ螤畈黄ヅ涞那闆r。
最后但并非最不重要的一點(diǎn)是,考慮使用子類 API。它能讓你的操作更容易編寫嗎?
添加回答
舉報(bào)