在 Keras 中使用自定义步骤激活函数会导致“'tuple' object has no attribute '_keras_shape'”错误如何解决这个问题?

问题描述

我正在尝试在 Keras 模型的输出层中实现一个二进制自定义激活函数

这是我的试验:

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

类似于here。 但我收到以下错误

文件“/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 行,在 模型 = 基线模型()

文件“/home/marlon/Área de Trabalho/omj_project/predicting_change.py”,第 80 行,在基线模型中 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' 对象没有属性 '_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