iis服务器助手广告广告
返回顶部
首页 > 资讯 > 后端开发 > Python >Pytorch nn.Dropout的用法示例详解
  • 564
分享到

Pytorch nn.Dropout的用法示例详解

Python 官方文档:入门教程 => 点击学习

摘要

目录1.nn.Dropout用法一2.nn.Dropout用法二补充:torch.nn.dropout和torch.nn.dropout2d的区别1.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)之后

在这里插入图片描述

代码部分:

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))

在这里插入图片描述

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

# -*- 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))

结果是:

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

到此这篇关于PyTorch nn.Dropout的用法的文章就介绍到这了,更多相关Pytorch nn.Dropout用法内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!

--结束END--

本文标题: Pytorch nn.Dropout的用法示例详解

本文链接: https://www.lsjlt.com/news/203231.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作