Pytorch 自定义层

前言

通过定义代码来按需⽣成任意复杂度的块,我们可以通过简洁的代码实现复杂的神经⽹络。


1.引入库

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

2.实现方式

2.1无名称

net1 = nn.Sequential(nn.Linear(10,20),
					 nn.ReLU(),
					 nn.Linear(20,3))
print(net1)
"""
输出结果:
Sequential(
  (0): Linear(in_features=10, out_features=20, bias=True)
  (1): ReLU()
  (2): Linear(in_features=20, out_features=3, bias=True)
)
"""

这种方式直接在Sequential中按顺序添加层,每一层没有名字只有索引

X = torch.rand(2, 10)
print(X)
"""
输出结果:
tensor([[0.7477, 0.1882, 0.4906, 0.2918, 0.1371, 0.1348, 0.5376, 0.3913, 0.8976,0.7175],
        [0.3601, 0.7126, 0.7465, 0.7667, 0.7281, 0.0142, 0.1097, 0.7086, 0.0304,0.1591]])
"""

print('net1.__call__(X):\n',net1.__call__(X))
print('net1(X):\n',net1(X))
"""
通过net(X)调⽤模型来获得输出,实际上是net1.__call__(X)的简写。
输出结果:
net1.__call__(X):
 tensor([[ 0.3241, -0.1625, -0.0823],
        [ 0.4224, -0.1465, -0.0354]], grad_fn=<AddmmBackward0>)
net1(X):
 tensor([[ 0.3241, -0.1625, -0.0823],
        [ 0.4224, -0.1465, -0.0354]], grad_fn=<AddmmBackward0>)    
"""

2.2有名称

1.通过OrderedDict来建立有序字典,为每一个层添加名字

from collections import OrderedDict
net2 = nn.Sequential(OrderedDict(Line1 = nn.Linear(10,20),
                                 Relu1 = nn.ReLU(),
                                 Line2 = nn.Linear(20,3)))
print(net2)
"""
输出结果:
Sequential(
  (Line1): Linear(in_features=10, out_features=20, bias=True)
  (Relu1): ReLU()
  (Line2): Linear(in_features=20, out_features=3, bias=True)
)
"""

2.通过add_module为每一个层添加名字

net3 = nn.Sequential()
net3.add_module('Line1',nn.Linear(10,20))
net3.add_module('Relu',nn.ReLU())
net3.add_module('Line2',nn.Linear(20,3))
print(net3)
"""
Sequential(
  (Line1): Linear(in_features=10, out_features=20, bias=True)
  (Relu): ReLU()
  (Line2): Linear(in_features=20, out_features=3, bias=True)
)
"""

通过索引访问模型的参数

print(net1[0].bias.data)
print(net2[0].bias.data)
print(net3[0].bias.data)
"""
输出结果:
tensor([-0.2356, -0.0435, -0.0970, -0.0823, -0.1362,  0.1233, -0.1198, -0.0274,
         0.0861,  0.1723, -0.2495,  0.1927,  0.2249, -0.0905, -0.2832, -0.0454,
        -0.2958, -0.1017,  0.0330, -0.2923])
tensor([-0.1373,  0.0859, -0.2827, -0.0146, -0.1069,  0.2276, -0.0155, -0.0095,
         0.2664,  0.2199,  0.2635, -0.2366,  0.1355,  0.2475, -0.2095, -0.1829,
         0.1811, -0.3021,  0.1595,  0.0335])
tensor([-0.2459, -0.2042,  0.0848,  0.2981,  0.0891, -0.2158,  0.0962, -0.0329,
        -0.1477,  0.1510, -0.0888,  0.1661,  0.3087,  0.1682, -0.1890, -0.1810,
         0.0902,  0.2852,  0.1354,  0.1661])
"""

但是就算给模型的层命名,也不能通过名字访问参数

print(net2['Line1'].bias.data)
"""
TypeError: 'str' object cannot be interpreted as an integer
"""

总结

本文仅仅简单介绍了Sequential的使用,Sequential除了本身可以用来定义模型之外,它还可以包装层,或者把几个层包装起来像一个块以供构建更复杂的模型

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
PyTorch中,您可以通过编写自定义的backward函数来实现自定义的梯度计算。这可以用于自定义损失函数、自定义层或其他需要自定义梯度计算的情况。 要自定义backward函数,您需要定义一个函数,它接受输入张量的梯度和其他参数,并返回相对于输入张量的梯度。然后,您可以将这个函数作为一个属性附加到您定义的自定义函数上。 下面是一个简单的示例,展示了如何实现一个自定义的梯度计算函数: ```python import torch class MyFunction(torch.autograd.Function): @staticmethod def forward(ctx, input): # 在forward函数中,您可以保存任何需要在backward函数中使用的中间结果 ctx.save_for_backward(input) return input @staticmethod def backward(ctx, grad_output): # 在backward函数中,您可以根据需要计算相对于输入的梯度 input, = ctx.saved_tensors grad_input = grad_output * 2 * input # 这里只是一个示例,您可以根据自己的需求编写梯度计算逻辑 return grad_input # 使用自定义函数创建输入张量 x = torch.tensor([1.0, 2.0, 3.0], requires_grad=True) # 使用自定义函数进行前向传播 output = MyFunction.apply(x) # 计算损失 loss = output.sum() # 执行反向传播 loss.backward() # 打印输入张量的梯度 print(x.grad) ``` 在这个示例中,我们定义了一个名为`MyFunction`的自定义函数,它将输入张量作为输出返回,并且在backward函数中计算相对于输入张量的梯度。我们使用`MyFunction.apply`方法应用自定义函数,并且可以通过调用`backward`方法来计算梯度。 请注意,自定义函数需要继承自`torch.autograd.Function`类,并且前向传播和反向传播函数都需要用`@staticmethod`修饰。 这只是一个简单的示例,您可以根据自己的需求编写更复杂的自定义backward函数。希望对您有帮助!

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值