【问题标题】:Keras Sequential model with cRelu activation具有 cRelu 激活的 Keras 序列模型
【发布时间】:2019-08-05 06:10:32
【问题描述】:

我在创建具有 3 层且激活函数为 cRelu 的 Dense 模型时遇到问题。 cRelu 连接两个 relu(一个负数和一个正数)并在其输出中创建一个两倍大小的张量。 尝试在其后添加另一层时,总是出现大小不匹配错误

model  = Sequential()
model.add(Dense(N, input_dim=K, activation=crelu))
model.add(Dense(N//2, activation=crelu))

我如何告诉下一层期望 2N 输入和 N?

【问题讨论】:

  • 你得到了什么确切的错误?
  • ValueError: 尺寸必须相等,但对于输入形状为 [?,500]、[250,83] 的“dense_2/MatMul”(操作:“MatMul”),尺寸必须是 500 和 250。
  • 您的 crelu 是如何实现的?我认为这就是问题所在,它应该是一个层,因此形状推断有效。

标签: keras sequential


【解决方案1】:

Keras 不希望激活函数改变输出形状。如果你想改变它,你应该将 crelu 功能包装在一个层中并指定相应的输出形状:

import tensorflow as tf
from keras.layers import Layer

class cRelu(Layer):

    def __init__(self, **kwargs):
        super(cRelu, self).__init__(**kwargs)

    def build(self, input_shape):
        super(cRelu, self).build(input_shape)

    def call(self, x):
        return tf.nn.crelu(x)

    def compute_output_shape(self, input_shape):
        """
        All axis of output_shape, except the last one,
        coincide with the input shape.
        The last one is twice the size of the corresponding input 
        as it's the axis along which the two relu get concatenated.
        """
        return (*input_shape[:-1], input_shape[-1]*2)

那么你可以如下使用它

model  = Sequential()
model.add(Dense(N, input_dim=K))
model.add(cRelu())
model.add(Dense(N//2))
model.add(cRelu())

【讨论】:

  • 谢谢!你能解释一下 compute_output_shape 方法中返回的形状吗?好像很奇怪
  • 是的!和返回元组中第一个元素之前的星号?是笔误吗?
  • 这根本不是错字。这是 Python 解包运算符:docs.python.org/3/tutorial/…
  • @Amirfel 如果您认为这个答案是正确的,我建议您考虑批准它,这样任何面临类似问题的人都可以很容易地看到这个问题可以通过这个答案来解决。如果您认为问题没有解决,请给予相应的反馈
猜你喜欢
  • 2017-08-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多