15 - Dropout的原理及其在TF/PyTorch/Numpy的源码实现

1. 作用

在训练模式下,dropout层指的是在对全连接层中的数据进行指定概率p对神经元的权重置零;从而使得在每个批次中的数据不一致,这样可以简单的看作是很多个不同的模型进行训练,从而得到更鲁棒性的权重,达到多模型融合作用,提高模型的泛化性,降低模型的过拟合率;
在这里插入图片描述

1.2 公式

h ′ = { 0 p h 1 − p o t h e r s h'=\left\{ \begin{aligned} 0&&p\\ \frac{h}{1-p}& & others \\ \end{aligned} \right. h=01phpothers
注: 由上述公式可以看出,我们需要分两步完成dropout:
(1)以概率p来对当前层权重置0
(2)将剩余的权重值乘以 1 / ( 1 − p ) 1/(1-p) 1/(1p)

那我们为什么需要将剩余的值乘以 1 / ( 1 − p ) 1/(1-p) 1/(1p)?为了保证样本的期望
E ( h ′ ) = 0 × p + h 1 − p × ( 1 − p ) = h ′ E(h')=0\times p+\frac{h}{1-p}\times (1-p)=h' E(h)=0×p+1ph×(1p)=h

import torch

# define dropout function
def dropout_test(x, dropout):
	"""

	:param x: input tensor
	:param dropout: probability for dropout
	:return: a tensor with masked by dropout
	"""
	# dropout must be between 0 and 1
	assert 0 <= dropout <= 1
	# if dropout is equal to 0;just return self_x
	if dropout == 0:
		return x
	# if dropout is equal to 1: put all values to zeros in tensor x
	if dropout == 1:
		return torch.zeros_like(x)
	# torch.rand is for return a tensor filled with values from uniform distribution [0,1)
	# we compare the values with dropout,if values is greater than dropout ,return 1,else 0
	mask = (torch.rand(x.shape) > dropout).float()
	# mask times
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值