首页 > 解决方案 > 具有 cRelu 激活的 Keras 序列模型

问题描述

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

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

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

标签: kerassequential

解决方案


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())

推荐阅读