动手学深度学习(Pytorch版)代码实践 -卷积神经网络-16自定义层

16自定义层

python 复制代码
import torch
import torch.nn.functional as F
from torch import nn

class CenteredLayer(nn.Module):
    def __init__(self):
        super().__init__()
    
    #从其输入中减去均值
    #X.mean() 计算的是整个张量的均值
    #希望计算特定维度上的均值,可以传递 dim 参数。
    #例如,每一列均值,X.mean(dim=0)
    def forward(self, X):
        return X - X.mean()

layer = CenteredLayer()
"""
torch.FloatTensor: 这是 PyTorch 中的一种张量类型,专门用于存储浮点数数据。
尽管 torch.FloatTensor 是创建浮点张量的一种方式,
但在 PyTorch 的最新版本中,建议使用 torch.tensor 函数,
因为它更加通用和灵活。
"""

#均值为 3.0
print(layer(torch.FloatTensor([1, 2, 3, 4, 5])))
#tensor([-2., -1.,  0.,  1.,  2.])

net = nn.Sequential(nn.Linear(8, 128), CenteredLayer())
"""
torch.rand和torch.randn有什么区别?
一个均匀分布 [0,1) ,一个是标准正态分布。
"""
Y = net(torch.rand(4, 8))
print(Y.mean())
#tensor(-6.5193e-09, grad_fn=<MeanBackward0>)

#带参数的层
#实现自定义版本的全连接层
"""
该层需要两个参数,一个用于表示权重,另一个用于表示偏置项。 
在此实现中,我们使用修正线性单元作为激活函数。
该层需要输入参数:in_units和units,分别表示输入数和输出数。
"""
class MyLinear(nn.Module):
    def __init__(self, in_units, units):
        super().__init__()
        #nn.Parameter 是一种特殊的张量,会被自动添加到模型的参数列表中。
        self.weight = nn.Parameter(torch.randn(in_units, units))
        self.bias = nn.Parameter(torch.randn(units,))
        
    def forward(self, X):
        linear = torch.matmul(X, self.weight.data) + self.bias.data
        return F.relu(linear)
    
linear = MyLinear(5, 3)
print(linear.weight)
"""
tensor([[ 0.7130, -1.0828,  0.2203],
        [-2.0417, -0.1385,  0.6858],
        [-0.5163, -0.6009,  0.0783],
        [-0.3642,  0.5252, -0.6144],
        [-0.6479, -0.4700,  0.1486]], requires_grad=True)
"""
#使用自定义层直接执行前向传播计算。
print(linear(torch.rand(2, 5)))
"""
tensor([[0.0000, 0.0000, 0.2741],
        [0.0000, 0.0000, 0.5418]])
"""

#使用自定义层构建模型,就像使用内置的全连接层一样使用自定义层。
net = nn.Sequential(MyLinear(64, 8), MyLinear(8, 1))
print(net(torch.rand(2, 64)))
"""
tensor([[9.0080],
        [7.6102]])
"""
相关推荐
翱翔的苍鹰29 分钟前
一个简单的法律问答机器人实现思路
人工智能·深度学习·语言模型·自然语言处理
林深现海32 分钟前
【刘二大人】PyTorch深度学习实践笔记 —— 第三集:梯度下降(凝练版)
pytorch·笔记·深度学习
EW Frontier1 小时前
【ISAC+抗干扰+信号识别】5G ISAC+深度学习!破解智能交通“自干扰”难题,V2X通信准确率近100%【附代码】
人工智能·深度学习·5g·调制识别·抗干扰·isac
QUDONG_biubiubiu1 小时前
DeepSeek推出OCR 2模型!瞄准高难度文档识别
人工智能·深度学习·deepseek·deepseek-ocr 2
zhangfeng11331 小时前
deepseek部署和训练的PyTorch CUDA Transformers Accelerate PEFT稳定版本呢推荐
人工智能·pytorch·python
乾元1 小时前
暗网情报:自动化采集与情感分析在威胁狩猎中的应用
运维·网络·人工智能·深度学习·安全·架构·自动化
翱翔的苍鹰1 小时前
当前主流的**开源大语言模型(LLM)的核心知识总结
人工智能·深度学习·自然语言处理
Polaris_T1 小时前
2本9硕AI人实习&秋招分享(回江苏版)
人工智能·经验分享·深度学习·求职招聘
翱翔的苍鹰2 小时前
法律问答机器人”技术方案”的实现
人工智能·rnn·深度学习·自然语言处理
m0_603888712 小时前
Structured Over Scale Learning Spatial Reasoning from Educational Video
人工智能·深度学习·机器学习·ai·论文速览