2 回答

TA貢獻1784條經驗 獲得超8個贊
在您的函數上使用@tf.custom_gradient裝飾器并在其中定義grad(dy)要返回的函數:
#works only with tensorflow
from keras.backend import tf
@tf.custom_gradient
def custom_activation(x):
#... do things ...
def grad(dy):
#... do things ...
return dy * the_derivative(x)
#... do things ...
return result, grad #return the result and the gradient function
改編自:https ://www.tensorflow.org/api_docs/python/tf/custom_gradient
我從未在 Keras 中使用過它,但如果它不能立即工作,你可以嘗試將這個函數放入標準 Keras 函數中:
from keras.layers import Lambda
layer = Lambda(lambda x: custom_activation(x))

TA貢獻1880條經驗 獲得超4個贊
我想你的問題與這個問題非常相似how-to-define-the-derivative-of-a-custom-activation-function-in-keras。該鏈接中接受的答案是不言自明且有用的信息。
簡而言之,您可以檢查TF Add New Op。.
添加回答
舉報