簡體   English   中英

在 Keras 中使用自定義步驟激活 function 會導致“'tuple' object has no attribute '_keras_shape'”錯誤。 如何解決這個問題?

[英]Using a custom step activation function in Keras results in “'tuple' object has no attribute '_keras_shape'” error. How to resolve this?

我正在嘗試在 Keras Z20F35E630DAF49DBFACZ368853 的 output 層中實現二進制自定義激活 function。

這是我的試驗:

def binary_activation(x):
    ones = tf.ones(tf.shape(x), dtype=x.dtype.base_dtype)
    zeros = tf.zeros(tf.shape(x), dtype=x.dtype.base_dtype)
    def grad(dy):
        return dy
    return switch(x > 0.5, ones, zeros), grad

此處類似。 但我得到以下錯誤:

文件“/usr/local/lib/python3.6/dist-packages/spyder_kernels/customize/spydercustomize.py”,第 786 行,運行文件 execfile(文件名,命名空間)

文件“/usr/local/lib/python3.6/dist-packages/spyder_kernels/customize/spydercustomize.py”,第 110 行,在 execfile exec(compile(f.read(), filename, 'exec'), namespace)

文件“/home/marlon/Área de Trabalho/omj_project/predicting_change.py”,第 85 行,model = baseline_model()

文件“/home/marlon/Área de Trabalho/omj_project/predicting_change.py”,第 80 行,baseline_model model.add(Dense(1, activation=binary_activation))

文件“/usr/local/lib/python3.6/dist-packages/keras/engine/sequential.py”,第 181 行,添加 output_tensor = layer(self.outputs[0])

文件“/usr/local/lib/python3.6/dist-packages/keras/engine/base_layer.py”,第 497 行,調用參數=user_kwargs)

文件“/usr/local/lib/python3.6/dist-packages/keras/engine/base_layer.py”,第 565 行,在 _add_inbound_node output_tensors[i]._keras_shape = output_shapes[i]

AttributeError: 'tuple' object 沒有屬性 '_keras_shape'

謝謝你的幫助。

你需要添加

@tf.custom_gradient

在您的代碼之上,就像您提到的其他評論一樣。

@tf.custom_gradient
def binary_activation(x):
    ones = tf.ones(tf.shape(x), dtype=x.dtype.base_dtype)
    
    zeros = tf.zeros(tf.shape(x), dtype=x.dtype.base_dtype)
    res = tf.keras.backend.switch(x > 0.5, ones, zeros)
    def grad(dy):
        return dy
    return res, grad

暫無
暫無

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

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