你是正确的,在推理过程中也会应用 MC Dropout,这与常规 dropout 不同。如果你用谷歌搜索,你可以很容易地找到关于这两者的大量信息。
关于 channel-wise dropout,我的理解是它不会丢弃特定的神经元,而是丢弃整个通道。
现在在 Keras 中实现(我将使用tf.keras)。
MC 辍学
像往常一样,Keras 定义了一个自定义层,无论是训练还是测试都应用 dropout,因此我们可以使用 tf.nn.dropout() 并保持恒定的 dropout 率:
import tensorflow as tf
class MCDropout(tf.keras.layers.Layer):
def __init__(self, rate):
super(MCDropout, self).__init__()
self.rate = rate
def call(self, inputs):
return tf.nn.dropout(inputs, rate=self.rate)
使用示例:
import tensorflow as tf
import numpy as np
model = tf.keras.models.Sequential()
model.add(tf.keras.layers.Conv2D(filters=6, kernel_size=3))
model.add(MCDropout(rate=0.5))
model.add(tf.keras.layers.Flatten())
model.add(tf.keras.layers.Dense(2))
model.compile(optimizer=tf.keras.optimizers.SGD(0.001),
loss='binary_crossentropy',
metrics=['accuracy'])
# generate dummy data for illustration
x_train = np.random.normal(size=(10, 4, 4, 3))
x_train = np.vstack([x_train, 2*np.random.normal(size=(10, 4, 4, 3))])
y_train = [[1, 0] for _ in range(10)] + [[0, 1] for _ in range(10)]
y_train = np.array(y_train)
model.fit(x_train,
y_train,
epochs=2,
batch_size=10,
validation_data=(x_train, y_train))
渠道明智的辍学
在这里您可以使用相同的tf.nn.dropout() 函数,但是,您必须指定噪声形状。 tf.nn.dropout() 的 documentation 给出了如何实现丢弃通道的确切示例:
shape(x) = [k, l, m, n] 和noise_shape = [k, 1, 1, n],每个batch和channel组件将独立保存,每一行和每一列将保留或不保留在一起。
这就是我们要在call() 方法中做的事情:
class ChannelWiseDropout(tf.keras.layers.Layer):
def __init__(self, rate):
super(ChannelWiseDropout, self).__init__()
self.rate = rate
def call(self, inputs):
shape = tf.keras.backend.shape(inputs)
noise_shape = (shape[0], 1, 1, shape[-1])
return tf.nn.dropout(inputs,
rate=self.rate,
noise_shape=noise_shape)
将其应用于一些示例:
model = tf.keras.models.Sequential()
model.add(tf.keras.layers.InputLayer(input_shape=(4, 4, 3)))
model.add(tf.keras.layers.Conv2D(filters=3, kernel_size=3))
model.add(ChannelWiseDropout(rate=0.5))
x_train = np.random.normal(size=(1, 4, 4, 3))
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
res = sess.run(model.output, feed_dict={model.inputs[0]:x_train})
print(res[:, :, :, 0])
print(res[:, :, :, 1])
print(res[:, :, :, 2])
# [[[2.5495746 1.3060737 ]
# [0.47009617 1.0427766 ]]]
# [[[-0. 0.]
# [-0. -0.]]] <-- second and third channels were dropped
# [[[-0. -0.]
# [-0. -0.]]]
注意
我正在使用tf.__version__ == '1.13.1'。旧版本的 tf 使用 keep_prob = 1 - rate 而不是 rate 参数。