首页 > 解决方案 > Tensorflow 可以自定义激活层自动微分并且不需要指定梯度或权重吗?

问题描述

我的 tensorflow 是 2.4.0 ,但我使用的是 tensorflow 1 base(sess.run) 中的代码,我想将我的网络激活函数更改为下面的自定义类型,它在同一个类中定义

 def new_relu10000(self, x, k=1):
    part_1 = tf.cast(tf.math.logical_and(tf.math.less_equal(0.0, x), tf.math.less(x, 10000.0)), dtype=tf.float32)
    part_3 = tf.cast(tf.math.less_equal(10000.0, x), dtype=tf.float32)
    return part_1*x*k + part_3*10000.0

我的网络被定义为

 def _build_a(self, s, scope, trainable):
        with tf.compat.v1.variable_scope(scope):
            net = tf.compat.v1.layers.dense(s, 400, activation=tf.nn.relu, name='l1', trainable=trainable)
            net2 = tf.compat.v1.layers.dense(net,300, activation=tf.nn.relu, name='l2', trainable=trainable)
            a = tf.compat.v1.layers.dense(net2, self.a_dim, activation=self.new_relu10000, name='a', trainable=trainable)
            return  a

并且这段代码可以编译并成功运行(a的输出永远不会大于10000),但是,我很担心,因为我看到其他人说我们需要定义自定义激活函数的梯度,例如 如何在 Tensorflow 中仅使用 Python 制作自定义激活函数?. 但是我在这里也看到了Tensorflow自定义激活函数的答案说使用张量类型时会自动微分,但是下面同一个问题的答案说需要定义自定义激活函数的权重

所以我想问一下我上面的激活函数定义好可以直接使用吗?或者我需要像这个问题答案一样定义渐变部分How to make a custom activation function with only Python in Tensorflow? ? 或者我需要为激活函数创建权重就像这里的解决方案一样?TensorFlow 自定义激活函数

标签: pythontensorflow

解决方案


推荐阅读