pytorch 共享参数方法

在很多神经网络中,往往会出现多个层共享一个权重的情况,pytorch可以快速地处理权重共享问题。

例子1:

class ConvNet(nn.Module):
def init(self):
super(ConvNet, self).init()
self.conv_weight = nn.Parameter(torch.randn(3, 3, 5, 5))

def forward(self, x):
    x = nn.functional.conv2d(x, self.conv_weight, bias=None, stride=1, padding=2, dilation=1, groups=1)
    x = nn.functional.conv2d(x, self.conv_weight.transpose(2, 3).contiguous(), bias=None, stride=1, padding=0, dilation=1,
                             groups=1)
    return x

上边这段程序定义了两个卷积层,这两个卷积层共享一个权重conv_weight,第一个卷积层的权重是conv_weight本身,第二个卷积层是conv_weight的转置。注意在gpu上运行时,transpose()后边必须加上.contiguous()使转置操作连续化,否则会报错。

例子2:

class LinearNet(nn.Module):
def init(self):
super(LinearNet, self).init()
self.linear_weight = nn.Parameter(torch.randn(3, 3))

def forward(self, x):
    x = nn.functional.linear(x, self.linear_weight)
    x = nn.functional.linear(x, self.linear_weight.t())

    return x

这个网络实现了一个双层感知器,权重同样是一个parameter的本身及其转置。

例子3:

class LinearNet2(nn.Module):
def init(self):
super(LinearNet2, self).init()
self.w = nn.Parameter(torch.FloatTensor([[1.1,0,0], [0,1,0], [0,0,1]]))

def forward(self, x):
    x = x.mm(self.w)
    x = x.mm(self.w.t())
    return x

这个方法直接用mm函数将x与w相乘,与上边的网络效果相同

作者:马管子
来源:CSDN
原文:https://blog.csdn.net/qq_19672579/article/details/79373985
版权声明:本文为博主原创文章,转载请附上博文链接!

-- coding: utf-8 --

import random
import torch
from torch.autograd import Variable

class DynamicNet(torch.nn.Module):
def init(self, D_in, H, D_out):
“”"
In the constructor we construct three nn.Linear instances that we will use
in the forward pass.
“”"
super(DynamicNet, self).init()
self.input_linear = torch.nn.Linear(D_in, H)
self.middle_linear = torch.nn.Linear(H, H)
self.output_linear = torch.nn.Linear(H, D_out)

def forward(self, x):
    """
    For the forward pass of the model, we randomly choose either 0, 1, 2, or 3
    and reuse the middle_linear Module that many times to compute hidden layer
    representations.

    Since each forward pass builds a dynamic computation graph, we can use normal
    Python control-flow operators like loops or conditional statements when
    defining the forward pass of the model.

    Here we also see that it is perfectly safe to reuse the same Module many
    times when defining a computational graph. This is a big improvement from Lua
    Torch, where each Module could be used only once.
    """
    h_relu = self.input_linear(x).clamp(min=0)
    for _ in range(random.randint(0, 3)):
        #这里重复利用Middle linear,权重共享,比tensorflow更方便哎
        h_relu = self.middle_linear(h_relu).clamp(min=0)
    y_pred = self.output_linear(h_relu)
    return y_pred

N is batch size; D_in is input dimension;

H is hidden dimension; D_out is output dimension.

N, D_in, H, D_out = 64, 1000, 100, 10

Create random Tensors to hold inputs and outputs, and wrap them in Variables

x = Variable(torch.randn(N, D_in))
y = Variable(torch.randn(N, D_out), requires_grad=False)

Construct our model by instantiating the class defined above

model = DynamicNet(D_in, H, D_out)

Construct our loss function and an Optimizer. Training this strange model with

vanilla stochastic gradient descent is tough, so we use momentum

criterion = torch.nn.MSELoss(size_average=False)
optimizer = torch.optim.SGD(model.parameters(), lr=1e-4, momentum=0.9)
for t in range(500):
# Forward pass: Compute predicted y by passing x to the model
y_pred = model(x)

# Compute and print loss
loss = criterion(y_pred, y)
print(t, loss.data[0])

# Zero gradients, perform a backward pass, and update the weights.
optimizer.zero_grad()
loss.backward()
optimizer.step()

作者:HxShine
来源:CSDN
原文:https://blog.csdn.net/qq_16949707/article/details/72626448
版权声明:本文为博主原创文章,转载请附上博文链接!

  • 5
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
PyTorch中调参是神经网络训练过程中非常重要的一部分。下面我将给出一些常用的PyTorch神经网络调参方法: 1. 参数访问和修改:你可以使用`model.parameters()`方法来访问模型的所有参数。这个方法返回一个可迭代的参数列表,你可以通过遍历这个列表来访问和修改每个参数的值。例如,你可以使用`param.data`来访问参数的值,并使用`param.data = new_value`来修改参数的值。 2. 参数初始化:在PyTorch中,你可以使用不同的方法来初始化神经网络的参数PyTorch提供了一些预定义的初始化方法,比如`torch.nn.init.xavier_uniform_()`和`torch.nn.init.kaiming_normal_()`等。你可以在创建模型的时候使用这些初始化方法来初始化参数。此外,你也可以自定义初始化方法,并在模型中调用它们。可以参考中的示例代码来了解如何在PyTorch中进行参数初始化。 3. 参数绑定:在某些情况下,你可能希望共享模型中的参数。在PyTorch中,你可以通过将一个参数的引用赋给另一个参数来实现参数的绑定。这样做的好处是可以节省内存,并且可以同时更新所有绑定的参数。你可以使用`param1.data = param2.data`来将参数2绑定到参数1。 总结起来,调参是神经网络训练中的重要环节,你可以通过访问和修改参数、初始化参数以及绑定参数方法来调整神经网络的性能和表现。你可以参考和中的内容来学习更多关于在PyTorch中进行神经网络调参的方法。同样,你也可以参考中提供的教程来深入了解PyTorch的使用。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值