亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

反向傳播時為 Keras 定制導數?

反向傳播時為 Keras 定制導數?

慕萊塢森 2022-06-07 19:59:04
我已經實現了自己的成本函數import numpy as npimport mathimport kerasfrom keras.models import Model, Sequentialfrom keras.layers import Input, Dense, Activationfrom keras import regularizersfrom keras import backend as Kdef custom_activation(x):    return (K.sigmoid(x) *2-1 ) x_train=np.random.uniform(low=-1,high=1,size=(200,2))model=Sequential([     Dense(20,input_shape=(2,)),     Activation(custom_activation),     Dense(2,),     Activation('linear')])model.compile(optimizer='adam',loss='mean_squared_error')model.fit(x_train,x_train,epochs=20,validation_split=0.1)我可以給它導數,而不是讓 Keras 自動取我的逼近函數的導數嗎?請注意,這只是一個示例。我真正的 custom_activation 要復雜得多。
查看完整描述

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))


查看完整回答
反對 回復 2022-06-07
?
慕村225694

TA貢獻1880條經驗 獲得超4個贊

我想你的問題與這個問題非常相似how-to-define-the-derivative-of-a-custom-activation-function-in-keras。該鏈接中接受的答案是不言自明且有用的信息。

簡而言之,您可以檢查TF Add New Op。.


查看完整回答
反對 回復 2022-06-07
  • 2 回答
  • 0 關注
  • 167 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號