gpt4 book ai didi

python - 反向传播时为 Keras 定制导数?

转载 作者:太空宇宙 更新时间:2023-11-03 15:30:25 28 4
gpt4 key购买 nike

这与 How do you create a custom activation function with Keras? 有关

我已经实现了自己的成本函数

import numpy as np
import math
import keras
from keras.models import Model, Sequential
from keras.layers import Input, Dense, Activation
from keras import regularizers
from keras import backend as K

def 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 要复杂得多。

最佳答案

在您的函数上使用 @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))

关于python - 反向传播时为 Keras 定制导数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58122557/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com