栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

在Pytorch中,如何将L1正则化函数添加到激活中?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

在Pytorch中,如何将L1正则化函数添加到激活中?

这是您的操作方式:

  • 在模块的正向返回最终输出和要应用L1正则化的图层的输出中
  • loss
    变量将是输出wrt目标的交叉熵损失与L1惩罚的总和。

这是一个示例代码

import torchfrom torch.autograd import Variablefrom torch.nn import functional as Fclass MLP(torch.nn.Module):    def __init__(self):        super(MLP, self).__init__()        self.linear1 = torch.nn.Linear(128, 32)        self.linear2 = torch.nn.Linear(32, 16)        self.linear3 = torch.nn.Linear(16, 2)    def forward(self, x):        layer1_out = F.relu(self.linear1(x))        layer2_out = F.relu(self.linear2(layer1_out))        out = self.linear3(layer2_out)        return out, layer1_out, layer2_outbatchsize = 4lambda1, lambda2 = 0.5, 0.01model = MLP()optimizer = torch.optim.SGD(model.parameters(), lr=1e-4)# usually following pre is looped over all batches # but let's just do a dummy batch for brevityinputs = Variable(torch.rand(batchsize, 128))targets = Variable(torch.ones(batchsize).long())optimizer.zero_grad()outputs, layer1_out, layer2_out = model(inputs)cross_entropy_loss = F.cross_entropy(outputs, targets)all_linear1_params = torch.cat([x.view(-1) for x in model.linear1.parameters()])all_linear2_params = torch.cat([x.view(-1) for x in model.linear2.parameters()])l1_regularization = lambda1 * torch.norm(all_linear1_params, 1)l2_regularization = lambda2 * torch.norm(all_linear2_params, 2)loss = cross_entropy_loss + l1_regularization + l2_regularizationloss.backward()optimizer.step()


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/659512.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号