LeakyReLU 层如何在不设置单元数的情况下工作?

问题描述

在构建 Sequential 模型时,我注意到添加 relu 层和 LeakyReLU 层之间存在差异。

test = Sequential()
test.add(Dense(1024,activation="relu"))
test.add(LeakyReLU(0.2))
  1. 为什么我们不能添加带有 activation = "LeakyReLU" 的层? (LeakyReLU 不是 keras 可以使用的字符串)
  2. 添加 relu 层时,我们设置单位数(在我的示例中为 1024) 为什么我们不能对 LeakyReLU 做同样的事情?

我确信 reluLeakyReLU 之间的区别在于方法行为,但似乎不止于此。

解决方法

  1. 我们可以通过使用别名 activation='relu' 来指定密集层本身的激活函数,这将使用默认的 keras 参数进行 relu。对于 LeakyRelu 激活函数,keras 中没有这样的别名可用。我们必须使用 tf.keras.layers.LeakyRelutf.nn.leaky_relu

  2. 我们无法在 Relu 层中设置单元数,它只是采用前一个输出张量并对其应用 relu 激活函数。您已为 Dense 层而不是 relu 层指定了单位数。当我们指定 Dense(1024,activation="relu") 时,我们将输入与权重相乘,添加偏差并在输出上应用 relu 函数(所有这些都在一行中提到)。从第 1 步中提到的方法来看,这个过程分 2 个阶段完成,首先是权重相乘、偏置相加,然后是应用 LeakyRelu 激活函数(在 2 行中提到)。

,
    import tensorflow as tf
    test = Sequential()
    test.add(Dense(1024,input_dim=784,activation="relu",name="First"))
    test.add(Dense(512,activation=tf.keras.layers.LeakyReLU(alpha=0.01),name="middle"))
    test.add(Dense(1,activation='sigmoid',name="Last"))
    test.compile(loss='binary_crossentropy',optimizer="adam")
    print(test.summary())

输出:

Model: "sequential"
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
First (Dense)                (None,1024)              803840    
_________________________________________________________________
middle (Dense)               (None,512)               524800    
_________________________________________________________________
Last (Dense)                 (None,1)                 513       
=================================================================

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...