慕標(biāo)琳琳
2022-06-14 15:21:45
我正在制作一個(gè)具有兩個(gè)自定義激活函數(shù)的神經(jīng)網(wǎng)絡(luò)。第一個(gè)激活函數(shù)是 f(x),第二個(gè)是 f(x) 對 f(x) 的導(dǎo)數(shù)。我怎樣才能讓 Keras 后端自動(dòng)完成,而不是手動(dòng)獲取導(dǎo)數(shù),這對于我的實(shí)際情況非常困難?這是我的代碼: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_f(x): return (K.sigmoid(x) *2-1 )def custom_activation_fprime(x): deriv(x)= # take the derivative of custom_activation_f(x) return deriv(x)x_train=np.random.uniform(low=-1,high=1,size=(200,2))model=Sequential([ Dense(20,input_shape=(2,)), Activation(custom_activation_f), Dense(2,), Activation(custom_activation_fprime)])model.compile(optimizer='adam',loss='mean_squared_error')model.fit(x_train,x_train,epochs=20,validation_split=0.1)更新:收到 Pranit Kothari 的答復(fù)后,我將 custom_activation_fprim 部分更改為以下內(nèi)容:def custom_activation_fprime(x): my_derivative= K.gradients(custom_activation_f, x) return my_derivative這是我應(yīng)該如何使用它嗎?
2 回答

MMTTMM
TA貢獻(xiàn)1869條經(jīng)驗(yàn) 獲得超4個(gè)贊
有兩種方法可以解決它。
使用 K.gradients 取導(dǎo)數(shù),但它需要張量作為輸入,但這里是一個(gè)函數(shù)。下面是如何使用它的示例片段。
示例代碼片段
def custom_activation_fprime(x):
my_derivative= K.gradients(tf.convert_to_tensor(custom_activation_f(x), dtype=tf.float32), x)
return my_derivative
或 2. 創(chuàng)建自定義導(dǎo)數(shù)函數(shù)并將該函數(shù)作為激活傳遞給模型

狐的傳說
TA貢獻(xiàn)1804條經(jīng)驗(yàn) 獲得超3個(gè)贊
你試過gradientskeras 嗎?
from keras import backend
backend.gradients(loss, variable)
添加回答
舉報(bào)
0/150
提交
取消