编码神经网络-Dropout

Dropout

Dropout是一种正则化技术。在每次迭代中,我们随机地关闭每个层上的一些神经元(单位),并不能在向前传播和反向传播中使用这些神经元。由于每个迭代中会被丢弃的单元是随机的,学习算法将不知道每个迭代中哪个神经元会被关闭;因此,强迫学习算法分散权重,而不是集中于某些特定的特征(单位)。此外,Dropout有助于提高泛化误差:

  • 由于我们在每次迭代中删除了一些单元,这将导致更小的网络,而这意味着更简单的网络(正则化)。

  • 可以看作是 bagging techniques的近似值。每次迭代都可以看作是不同的模型,因为我们在每个图层上随机放置不同的单元。这意味着错误将是来自所有不同模型(迭代)的错误的平均值。因此,平均来自不同模型的误差,特别是如果这些误差不相关将会减少整体误差。在错误完全相关的最坏情况下,所有模型之间的平均值根本无济于事; 然而,我们知道在实践中错误有一定程度的不相关性。结果,它总会改善泛化错误。

我们可以在每一层使用不同的概率; 然而,输出层总是有keep_prob = 1输入层,并且输入层有很高的keep_prob比如0.9或1.如果隐藏层有keep_prob = 0.8,这意味着; 在每次迭代中,每个单位都有80%的被包括概率和20%的被辍学概率。

因为我们有很多功能,而且数据量不是很多,所以在计算机视觉问题中使用了大量的Dropout。此外,彼此相邻的特征(像素)通常不会添加大量信息。因此,模型总是遭受过度拟合。

为了说明dropout如何帮助我们减少泛化错误,我们将使用之前发布的相同数据集。数据集包含猫和非猫的图像。我们将尝试构建一个神经网络来分类图像是否有猫。每个图像在RGB比例上都是64 x 64像素。让我们导入数据,看看形状以及训练集中猫图像的样本。

# Import training data

train_dataset = h5py.File("../data/train_catvnoncat.h5")

X_train = np.array(train_dataset["train_set_x"])

Y_train = np.array(train_dataset["train_set_y"])

# Plot a sample image

plt.imshow(X_train[50])

plt.axis("off");

# Import test data

test_dataset = h5py.File("../data/test_catvnoncat.h5")

X_test = np.array(test_dataset["test_set_x"])

Y_test = np.array(test_dataset["test_set_y"])

# Transform data

X_train = X_train.reshape(209, -1).T

X_train = X_train / 255

Y_train = Y_train.reshape(-1, 209)

X_test = X_test.reshape(50, -1).T

X_test = X_test / 255

Y_test = Y_test.reshape(-1, 50)

# print the new shape of both training and test datasets

print("Training data dimensions:")

print("X's dimension: {}, Y's dimension: {}".format(X_train.shape, Y_train.shape))

print("Test data dimensions:")

print("X's dimension: {}, Y's dimension: {}".format(X_test.shape, Y_test.shape))

Training data dimensions:

X's dimension: (12288, 209), Y's dimension: (1, 209)

Test data dimensions:

X's dimension: (12288, 50), Y's dimension: (1, 50)

编码神经网络-Dropout

图2:示例图像

现在,我们将编写在前向传播和后向传播中应用Dropout所需的函数。

def drop_out_matrices(layers_dims, m, keep_prob):

np.random.seed(1)

D = {}

L = len(layers_dims)

for l in range(L):

# initialize the random values for the dropout matrix

D[str(l)] = np.random.rand(layers_dims[l], m)

# Convert it to 0/1 to shut down neurons corresponding to each element

D[str(l)] = D[str(l)] < keep_prob[l]

assert(D[str(l)].shape == (layers_dims[l], m))

return D

def L_model_forward(

X, parameters, D, keep_prob, hidden_layers_activation_fn="relu"):

A = X # since input matrix A0

A = np.multiply(A, D[str(0)])

A /= keep_prob[0]

caches = [] # initialize the caches list

L = len(parameters) // 2 # number of layer in the network

for l in range(1, L):

A_prev = A

A, cache = linear_activation_forward(

A_prev, parameters["W" + str(l)], parameters["b" + str(l)],

hidden_layers_activation_fn)

# shut down some units

A = np.multiply(A, D[str(l)])

# scale that value of units to keep expected value the same

A /= keep_prob[l]

caches.append(cache)

AL, cache = linear_activation_forward(

A, parameters["W" + str(L)], parameters["b" + str(L)], "sigmoid")

AL = np.multiply(AL, D[str(L)])

AL /= keep_prob[L]

caches.append(cache)

assert(AL.shape == (1, X.shape[1]))

return AL, caches

def L_model_backward(

AL, Y, caches, D, keep_prob, hidden_layers_activation_fn="relu"):

Y = Y.reshape(AL.shape)

L = len(caches)

grads = {}

# dA for output layer

dAL = np.divide(AL - Y, np.multiply(AL, 1 - AL))

dAL = np.multiply(dAL, D[str(L)])

dAL /= keep_prob[L]

grads["dA" + str(L - 1)], grads["dW" + str(L)], grads[

"db" + str(L)] = linear_activation_backward(

dAL, caches[L - 1], "sigmoid")

grads["dA" + str(L - 1)] = np.multiply(

grads["dA" + str(L - 1)], D[str(L - 1)])

grads["dA" + str(L - 1)] /= keep_prob[L - 1]

for l in range(L - 1, 0, -1):

