python - 在 keras 中创建自定义激活函数
问题描述
我正在尝试在 keras 中创建自己的自定义激活函数,如果 x < 0 则返回 0,如果 x >= 0 则返回 1
from keras.layers import Dense
from keras.models import Sequential
from keras.layers import Activation
import tensorflow as tf
def hard_lim(x):
zero = tf.convert_to_tensor(0., x.dtype.base_dtype)
one = tf.convert_to_tensor(1., x.dtype.base_dtype)
sess = tf.Session()
if sess.run(tf.greater_equal(x, zero)):
return one
else:
return zero
model = Sequential()
model.add(Dense(4, input_dim=2, activation=Activation(hard_lim))
model.add(Dense(2, activation=Activation(hard_lim))
model.add(Dense(1, activation=Activation(hard_lim))
它给了我这个错误
InvalidArgumentError (see above for traceback): You must feed a value
for placeholder tensor '1_input' with dtype float and shape [?,2]
我该如何解决?
解决方案
警告:你想要的这个操作没有梯度,并且在它之前不允许任何权重是可训练的。您将看到错误消息,例如“操作没有渐变”或“不支持无类型”之类的错误消息。
作为激活的一种解决方法,我相信“relu”激活将是最接近和最好的选择,其优势是非常受欢迎并在大多数模型中使用。
在 Keras 中,您通常不运行会话。对于自定义操作,您可以使用后端函数创建函数。
所以,你会使用一个Lambda
层:
import keras.backend as K
def hardlim(x):
return K.cast(K.greater_equal(x,0), K.floatx())
然后,您可以activation=hardlim
在图层中使用。
推荐阅读
- git - Visual Studio 代码源代码管理与资源管理器不同步
- python - NLopt AUGLAG 的舍入限制错误 - 发生此错误时如何获得合理的值以及为什么会发生?
- javascript - 如何在每个文件中保持相同的音量
- c# - EF Core 和 Postgres 中的原子事务
- javascript - 使用javascript中的reduce方法从数组中删除冗余方向
- python - 获取包含特定时间的所有数据行,不分日、月、年
- php - 无法从codeigniter中的数据库中删除数据
- regex - 正则表达式:如何选择后面的字符
没有选择那个 ? - ios - SwiftUI 列表不显示图像
- javascript - 替代componentWillMount注册axios拦截器?反应