python - 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 自定义激活函数
解决方案
推荐阅读
- java - 无法在项目 springboot 上执行目标 org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile)
- javascript - 如何使用 JS 将值从一个输入字段复制到另一个字段
- php - session_set_cookie_params 数组到字符串的转换
- c - 我将gets转换为fgets,但代码进入无限循环
- lua - 有没有办法在喊或说时获得最后的聊天按摩?
- css - Docker 在 sapper 图像构建上抛出 postcss 错误
- serialization - UWP DataWriter.WriteDateTime 使用什么格式?
- django - Django + Heroku + MongoDB Atlas (Djongo) = DatabaseError 无异常
- java - 如何使用 mockito 在不同的 jar 中模拟方法
- amazon-web-services - AWS Data Pipeline 不支持“m3.xlarge”