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

Posted

技术标签:

【中文标题】在 Keras 中使用自定义步骤激活函数会导致“\'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 中使用自定义步骤激活函数会导致“'tuple' object has no attribute '_keras_shape'”错误。如何解决这个问题? 【发布时间】:2021-05-16 10:01:04 【问题描述】:

我正在尝试在 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(编译(f.read(),文件名,'exec'),命名空间)

文件“/home/marlon/Área de Trabalho/omj_project/predicting_change.py”,第 85 行,在 模型 = 基线模型()

baseline_model 中的文件“/home/marlon/Área de Trabalho/omj_project/predicting_change.py”,第 80 行 model.add(密集(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'

感谢您的帮助。

【问题讨论】:

您的代码与其他问题中的代码略有不同,这些小细节很重要,例如您不能在激活中使用 numpy 函数,您应该提供使用此激活的代码。跨度> 您好,感谢您的评论。事实上,numpy 方法是一个错误,但它让我注意到另一个缺失的细节@tf.custom_gradient。现在它正在工作。 【参考方案1】:

你需要添加

@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

【讨论】:

正是它!谢谢! 我也删除了转换为 numpy.欢迎。

以上是关于在 Keras 中使用自定义步骤激活函数会导致“'tuple' object has no attribute '_keras_shape'”错误。如何解决这个问题?的主要内容,如果未能解决你的问题,请参考以下文章

如何使用 Keras 创建自定义激活函数?

如何为层中的每个节点为 Keras relu 函数分配自定义 alpha?

keras 自定义激活在某些条件下下降

Keras自定义Layer使用说明

如何强制 TensorFlow 在 float16 下运行?

使用 Keras 为损失函数构建自定义指标,但有错误