具有 cRelu 激活的 Keras 顺序模型
Keras Sequential model with cRelu activation
我在创建激活函数为 cRelu 的 3 层密集模型时遇到问题。
cRelu 连接两个 relu(一个负数和一个正数)并在其输出中创建一个两倍大小的张量。
当试图在它之后添加另一层时,我总是得到一个大小不匹配的错误
model = Sequential()
model.add(Dense(N, input_dim=K, activation=crelu))
model.add(Dense(N//2, activation=crelu))
我如何告诉下一层期望 2N 输入和 N?
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())
我在创建激活函数为 cRelu 的 3 层密集模型时遇到问题。 cRelu 连接两个 relu(一个负数和一个正数)并在其输出中创建一个两倍大小的张量。 当试图在它之后添加另一层时,我总是得到一个大小不匹配的错误
model = Sequential()
model.add(Dense(N, input_dim=K, activation=crelu))
model.add(Dense(N//2, activation=crelu))
我如何告诉下一层期望 2N 输入和 N?
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())