如何解决Tensorflow中的辍学层会影响哪些层?
请考虑进行迁移学习,以便在keras / tensorflow中使用预训练的模型。对于每个旧层,将trained
参数设置为false
,以便在训练期间不会更新其权重,而最后一层已被新层替换,因此必须对其进行训练。特别是添加了两个完全连接的具有512
和1024
神经元以及relu激活功能的隐藏层。在这些层之后,Dropout层与rate
0.2
一起使用。这意味着在训练的每个时期,20%
个神经元都会被随机丢弃。
此辍学层影响哪些层?它会影响包括已设置layer.trainable=false
的预训练层在内的所有网络,还是仅影响新添加的层?还是只影响前一层(即具有1024
个神经元的那一层)?
换句话说,在每个时期,由于辍学而关闭的神经元属于哪一层?
import os
from tensorflow.keras import layers
from tensorflow.keras import Model
from tensorflow.keras.applications.inception_v3 import InceptionV3
local_weights_file = 'weights.h5'
pre_trained_model = InceptionV3(input_shape = (150,150,3),include_top = False,weights = None)
pre_trained_model.load_weights(local_weights_file)
for layer in pre_trained_model.layers:
layer.trainable = False
# pre_trained_model.summary()
last_layer = pre_trained_model.get_layer('mixed7')
last_output = last_layer.output
# Flatten the output layer to 1 dimension
x = layers.Flatten()(last_output)
# Add two fully connected layers with 512 and 1,024 hidden units and ReLU activation
x = layers.Dense(512,activation='relu')(x)
x = layers.Dense(1024,activation='relu')(x)
# Add a dropout rate of 0.2
x = layers.Dropout(0.2)(x)
# Add a final sigmoid layer for classification
x = layers.Dense (1,activation='sigmoid')(x)
model = Model( pre_trained_model.input,x)
model.compile(optimizer = RMSprop(lr=0.0001),loss = 'binary_crossentropy',metrics = ['accuracy'])
解决方法
辍学层将影响上一层的输出。
如果我们查看您代码的特定部分:
x = layers.Dense(1024,activation='relu')(x)
# Add a dropout rate of 0.2
x = layers.Dropout(0.2)(x)
# Add a final sigmoid layer for classification
x = layers.Dense (1,activation='sigmoid')(x)
在您的情况下,x = layers.Dense(1024,activation='relu')(x)
定义的层的输出的20%将被随机丢弃,然后传递到最后的Dense
层。
仅上一个层的神经元被“关闭”,但所有层在反向传播方面均“受影响”。
- 较新的图层:Dropout的输出被输入到下一层,因此下一图层的输出将发生变化,next-next的输出也会发生变化,等等。
- 先前的图层:随着pre-Dropout图层的“有效输出”发生变化,渐变也会随之变化,因此也会出现任何后续渐变。在
Dropout(rate=1)
的极端情况下,零梯度会流动。
此外,请注意,仅当输入到Dense为2D (batch_size,features)
时,才会丢弃整个神经元; Dropout对所有维度应用随机的统一蒙版(相当于在2D情况下丢弃整个神经元)。要丢弃整个神经元,请设置Dropout(.2,noise_shape=(batch_size,1,features))
(3D情况)。要在所有样本中放置相同个神经元,请使用noise_shape=(1,features)
(或将(1,features)
用于2D)。
Dropout技术并不是在神经网络的每个层上实现的;通常会在网络中最后几层的神经元内发挥作用。
该技术通过随机减少神经网络中相互连接的神经元的数量而起作用。在每个训练步骤中,每个神经元都有被遗弃的机会,或者说可能会从连接的神经元的归纳贡献中消失
关于是否应该在激活功能之前或之后放置辍学有一些争论。根据经验,对于除relu
以外的所有激活功能,都将其放置在激活功能之后。
您可以在每个隐藏层之后添加dropout
,通常它只影响上一层(您的情况将影响(x = layers.Dense(1024,activation='relu')(x) )
)。在最初的提出丢包层的论文中,通过Hinton (2012),在输出之前,在每个完全连接的(密集)层上都使用了丢包(p = 0.5)。卷积层上没有使用它。这成为最常用的配置。
我正在添加可能对您有帮助的资源链接:
https://towardsdatascience.com/dropout-on-convolutional-layers-is-weird-5c6ab14f19b2
https://towardsdatascience.com/machine-learning-part-20-dropout-keras-layers-explained-8c9f6dc4c9ab
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。