【问题标题】:Add custom activation function to be used with a string添加要与字符串一起使用的自定义激活函数
【发布时间】:2021-03-25 21:14:02
【问题描述】:

我关注了this的回复:

get_custom_objects().update(act_dispatcher)

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

首先引起我注意的是,在开始时,如果我什么都不添加,get_custom_objects() 返回一个空字典{}。添加函数后,我检查每个对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,其中:

  • custom_objectsNone
  • _GLOBAL_CUSTOM_OBJECTS{}(可能不应该为空)。
  • module_objects.get(object_name) 返回无(module_objects 接缝正确)。

安装

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

【问题讨论】:

    标签: python tensorflow tensorflow2.0 activation-function


    【解决方案1】:

    我可以正常运行这些代码,您可以尝试将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'))
    

    【讨论】:

    • 所以我按照你说的添加了 Activation 构造函数,但仍然没有。添加后,我得到print(get_custom_objects())的输出:{'my_fun': <tensorflow.python.keras.layers.core.Activation object at 0x7fbc3c24b6d0>}
    • @AgustinBarrachina 你是如何使用你的自定义激活函数的?像 model.add(my_fun) 还是像 model.add(Conv2D(64, (3, 3), activation='my_fun')) ?你得到了什么错误?还有你的自定义函数是什么样的?
    • model = tf.keras.Sequential([tf.keras.Input(shape), tf.keras.layers.Flatten, tf.keras.layers.Dense(128, activation='my_fun')])
    • 我添加了有关错误的信息,我也去了Tensorflow发生错误的地方。
    • @AgustinBarrachina 我编辑答案,让我知道它是否有用
    猜你喜欢
    • 2018-04-15
    • 2018-09-30
    • 1970-01-01
    • 1970-01-01
    • 2020-02-02
    • 2017-10-10
    • 1970-01-01
    • 1970-01-01
    • 2020-04-11
    相关资源
    最近更新 更多