【机器学习基础】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)之后

代码部分:

python 复制代码
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用法二

python 复制代码
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

https://blog.csdn.net/weixin_47050107/article/details/122722516

相关推荐
用户69190268133910 分钟前
Vibe Coding 开发项目的基本范式
人工智能·设计模式·代码规范
To_OC14 分钟前
别再跟 AI 死磕 prompt 了,我写了个 Loop 让它自己改到满意为止
人工智能·aigc·agent
血小溅42 分钟前
三大 AI 编码框架深度对比:GSD vs OpenSpec vs Superpowers
人工智能·后端
武子康4 小时前
调查研究-186 LangChain 和 LangGraph 的区别:从快速构建 Agent 到生产级工作流编排
人工智能·langchain·llm
武子康5 小时前
调查研究-185 CodeGraph 调研:给 AI 编程 Agent 一张代码库地图,少一点反复 grep(2026)
人工智能·openai·claude
aqi005 小时前
15天学会AI应用开发(八)使用向量数据库实现RAG功能
人工智能·python·大模型·ai编程·ai应用
混沌福王7 小时前
Electron三端统一架构:运行时Adapter、IPC能力边界与分层设计
人工智能·agent·ai编程
说了很好7 小时前
马尔可夫扩散链+损失函数推导,手把手实现原生Diffusion
人工智能
聂二AI落地内参7 小时前
合同抽取别停在 JSON:标准规则和交易日历才是硬仗
人工智能