Skip to main content
 首页 » 编程设计

python之keras + tensorflow 中的高级自定义激活函数

2025年05月04日27luoye11

def newactivation(x): 
    if x>0: 
        return K.relu(x, alpha=0, max_value=None) 
    else : 
        return x * K.sigmoid(0.7* x) 
 
get_custom_objects().update({'newactivation': Activation(newactivation)}) 

我正尝试在 keras 中为我的模型使用此激活函数,但我很难找到要替换的内容

if x>0: 

我得到的错误:

File "/usr/local/lib/python3.4/dist-packages/tensorflow/python/framework/ops.py", line 614, in bool raise TypeError("Using a tf.Tensor as a Python bool is not allowed. "

TypeError: Using a tf.Tensor as a Python bool is not allowed. Use if >t is not None: instead of if t: to test if a tensor is defined, and >use TensorFlow ops such as tf.cond to execute subgraphs conditioned on >the value of a tensor.

有人能帮我说清楚吗?

请您参考如下方法:

if x > 0 没有意义,因为 x > 0 是张量,而不是 bool 值。

要在 Keras 中执行条件语句,请使用 keras.backend.switch。

比如你的

if x > 0: 
   return t1 
else: 
   return t2 

会变成

keras.backend.switch(x > 0, t1, t2)