[英]Custom Activation function in tensorflow with learnable parameter for tanh
我想在 tensorflow 中實現自定義激活 function。 這個激活 function 的想法是它應該學習它的線性度。 使用以下 function。
tanh(x*w)/w for w!= 0
x for w = 0
應該學習參數 w。 但是我不知道如何在 tensorflow 中實現這一點。
激活 function 只是 model 的一部分,所以這里是您描述的 function 的代碼。
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)>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.