在 tensorflow 2.0 中制作自定义激活函数

Making custom activation function in tensorflow 2.0

我正在尝试在 tensorflow 中创建一个自定义 tanh() 激活函数,以处理我想要的特定输出范围。我希望我的网络输出浓度乘数,所以我想如果 tanh() 的输出是负的,它应该 return 一个介于 0 和 1 之间的值,如果它是正的输出一个介于 1 和 10 之间的值。

这是我目前拥有的

def output_activation(x):
    # function to scale tanh activation to be 1-10 if x > 0, or 0-1 if x < 0
    return tf.cond(x >= 0, lambda: tf.math.tanh(x+0.1)*10, lambda: tf.math.tanh(x) + 1)

我相信这将适用于单个值,但我想输出一个值向量,python 会向其抛出值错误 ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

张量是不可变的,据我所知,如果我在 GPU 上,转换为 numpy 数组并返回会减慢网络训练速度。解决此错误但仍保留硬件加速优势的最佳方法是什么?

我建议你tf.keras.backend.switch。这是一个虚拟示例

import numpy as np
import tensorflow as tf
from tensorflow.keras.layers import *
from tensorflow.keras.models import *
from tensorflow.keras import backend as K

def output_activation(x):
    return K.switch(x >= 0, tf.math.tanh(x+0.1)*10, tf.math.tanh(x) + 1)

X = np.random.uniform(0,1, (100,10))
y = np.random.uniform(0,1, 100)

inp = Input((10,))
x = Dense(8, activation=output_activation)(inp)
out = Dense(1)(x)

model = Model(inp, out)
model.compile('adam', 'mse')
model.fit(X,y, epochs=3)

这里是 运行 笔记本:https://colab.research.google.com/drive/1T_kRNUphJt9xTjiOheTgoIGpGDZaaRAg?usp=sharing