tensorflow - 张量流中的自定义激活函数,具有可学习的 tanh 参数
问题描述
我想在 tensorflow 中实现一个自定义激活函数。这个激活函数的想法是它应该学习它的线性度。使用以下功能。
tanh(x*w)/w for w!= 0
x for w = 0
应该学习参数 w。但是我不知道如何在 tensorflow 中实现这一点。
解决方案
激活函数只是模型的一部分,所以这里是您描述的函数的代码。
import tensorflow as tf
from tensorflow.keras import Model
class MyModel(Model):
def __init__(self):
super().__init__()
# Some layers
self.W = tf.Variable(tf.constant([[0.1, 0.1], [0.1, 0.1]]))
def call(self, x):
# Some transformations with your layers
x = tf.where(x==0, x, tf.tanh(self.W*x)/self.W)
return x
因此,对于非零矩阵MyModel()(tf.constant([[1.0, 2.0], [3.0, 4.0]]))
,它返回
<tf.Tensor: shape=(2, 2), dtype=float32, numpy=
array([[0.9966799, 1.9737529],
[2.913126 , 3.79949 ]], dtype=float32)>
对于零矩阵MyModel()(tf.constant([[0.0, 0.0], [0.0, 0.0]]))
,它返回零
<tf.Tensor: shape=(2, 2), dtype=float32, numpy=
array([[0., 0.],
[0., 0.]], dtype=float32)>
推荐阅读
- visual-c++ - RegGetValue 返回类型 REG_NONE
- spring - 有哪些具体案例可以证明 Spring 选择优于 Spring Boot 是合理的?
- python - 在 python 中创建具有分布作为插图的图形的最佳方法是什么?
- python - 向数据库发送信息时出错
- c# - StackExchange Redis 中的 KeysAsync 方法在哪里
- ios - 如何从其句柄(macOS / iOS)中获取库的路径?
- pandas - 在两列之间查找最早和最晚的日期
- python-3.x - 如何修复python sqlite数据库不存储数据
- javascript - Uncaught DOMException (in promise) - 在 serviceworker 中劫持特定的 GraphQL 请求
- swift - Auth0 不会使用 swift 退出