温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Pytorch nn.Dropout怎么使用

发布时间:2023-04-08 16:58:38 来源:亿速云 阅读:261 作者:iii 栏目:开发技术

这篇文章主要介绍“Pytorch nn.Dropout怎么使用”,在日常操作中,相信很多人在Pytorch nn.Dropout怎么使用问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”Pytorch nn.Dropout怎么使用”的疑惑有所帮助!接下来,请跟着小编一起来学习吧!

1.nn.Dropout用法一

一句话总结:Dropout的是为了防止过拟合而设置

详解部分:
1.Dropout是为了防止过拟合而设置的
2.Dropout顾名思义有丢掉的意思
3.nn.Dropout(p = 0.3) # 表示每个神经元有0.3的可能性不被激活
4.Dropout只能用在训练部分而不能用在测试部分
5.Dropout一般用在全连接神经网络映射层之后,如代码的nn.Linear(20, 30)之后

Pytorch nn.Dropout怎么使用

代码部分:

class Dropout(nn.Module):
	def __init__(self):
		super(Dropout, self).__init__()
		self.linear = nn.Linear(20, 40)
		self.dropout = nn.Dropout(p = 0.3) # p=0.3表示下图(a)中的神经元有p = 0.3的概率不被激活

	def forward(self, inputs):
		out = self.linear(inputs)
		out = self.dropout(out)
		return out

net = Dropout()
# Dropout只能用在train而不能用在test	

2.nn.Dropout用法二

以代码为例

import torch
import torch.nn as nn
a = torch.randn(4, 4)
print(a)
"""
tensor([[ 1.2615, -0.6423, -0.4142,  1.2982],
        [ 0.2615,  1.3260, -1.1333, -1.6835],
        [ 0.0370, -1.0904,  0.5964, -0.1530],
        [ 1.1799, -0.3718,  1.7287, -1.5651]])
"""
dropout = nn.Dropout()
b = dropout(a)
print(b)
"""
tensor([[ 2.5230, -0.0000, -0.0000,  2.5964],
        [ 0.0000,  0.0000, -0.0000, -0.0000],
        [ 0.0000, -0.0000,  1.1928, -0.3060],
        [ 0.0000, -0.7436,  0.0000, -3.1303]])
"""

由以上代码可知Dropout还可以将部分tensor中的值置为0

补充:torch.nn.dropout和torch.nn.dropout2d的区别

import torch
import torch.nn as nn
import torch.autograd as autograd

m = nn.Dropout(p=0.5)
n = nn.Dropout2d(p=0.5)
input = autograd.Variable(torch.randn(1, 2, 6, 3)) ## 对dim=1维进行随机置为0

print(m(input))
print('****************************************************')
print(n(input))

Pytorch nn.Dropout怎么使用

下面的都是错误解释和错误示范,没有删除的原因是留下来进行对比,希望不要犯这类错误

# -*- coding: utf-8 -*-
import torch
import torch.nn as nn
import torch.autograd as autograd

m = nn.Dropout(p=0.5)
n = nn.Dropout2d(p=0.5)
input = autograd.Variable(torch.randn(2, 6, 3)) ## 对dim=1维进行随机置为0

print(m(input))
print('****************************************************')
print(n(input))

结果是:

Pytorch nn.Dropout怎么使用

可以看到torch.nn.Dropout对所有元素中每个元素按照概率0.5更改为零, 绿色椭圆,
而torch.nn.Dropout2d是对每个通道按照概率0.5置为0, 红色方框内
注:我只是圈除了部分

到此,关于“Pytorch nn.Dropout怎么使用”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注亿速云网站,小编会继续努力为大家带来更多实用的文章!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI