tensorflow - 在 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 数组并返回会减慢网络训练速度。解决此错误但仍保留硬件加速优势的最佳方法是什么?
解决方案
我建议你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
推荐阅读
- java - Mono.defer() 做什么?
- c++ - 如何识别“错误”指针
- spring - 如何在子类中为基类中定义的字段使用@Autowired?
- c# - Sql 数据类型日期也显示时间
- machine-learning - 如何在不丢失早期模型的情况下根据新数据重新训练模型
- c++ - CGAL:加载 .off 文件后如何访问顶点颜色?
- java - 在没有任何循环的情况下反转整数数组
- java - Spring config 附加位置作为 docker-compose 中的环境变量
- python-3.x - 有没有更有效的方法来使用 zenpy 编写这个 API 调用的脚本?
- c# - 将 C# 加密算法转换为 Python 3