使用自定义激活函数替换Sigmoid激活函数

我正在尝试用一个分段线性函数替换Keras的Sigmoid函数,该函数定义如下:

def custom_activation_4(x):if x < -6:    return 0elif x >= -6 and x < -4:    return (0.0078*x + 0.049)elif x >= -4 and x < 0:    return (0.1205*x + 0.5)elif x >= 0 and x < 4:    return (0.1205*x + 0.5)elif x >= 4 and x < 6:    return (0.0078*x + 0.951)else:    return 1;

当我尝试这样运行时:

classifier_4.add(Dense(output_dim = 18, init = 'uniform', activation = custom_activation_4, input_dim = 9))

编译器抛出错误说:

Using a `tf.Tensor` as a Python `bool` is not allowed.

我研究了这个问题并了解到,我将变量x视为一个简单的Python变量,而它实际上是一个张量。这就是它不能像简单的布尔变量那样被处理的原因。我还尝试使用了tensorflow cond方法。如何在这里将x视为并使用张量?非常感谢您提前提供的所有帮助。


回答:

您的自定义激活函数是作为单个浮点数的函数编写的,但您想将其应用于整个张量。最好的方法是使用tf.where。像这样

def custom_activation_4(x):  orig = x  x = tf.where(orig < -6, tf.zeros_like(x), x)  x = tf.where(orig >= -6 and orig < -4, (0.0078*x + 0.049), x)  x = tf.where(orig >= -4 and orig < 0, (0.1205*x + 0.5), x)  x = tf.where(orig >= 0 and orig < 4, (0.1205*x + 0.5), x)  x = tf.where(orig  >= 4 and orig < 6, (0.0078*x + 0.951), x)  return tf.where(orig >= 6, 1, x)

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注