【转载】 深度学习总结:用pytorch做dropout和Batch Normalization时需要注意的地方,用tensorflow做dropout和BN时需要注意的地方,
原文地址:
https://blog.csdn.net/weixin_40759186/article/details/87547795
---------------------------------------------------------------------------------------------------------------
用pytorch做dropout和BN时需要注意的地方
pytorch做dropout:
就是train的时候使用dropout,训练的时候不使用dropout,
pytorch里面是通过net.eval()固定整个网络参数,包括不会更新一些前向的参数,没有dropout,BN参数固定,理论上对所有的validation set都要使用net.eval()
net.train()表示会纳入梯度的计算。
net_dropped = torch.nn.Sequential(
torch.nn.Linear(1, N_HIDDEN),
torch.nn.Dropout(0.5), # drop 50% of the neuron
torch.nn.ReLU(),
torch.nn.Linear(N_HIDDEN, N_HIDDEN),
torch.nn.Dropout(0.5), # drop 50% of the neuron
torch.nn.ReLU(),
torch.nn.Linear(N_HIDDEN, 1),
)
for t in range(500):
pred_drop = net_dropped(x)
loss_drop = loss_func(pred_drop, y) optimizer_drop.zero_grad()
loss_drop.backward()
optimizer_drop.step() if t % 10 == 0:
# change to eval mode in order to fix drop out effect
net_dropped.eval() # parameters for dropout differ from train mode test_pred_drop = net_dropped(test_x) # change back to train mode
net_dropped.train()
pytorch做Batch Normalization:
net.eval()固定整个网络参数,固定BN的参数,moving_mean 和moving_var,不懂这个看下图:
if self.do_bn:
bn = nn.BatchNorm1d(10, momentum=0.5)
setattr(self, 'bn%i' % i, bn) # IMPORTANT set layer to the Module
self.bns.append(bn) for epoch in range(EPOCH):
print('Epoch: ', epoch)
for net, l in zip(nets, losses):
net.eval() # set eval mode to fix moving_mean and moving_var
pred, layer_input, pre_act = net(test_x) net.train() # free moving_mean and moving_var
plot_histogram(*layer_inputs, *pre_acts)
moving_mean 和 moving_var