current_cache = caches[l - 1]

grads["dA" + str(l - 1)], grads["dW" + str(l)], grads[

"db" + str(l)] = linear_activation_backward(

grads["dA" + str(l)], current_cache,

hidden_layers_activation_fn)

grads["dA" + str(l - 1)] = np.multiply(

grads["dA" + str(l - 1)], D[str(l - 1)])

grads["dA" + str(l - 1)] /= keep_prob[l - 1]

return grads

def model_with_dropout(

X, Y, layers_dims, keep_prob, learning_rate=0.01, num_iterations=3000,

print_cost=True, hidden_layers_activation_fn="relu"):

# get number of examples

m = X.shape[1]

# to get consistents output

np.random.seed(1)

# initialize parameters

parameters = initialize_parameters(layers_dims)

# intialize cost list

cost_list = []

# implement gradient descent

for i in range(num_iterations):

# Initialize dropout matrices

D = drop_out_matrices(layers_dims, m, keep_prob)

# compute forward propagation

AL, caches = L_model_forward(

X, parameters, D, keep_prob, hidden_layers_activation_fn)

# compute regularized cost

cost = compute_cost(AL, Y)

# compute gradients

grads = L_model_backward(

AL, Y, caches, D, keep_prob, hidden_layers_activation_fn)

# update parameters

parameters = update_parameters(parameters, grads, learning_rate)

# print cost

if (i + 1) % 100 == 0 and print_cost:

print(f"The cost after {i + 1} iterations : {cost:.4f}.")

# append cost

if i % 100 == 0:

cost_list.append(cost)

# plot the cost curve

plt.plot(cost_list)

plt.xlabel("Iteration (per hundreds)")

plt.ylabel("Cost")

plt.title(f"Cost curve for the learning rate = {learning_rate}")

return parameters

最后,我们准备建立我们的神经网络。首先,我们将建立一个全连接的网络,而不会dropout。这就是说,keep_prob = 1。接下来,我们将在其中建立另一个网络keep_prob < 1。最后,我们将比较两个网络的泛化误差,并了解dropout技术如何帮助我们改进泛化误差。

# setup layers dimensions, number of examples, and keep probabilities list

m = X_train.shape[0]

keep_prob = [1, 1, 1, 1]

layers_dims = [m, 10, 10, 1]

# train NN with no dropout

parameters = model_with_dropout(X_train, Y_train, layers_dims, keep_prob=keep_prob, learning_rate=0.03, num_iterations=1000, hidden_layers_activation_fn="relu")

# print the test accuracy

print("The training accuracy rate: {}".format(accuracy(X_train, parameters, Y_train, "relu")[-7:]))

print("The test accuracy rate: {}".format(accuracy(X_test, parameters, Y_test, "relu")[-7:]))

The cost after 100 iterations : 0.6555.

The cost after 200 iterations : 0.6468.

The cost after 300 iterations : 0.6447.

The cost after 400 iterations : 0.6442.

The cost after 500 iterations : 0.6440.

The cost after 600 iterations : 0.6440.

The cost after 700 iterations : 0.6440.

The cost after 800 iterations : 0.6440.

The cost after 900 iterations : 0.6440.

The cost after 1000 iterations : 0.6440.

The training accuracy rate: 65.55%.

The test accuracy rate: 34.00%.

编码神经网络-Dropout

Figure 3: Cost curve with no dropout

# setup keep probabilities list

keep_prob = [1, 0.5, 0.5, 1]

# train NN with no dropout

parameters = model_with_dropout(X_train, Y_train, layers_dims, keep_prob=keep_prob, learning_rate=0.03, num_iterations=1000, hidden_layers_activation_fn="relu")

# print the test accuracy

print("The training accuracy rate: {}".format(accuracy(X_train, parameters, Y_train, "relu")[-7:]))

print("The test accuracy rate: {}".format(accuracy(X_test, parameters, Y_test, "relu")[-7:]))

The cost after 100 iterations : 0.6555.

The cost after 200 iterations : 0.6467.

The cost after 300 iterations : 0.6445.

The cost after 400 iterations : 0.6437.

The cost after 500 iterations : 0.6412.

The cost after 600 iterations : 0.6338.

The cost after 700 iterations : 0.6108.

The cost after 800 iterations : 0.5367.

The cost after 900 iterations : 0.4322.

The cost after 1000 iterations : 0.3114.

The training accuracy rate: 74.16%.

The test accuracy rate: 44.00%.

编码神经网络-Dropout

Figure 4: Cost curve with dropout

正如以上结果所显示的那样,出现dropout的网络在测试准确率上提高了30%。请注意,这只是一个说明性的例子,以显示dropout技术的有效性。在这个例子中我们选择了一个任意的概率。但是,我们可以调整每个图层上的丢失概率,以产生最佳验证损失和准确性。

结论

失落是一种非常有效的正则化技术,在卷积神经网络中被广泛使用。以下是一些要求:

  • keep_prob = 1使用梯度检查时设置; 否则,它将无法工作。

  • dropout仅在训练期间使用。测试/预测新示例时不要使用它。

  • 最低的keep_prob→简单的神经网络。随着keep_prob减少,偏差增加,方差减小。因此,具有更多神经元的层数预计会降低keep_prob以避免过度拟合。

  • 这在计算上是改善泛化误差并帮助解决过拟合的廉价方法。

  • 人们可以调整keep_prob以从手头的任务中获得最佳结果。