【问题标题】:Dropout layer after embedding layer嵌入层后的dropout层
【发布时间】:2020-12-10 09:12:10
【问题描述】:
model = tf.keras.Sequential([
    tf.keras.layers.Embedding(1000, 16, input_length=20), 
    tf.keras.layers.Dropout(0.2),                           # <- How does the dropout work?
    tf.keras.layers.Conv1D(64, 5, activation='relu'),
    tf.keras.layers.MaxPooling1D(pool_size=4),
    tf.keras.layers.LSTM(64),
    tf.keras.layers.Dense(1, activation='sigmoid')
])

我可以理解 Dense 层之间何时应用 dropout,它会随机丢弃并阻止前一层神经元更新参数。我不明白 Embedding layer 之后 dropout 是如何工作的。

假设Embedding layer 的输出形状是(batch_size,20,16),或者如果我们忽略批量大小,则只是(20,16)。 dropout 如何应用于嵌入层的输出?

随机删除行或列?

【问题讨论】:

    标签: tensorflow nlp lstm recurrent-neural-network word-embedding


    【解决方案1】:

    dropout 层会丢弃前一层的输出。
    它将随机强制先前的输出为 0。
    在您的情况下,嵌入层的输出将是 3d 张量 (size, 20, 16)

    import tensorflow as tf
    import numpy as np
    tf.random.set_seed(0)
    layer = tf.keras.layers.Dropout(0.5)
    data = np.arange(1,37).reshape(3, 3, 4).astype(np.float32)
    data
    

    输出

    array([[[ 1.,  2.,  3.,  4.],
            [ 5.,  6.,  7.,  8.],
            [ 9., 10., 11., 12.]],
    
           [[13., 14., 15., 16.],
            [17., 18., 19., 20.],
            [21., 22., 23., 24.]],
    
           [[25., 26., 27., 28.],
            [29., 30., 31., 32.],
            [33., 34., 35., 36.]]], dtype=float32)
    

    代码:

    outputs = layer(data, training=True)
    outputs
    

    输出:

    <tf.Tensor: shape=(3, 3, 4), dtype=float32, numpy=
    array([[[ 0.,  0.,  6.,  8.],
            [ 0., 12.,  0., 16.],
            [18.,  0., 22., 24.]],
    
           [[26.,  0.,  0., 32.],
            [34., 36., 38.,  0.],
            [ 0.,  0., 46., 48.]],
    
           [[50., 52., 54.,  0.],
            [ 0., 60.,  0.,  0.],
            [ 0.,  0.,  0., 72.]]], dtype=float32)>
    

    您应该考虑的一种方法是 SpatialDropout1d,它实际上会删除整个列。

    layer = tf.keras.layers.SpatialDropout1D(0.5)
    outputs = layer(data, training=True)
    

    输出:

    <tf.Tensor: shape=(3, 3, 4), dtype=float32, numpy=
    array([[[ 2.,  0.,  6.,  8.],
            [10.,  0., 14., 16.],
            [18.,  0., 22., 24.]],
    
           [[26., 28.,  0., 32.],
            [34., 36.,  0., 40.],
            [42., 44.,  0., 48.]],
    
           [[ 0.,  0., 54., 56.],
            [ 0.,  0., 62., 64.],
            [ 0.,  0., 70., 72.]]], dtype=float32)>
    

    我希望这能消除你的困惑。

    【讨论】:

    • 谢谢。我发现将嵌入层输出想象为神经元并不直观。在这种情况下,dropout之前有多少个神经元?
    • 如果解决方案有效,您能否接受并投票。
    猜你喜欢
    • 2018-02-25
    • 2022-01-10
    • 1970-01-01
    • 1970-01-01
    • 2019-08-09
    • 1970-01-01
    • 2018-05-21
    • 1970-01-01
    • 2017-11-21
    相关资源
    最近更新 更多