pytorch实现dropout和正则化

本文介绍了 Dropout 的原理,它通过在前向传播时随机关闭部分神经元来增强模型泛化能力,以此防止过拟合。此外,还详细阐述了如何在 PyTorch 中实现 L1 和 L2 正则化,这两种正则化技术用于减少模型复杂度,避免过拟合。
摘要由CSDN通过智能技术生成

一.Dropout原理

简单来说,就是在前向传播的时候,让某个神经元的激活值以一定的概率p停止工作,这样可以使模型泛化性更强,防止过拟合。

dim_in = 28*28
dim_hidden = 158
dim_out = 10

class TwoLayerNet(torch.nn.Module):
    def __init__(self,dim_in,dim_hidden,dim_out):
        super(TwoLayerNet,self).__init()
        self.fc1 = torch.nn.Linear(dim_in,din_hid,bias=True)
        self.fc2 = torch.nn.Linear(dim_hid,dim_out,bias=True)
    
    def forward(self,x):
        x = x.view(x.size(0),-1)
        x = self.fc1(x)
        x = F.relu(x)
        x = F.dropout(x,p=0.5)
        x = self.fc2(x)
        return F.log_softmax(x,dim=1)
#之后定义模型

二.pytorch实现L1、L2正则化

import torch
from torch.nn import functional as F
from torch.autograd import Variable

class MLP(torch.nn.Module):
    def __init__(self):
        super(MLP,self).__init__()
        se
  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值