avatar

AngYi

Aim for the stars, and beyond.

  • 首页
  • 分类
  • 标签
  • 归档
  • 相册
  • 关于我
Home 【PyTorch】2. 激活函数、模型函数、损失函数
文章

【PyTorch】2. 激活函数、模型函数、损失函数

Posted 2022-02-17 Updated 2023-10- 17
By AngYi
12~15 min read

1. torch.nn.function

PyTorch 和神经网络相关的功能组件基本都封装在torch.nn中,而这些功能组件基本上都有函数和类两种形式实现。

函数实现方法:nn.functional(F)的基本功能组件罗列如下:

激活函数模型层损失函数
F.reluF.linearF.binary_cross_entropy
F.sigmoidF.cov2dF.mse_loss
F.tanhF.max_pool2dF.cross_entropy
F.softmaxF.dropout2d
F.embedding

类实现:torch.nn.class, from torch import nn

激活函数模型层损失函数
nn.ReLunn.Linearnn.BCELoss
nn.Sigmoidnn.Cov2dnn.MSELoss
nn.Tanhnn.MaxPool2dnn.CrossEntropyLoss
nn.Softmaxnn.DropOut2d
nn.Embedding

2. torch.nn.Module

在Pytorch中,模型的参数是需要被优化器训练的,因此,通常要设置参数为 requires_grad = True 的张量。

同时,在一个模型中,往往有许多的参数,要手动管理这些参数并不是一件容易的事情。

nn.Module 管理参数

Pytorch一般将参数用nn.Parameter来表示,并且用nn.Module来管理其结构下的所有参数。

# nn.ParameterList 可以将多个nn.Parameter组成一个列表
params_list = nn.ParameterList([nn.Parameter(torch.rand(8,i)) for i in range(1,3)])
print(params_list)
print(params_list[0].requires_grad)
ParameterList(
    (0): Parameter containing: [torch.FloatTensor of size 8x1]
    (1): Parameter containing: [torch.FloatTensor of size 8x2]
)
True
# nn.ParameterDict 可以将多个nn.Parameter组成一个字典

params_dict = nn.ParameterDict({"a":nn.Parameter(torch.rand(2,2)),
                               "b":nn.Parameter(torch.zeros(2))})
print(params_dict)
print(params_dict["a"].requires_grad)

ParameterDict(
    (a): Parameter containing: [torch.FloatTensor of size 2x2]
    (b): Parameter containing: [torch.FloatTensor of size 2]
)
True

nn.Module管理模型子模块

一般情况下,我们都很少直接使用 nn.Parameter来定义参数构建模型,而是通过一些拼装一些常用的模型层来构造模型。

这些模型层也是继承自nn.Module的对象,本身也包括参数,属于我们要定义的模块的子模块。

如果模型是分功能模块的,那么可以通过下面这种方式,定义子模块。

class Net(nn.Module):

    def __init__(self):
        super(Net, self).__init__()
        
				## 第一个子模块
        self.embedding = nn.Embedding(num_embeddings = 10000,embedding_dim = 3,padding_idx = 1)
        
        ## 第二个子模块
        self.conv = nn.Sequential()
        self.conv.add_module("conv_1",nn.Conv1d(in_channels = 3,out_channels = 16,kernel_size = 5))
        self.conv.add_module("pool_1",nn.MaxPool1d(kernel_size = 2))
        self.conv.add_module("relu_1",nn.ReLU())
        self.conv.add_module("conv_2",nn.Conv1d(in_channels = 16,out_channels = 128,kernel_size = 2))
        self.conv.add_module("pool_2",nn.MaxPool1d(kernel_size = 2))
        self.conv.add_module("relu_2",nn.ReLU())
        
				## 第三个子模块
        self.dense = nn.Sequential()
        self.dense.add_module("flatten",nn.Flatten())
        self.dense.add_module("linear",nn.Linear(6144,1))
        self.dense.add_module("sigmoid",nn.Sigmoid())

    def forward(self,x):
        x = self.embedding(x).transpose(1,2)
        x = self.conv(x)
        y = self.dense(x)
        return y

net = Net()

遍历子模块

i = 0
for name,child in net.named_children():
    i+=1
    print(name,":",child,"\n")
print("child number",i)

冻结某一个模块

children_dict = {name:module for name,module in net.named_children()}

print(children_dict)
embedding = children_dict["embedding"]
embedding.requires_grad_(False) #冻结其参数
人工智能
python PyTorch
License:  CC BY 4.0
Share

Further Reading

Feb 8, 2025

DeepSeek 创始人梁文峰采访:创新、人才与中国 AI 发展

一、DeepSeek 引发的震动及其背后原因 当 DeepSeek 震惊了硅谷、美国乃至全世界时,我们来看看 DeepSeek 创始人梁文峰的观点。他认为 DeepSeek 之所以让硅谷的很多人惊讶,是因为这是一个中国公司以创新贡献者的身份加入到他们的游戏里。在大部分中国公司习惯跟随而非创新的大环境

Oct 19, 2024

DVC-DataVersionControl 数据版本管理

介绍 作为一名算法工程师,你是否有这样的困惑,每个实验的数据(配置)文件和模型文件,模型结果无法很好的进行版本管理 这三者的匹配是很麻烦的一个事情,当你做了很多次实验之后,你发现,诶,这个结果对应的参数配置是哪套,对应的数据处理方法是什么?模型文件是怎么命名的,面对文件夹里的一堆开始拼命回忆和翻找

Oct 10, 2024

诺贝尔物理学奖颁给了神经网络

偶然间在CSDN看到了这个官方组织的活动,说明这个话题不止少部分人关注,还是值得思考的。 据法新社10月8日斯德哥尔摩消息,诺贝尔委员会表示:“今年的两位诺贝尔物理学奖获得者利用了物理学方法来寻找信息的特征,构建了为当今强大的机器学习奠定基础的方法。”

OLDER

【PyTorch】1. 为什么要学PyTorch

NEWER

免费为你的网站开启Https

Recently Updated

  • DeepSeek 创始人梁文峰采访:创新、人才与中国 AI 发展
  • 福州-厦门之行
  • 我有自己的摄影网站啦
  • 借助Ollama一键本地部署CodeGeex,让AI帮你打工
  • Dash 进阶技巧

Trending Tags

ssh linux matlab 感悟 读书 blog git python flask ML

Contents

©2025 AngYi. Some rights reserved.

Using the Halo theme Chirpy