使用keras自定义激活

2024-04-23 07:31:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试用TensorFlow 2.0在Keras中构建双曲正切sigmoid函数作为自定义激活函数。 我在论坛中尝试了不同的建议,如thisalso this,但出现了一个错误: AttributeError:模块“TensorFlow”没有“get\u default\u graph”属性

据我所知,这个问题是在TensorFlow2.0中讨论的here。我相应地修改了代码,但现在出现了一个错误: NotImplementedError:无法转换符号张量(密集\u 3)/标识:0)到numpy数组。你知道吗

这是我的密码:

import tensorflow as tf
import numpy as np
from tensorflow.python.framework import ops

from tensorflow.python.keras import backend as k

x=np.arange(-40,40,1)
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
# Custom activation function
from tensorflow.keras.layers import Activation

from tensorflow.python.keras.utils.generic_utils import get_custom_objects

# definition of tanhsigma
def tanhsigma(x):
    return 2/(1+np.exp((-2*x)))-1
tanhsigma=np.vectorize(tanhsigma)
derive_tanhsigma=tf.GradientTape(tanhsigma,x)
np_derive_tanhsigma=lambda x: np_derive_tanhsigma(x).astype(np.float32)
def tf_derive_tanhsigma(x,name=None):
    with tf.name_scope(name, "derive_tanhsigma", [x]) as name:
        y = tf.py_func(np_derive_tanhsigma,
                        [x],
                        [tf.float32],
                        name=name,
                        stateful=False)
        return y[0]
tf.compat.v1.get_default_graph
get_custom_objects().update({'tanhsigma': Activation(tanhsigma)})

# Usage
model = Sequential()
model.add(Dense(32, input_dim=784))
model.add(Activation(tanhsigma, name='tanhsigma'))# problem is here
print(model.summary())

请帮助我解决问题。我真的不太懂代码,只是在尝试实现。你知道吗


Tags: 函数namefromimportgetmodeltftensorflow