添加要与字符串一起使用的自定义激活函数

Add custom activation function to be used with a string

我按照 this 响应做了:

get_custom_objects().update(act_dispatcher)

其中 act_dispatcher 是一个字典,其中包含我要添加的所有激活函数,例如 {'fun_1':fun_1, 'fun_2': fun_2}

首先引起我注意的是,一开始,如果我什么都不加,get_custom_objects() returns 一个空字典 {}。添加函数后,我检查对 get_custom_objects() 的每次调用是否符合我所说的。

但是,我得到 ValueError: Unknown activation function:<my_fun>

我添加了行

assert 'my_func', in get_custom_objects().keys()

tf.keras.layers.Dense(128, activation='my_func')

并且断言毫无问题地通过了 keras Dense init 中提到的错误。


错误发生在deserialize_keras_object,其中:


安装

我正在使用 anaconda 环境。由于我首先使用 from keras.utils.generic_utils import get_custom_objects 时出现的错误,我安装了 keras-applicationsconda install -c conda-forge keras-applications

我可以运行那些代码没有任何错误,你可以尝试将from tensorflow.keras.utils.generic_utils import get_custom_objects更改为from tensorflow.keras.utils import get_custom_objects看看是否有帮助:

from tensorflow.keras import backend as K
from tensorflow.keras.utils import get_custom_objects
from tensorflow.keras.layers import Activation, Conv2D
from tensorflow.keras.models import Sequential

def my_func(x, beta=1.0):
    return x * K.sigmoid(beta * x)

model = Sequential()
model.add(Conv2D(64, (3, 3)))
model.add(Activation(my_func))

get_custom_objects().update({'my_func': Activation(my_func)})

model.add(Conv2D(64, (3, 3), activation='my_func'))