簡體   English   中英

keras + tensorflow 中的高級自定義激活函數

[英]Advanced Custom activation function in keras + tensorflow

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:

錯誤我得到:

文件“/usr/local/lib/python3.4/dist-packages/tensorflow/python/framework/ops.py”,第 614 行, bool raise TypeError(“不允許使用tf.Tensor作為 Python bool 。 “

TypeError:不允許使用tf.Tensor作為 Python bool 使用if >t is not None:而不是if t:來測試是否定義了張量,並使用 TensorFlow ops 例如 tf.cond 來執行以張量值為條件的子圖。

有人能幫我說清楚嗎?

if x > 0沒有意義,因為x > 0是張量,而不是布爾值。

要在 Keras 中執行條件語句,請使用keras.backend.switch

例如你的

if x > 0:
   return t1
else:
   return t2

會成為

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

嘗試類似的東西:

def newactivation(x):
    return tf.cond(x>0, x, x * tf.sigmoid(0.7* x))

x 不是 python 變量,它是一個張量,在模型運行時會保存一個值。 x 的值只有在評估該 op 時才知道,因此需要通過 TensorFlow(或 Keras)評估條件。

您可以評估張量,然后檢查條件

from keras.backend.tensorflow_backend import get_session


sess=get_session()
if sess.run(x)>0:
    return t1
else:
    return t2

get_session 不適用於 TensorFlow 2.0。 您可以在此處找到解決方案

靈感來自 ed Mar 21 '18 at 17:28 tomhosking 的先前答案。 這對我有用。 tf.cond

def custom_activation(x):
    return tf.cond(tf.greater(x, 0), lambda: ..., lambda: ....)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM