首页 > 解决方案 > 在 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]

我该如何解决?

标签: pythontensorflowmachine-learningkerasdeep-learning

解决方案


警告:你想要的这个操作没有梯度,并且在它之前不允许任何权重是可训练的。您将看到错误消息,例如“操作没有渐变”或“不支持无类型”之类的错误消息。

作为激活的一种解决方法,我相信“relu”激活将是最接近和最好的选择,其优势是非常受欢迎并在大多数模型中使用。

在 Keras 中,您通常不运行会话。对于自定义操作,您可以使用后端函数创建函数。

所以,你会使用一个Lambda层:

import keras.backend as K

def hardlim(x):
   return K.cast(K.greater_equal(x,0), K.floatx())

然后,您可以activation=hardlim在图层中使用。


推荐阅读