用tensorflow做dropout和BN时需要注意的地方
dropout和BN都有一个training的参数表明到底是train还是test, 表明test那dropout就是不dropout,BN就是固定住了BN的参数;
tf_is_training = tf.placeholder(tf.bool, None) # to control dropout when training and testing # dropout net
d1 = tf.layers.dense(tf_x, N_HIDDEN, tf.nn.relu)
d1 = tf.layers.dropout(d1, rate=0.5, training=tf_is_training) # drop out 50% of inputs
d2 = tf.layers.dense(d1, N_HIDDEN, tf.nn.relu)
d2 = tf.layers.dropout(d2, rate=0.5, training=tf_is_training) # drop out 50% of inputs
d_out = tf.layers.dense(d2, 1) for t in range(500):
sess.run([o_train, d_train], {tf_x: x, tf_y: y, tf_is_training: True}) # train, set is_training=True if t % 10 == 0:
# plotting
plt.cla()
o_loss_, d_loss_, o_out_, d_out_ = sess.run(
[o_loss, d_loss, o_out, d_out], {tf_x: test_x, tf_y: test_y, tf_is_training: False} # test, set is_training=False
)
def add_layer(self, x, out_size, ac=None):
x = tf.layers.dense(x, out_size, kernel_initializer=self.w_init, bias_initializer=B_INIT)
self.pre_activation.append(x)
# the momentum plays important rule. the default 0.99 is too high in this case!
if self.is_bn: x = tf.layers.batch_normalization(x, momentum=0.4, training=tf_is_train) # when have BN
out = x if ac is None else ac(x)
return out
当BN的training的参数为train时,只是表示BN的参数是可变化的,并不是代表BN会自己更新moving_mean 和moving_var,因为这个操作是前向更新的op,在做train之前必须确保moving_mean 和moving_var更新了,更新moving_mean 和moving_var的操作在tf.GraphKeys.UPDATE_OPS
# !! IMPORTANT !! the moving_mean and moving_variance need to be updated,
# pass the update_ops with control_dependencies to the train_op
update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)
with tf.control_dependencies(update_ops):
self.train = tf.train.AdamOptimizer(LR).minimize(self.loss)
【转载】 深度学习总结:用pytorch做dropout和Batch Normalization时需要注意的地方,用tensorflow做dropout和BN时需要注意的地方,的更多相关文章
- 深度学习面试题21:批量归一化(Batch Normalization,BN)
目录 BN的由来 BN的作用 BN的操作阶段 BN的操作流程 BN可以防止梯度消失吗 为什么归一化后还要放缩和平移 BN在GoogLeNet中的应用 参考资料 BN的由来 BN是由Google于201 ...
- Hinton“深度学习之父”和“神经网络先驱”,新论文Capsule将推翻自己积累了30年的学术成果时
Hinton“深度学习之父”和“神经网络先驱”,新论文Capsule将推翻自己积累了30年的学术成果时 在论文中,Capsule被Hinton大神定义为这样一组神经元:其活动向量所表示的是特定实体类型 ...
- 深度学习基础系列(九)| Dropout VS Batch Normalization? 是时候放弃Dropout了
Dropout是过去几年非常流行的正则化技术,可有效防止过拟合的发生.但从深度学习的发展趋势看,Batch Normalizaton(简称BN)正在逐步取代Dropout技术,特别是在卷积层.本文将首 ...
- windows10环境下安装深度学习环境anaconda+pytorch+CUDA+cuDDN
步骤零:安装anaconda.opencv.pytorch(这些不详细说明).复制运行代码,如果没有报错,说明已经可以了.不过大概率不行,我的会报错提示AssertionError: Torch no ...
- 常用深度学习框架(keras,pytorch.cntk,theano)conda 安装--未整理
版本查询 cpu tensorflow conda env list source activate tensorflow python import tensorflow as tf 和 tf.__ ...
- 深度学习之入门Pytorch(1)------基础
目录: Pytorch数据类型:Tensor与Storage 创建张量 tensor与numpy数组之间的转换 索引.连接.切片等 Tensor操作[add,数学运算,转置等] GPU加速 自动求导: ...
- 【深度学习】基于Pytorch的ResNet实现
目录 1. ResNet理论 2. pytorch实现 2.1 基础卷积 2.2 模块 2.3 使用ResNet模块进行迁移学习 1. ResNet理论 论文:https://arxiv.org/pd ...
- 动手学深度学习11- 多层感知机pytorch简洁实现
多层感知机的简洁实现 定义模型 读取数据并训练数据 损失函数 定义优化算法 小结 多层感知机的简洁实现 import torch from torch import nn from torch.nn ...
- 动手学深度学习8-softmax分类pytorch简洁实现
定义和初始化模型 softamx和交叉熵损失函数 定义优化算法 训练模型 import torch from torch import nn from torch.nn import init imp ...
随机推荐
- 在ubuntu14中搭建邮箱服务器
1.前提准备 1.1在服务器上安装ubuntu14 1.2为ubuntu14配置静态ip 使用命令 sudo vim /etc/network/interfaces打开配置文件 修改内容如下: 使用命 ...
- 洛谷U36590搬书
题目背景 陈老师喜欢网购书籍,经常一次购它个百八十本,然后拿来倒卖,牟取暴利.前些天,高一的新同学来了,他便像往常一样,兜售他的书,经过一番口舌,同学们决定买他的书,但是陈老师桌上的书有三堆,每一堆都 ...
- Java文档注释导出帮助文档和项目的jar包导入和导出。
1.1 文档注释导出帮助文档 在eclipse使用时,可以配合文档注释,导出对类的说明文档,从而供其他人阅读学习与使用. 通过使用文档注释,将类或者方法进行注释用@简单标注基本信息.如@au ...
- SpringBoot添加webapp目录
一.文章简述 使用IDEA工具创建的SpringBoot项目本身是没有webapp目录的.如果我们想要添加webapp目录的话,可以手动添加. 二.操作步骤 1)点击IDEA右上角的Project S ...
- 字符串和数组----string
一.初始化string对象的方式 #include <iostream> #include <string> using std::cout; using std::endl; ...
- latex 公式距离
\setlength{\abovedisplayshortskip}{0cm} 公式和文本之间的间距 \setlength{\belowdisplayshortskip}{0cm} \setlengt ...
- 求1+2+……+n的和
题目描述 求1+2+3+...+n,要求不能使用乘除法.for.while.if.else.switch.case等关键字及条件判断语句(A?B:C). class Solution { public ...
- RabbitMQ 循环调度
循环调度是针对Consumer消费者来说的.如果有多个Consumer订阅同一个队列的消息,RabbitMQ会自动按照顺序将消息发送到每一个Consumer手中. 就是这么简单!
- relativeURL 相对URL的坑
我正在尝试实现一个使用RestKit的iOS应用程序.在我迄今为止看到的所有示例中,以下代码用于创建URL: NSURL *baseURL = [NSURL URLWithString:@" ...
- python安装与初始
第一天学习中了解到python是高级语言,和java.PHP性质相同,而c语言.汇编属于低级语言,而高级语言与低级语言的区别,很重要的一点在于内存的处理上,低级语言在调用内存时需要自己编程来控制程序内 ...