【问题标题】:Adding Dropout to testing/inference phase将 Dropout 添加到测试/推理阶段
【发布时间】:2019-03-16 07:30:51
【问题描述】:

我已经在 Keras 中为一些时间序列训练了以下模型:

    input_layer = Input(batch_shape=(56, 3864))
    first_layer = Dense(24, input_dim=28, activation='relu',
                        activity_regularizer=None,
                        kernel_regularizer=None)(input_layer)
    first_layer = Dropout(0.3)(first_layer)
    second_layer = Dense(12, activation='relu')(first_layer)
    second_layer = Dropout(0.3)(second_layer)
    out = Dense(56)(second_layer)
    model_1 = Model(input_layer, out)

然后我用model_1 的训练层定义了一个新模型,并添加了具有不同速率的dropout 层drp

    input_2 = Input(batch_shape=(56, 3864))
    first_dense_layer = model_1.layers[1](input_2)
    first_dropout_layer = model_1.layers[2](first_dense_layer)
    new_dropout = Dropout(drp)(first_dropout_layer)
    snd_dense_layer = model_1.layers[3](new_dropout)
    snd_dropout_layer = model_1.layers[4](snd_dense_layer)
    new_dropout_2 = Dropout(drp)(snd_dropout_layer)
    output = model_1.layers[5](new_dropout_2)
    model_2 = Model(input_2, output)

然后我得到这两个模型的预测结果如下:

result_1 = model_1.predict(test_data, batch_size=56)
result_2 = model_2.predict(test_data, batch_size=56)

我期望得到完全不同的结果,因为第二个模型有新的 dropout 层,而且这两个模型是不同的 (IMO),但事实并非如此。两者都产生相同的结果。为什么会这样?

【问题讨论】:

  • 您应该告诉我们您正在使用哪个框架。是 Keras 吗?
  • @JérémyBlain 是的 Keras(更新问题)
  • @Birish Dropout 层仅在训练阶段有效。在推理阶段它被关闭。
  • @today 说得好!谢谢!那么如何在测试中添加 dropout 呢?有什么想法吗?

标签: python neural-network keras deep-learning dropout


【解决方案1】:

正如我在 cmets 中提到的,Dropout 层在推理阶段(即测试模式)是关闭的,所以当您使用 model.predict() 时,Dropout 层是不活动的。但是,如果您希望模型在训练和推理阶段都使用Dropout,则可以在调用时传递training 参数as suggested by François Chollet

# ...
new_dropout = Dropout(drp)(first_dropout_layer, training=True)
# ...

或者,如果您已经训练了模型并且现在想要在推理模式下使用它并保持Dropout 层(以及可能在训练/推理阶段具有不同行为的其他层,例如BatchNormalization)处于活动状态,您可以定义一个接受模型输入以及 Keras 学习阶段的后端函数:

from keras import backend as K

func = K.function(model.inputs + [K.learning_phase()], model.outputs)

# to use it pass 1 to set the learning phase to training mode
outputs = func([input_arrays] + [1.]) 

【讨论】:

    猜你喜欢
    • 2017-10-08
    • 1970-01-01
    • 2020-05-10
    • 2019-09-06
    • 2020-07-03
    • 1970-01-01
    • 2017-09-19
    • 1970-01-01
    • 2019-03-11
    相关资源
    最近更新 更多