首页 > 解决方案 > 在 tensorflow 2.0 中制作自定义激活函数

问题描述

我正在尝试在 tensorflow 中创建一个自定义的 tanh() 激活函数来处理我想要的特定输出范围。我希望我的网络输出浓度乘数,所以我想如果 tanh() 的输出为负,它应该返回 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 数组并返回会减慢网络训练速度。解决此错误但仍保留硬件加速优势的最佳方法是什么?

标签: tensorflowkerastensorflow2.0activation-function

解决方案


我建议你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


推荐阅读