深度学习笔记12:PyTorch神经网络基础

本文介绍了PyTorch中构建神经网络的基本方法,包括使用nn.Sequential、自定义Module、顺序块以及混合模块的组合。还探讨了参数管理,如权重初始化、参数访问和保存加载模型。最后展示了如何在自定义层中实现特定的前向传播逻辑。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

PyTorch 神经网络基础

层和块

首先,我们回顾一下多层感知机

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

net = nn.Sequential(nn.Linear(20, 256), nn.ReLU(), nn.Linear(256, 10)) #构造简单单层神经网络

X = torch.rand(2, 20)
net(X)

结果:

tensor([[ 0.1808, 0.0987, 0.0579, -0.0164, 0.0855, 0.1229, 0.0430, 0.1360,
0.0092, -0.0319],
[ 0.2228, 0.1155, 0.1356, -0.0012, 0.2328, 0.0880, -0.0672, 0.1296,
0.0027, -0.0714]], grad_fn=)

nn.Sequential定义了一种特殊的Module

自定义块

class MLP(nn.Module): 
    def __init__(self):
        super().__init__()
        self.hidden = nn.Linear(20, 256)
        self.out = nn.Linear(256, 10)

    def forward(self, X):
        return self.out(F.relu(self.hidden(X)))

实例化多层感知机的层,然后在每次调用正向传播函数时调用这些层

net = MLP()
net(X)

结果:

tensor([[ 0.0277, -0.0289, -0.0253, -0.0940, -0.1739, -0.1322, -0.0255, -0.0681,
-0.1383, -0.0426],
[ 0.1502, -0.0275, 0.0335, -0.0254, -0.1443, 0.0488, -0.1500, -0.0989,
-0.1833, -0.1418]], grad_fn=)

顺序块

class MySequential(nn.Module):
    def __init__(self, *args):
        super().__init__()
        for block in args:
            self._modules[block] = block

    def forward(self, X):
        for block in self._modules.values():
            X = block(X)
        return X

net = MySequential(nn.Linear(20, 256), nn.ReLU(), nn.Linear(256, 10))
net(X)

结果:

tensor([[-0.2656, -0.2195, -0.1814, 0.0748, -0.1268, 0.0262, 0.1946, -0.0730,
0.1129, 0.0511],
[-0.0832, -0.2227, -0.0749, 0.1662, -0.1054, 0.0838, 0.1809, -0.1683,
0.1251, 0.0843]], grad_fn=)

在正向传播函数中执行代码

class FixedHiddenMLP(nn.Module):
    def __init__(self):
        super().__init__()
        self.rand_weight = torch.rand((20, 20), requires_grad=False)
        self.linear = nn.Linear(20, 20)

    def forward(self, X):
        X = self.linear(X)
        X = F.relu(torch.mm(X, self.rand_weight) + 1)
        X = self.linear(X)
        while X.abs().sum() > 1:
            X /= 2
        return X.sum()

net = FixedHiddenMLP()
net(X)

结果:tensor(0.1623, grad_fn=)

混合搭配各种组合块的方法

class NestMLP(nn.Module):
    def __init__(self):
        super().__init__()
        self.net = nn.Sequential(nn.Linear(20, 64), nn.ReLU(),
                                 nn.Linear(64, 32), nn.ReLU())
        self.linear = nn.Linear(32, 16)

    def forward(self, X):
        return self.linear(self.net(X))

chimera = nn.Sequential(NestMLP(), nn.Linear(16, 20), FixedHiddenMLP())
chimera(X)

结果:tensor(0.0561, grad_fn=)

参数管理

我们首先关注具有单隐藏层的多层感知机

import torch
from torch import nn

net = nn.Sequential(nn.Linear(4, 8), nn.ReLU(), nn.Linear(8, 1))
X = torch.rand(size=(2, 4))
net(X)

结果:

tensor([[0.4708],
[0.4191]], grad_fn=)

参数访问

print(net[2].state_dict())

结果:OrderedDict([(‘weight’, tensor([[ 0.2507, -0.0244, 0.2514, 0.1623, 0.0830, 0.1512, -0.3402, -0.0861]])), (‘bias’, tensor([0.2691]))])

目标参数

print(type(net[2].bias))
print(net[2].bias)
print(net[2].bias.data)

结果:

<class ‘torch.nn.parameter.Parameter’>
Parameter containing:
tensor([0.2691], requires_grad=True)
tensor([0.2691])

net[2].weight.grad == None

结果:True

一次性访问所有参数

print(*[(name, param.shape) for name, param in net[0].named_parameters()])
print(*[(name, param.shape) for name, param in net.named_parameters()])

结果:

(‘weight’, torch.Size([8, 4])) (‘bias’, torch.Size([8]))
(‘0.weight’, torch.Size([8, 4])) (‘0.bias’, torch.Size([8])) (‘2.weight’, torch.Size([1, 8])) (‘2.bias’, torch.Size([1]))

net.state_dict()['2.bias'].data

结果:tensor([0.2691])

从嵌套块收集参数

def block1():
    return nn.Sequential(nn.Linear(4, 8), nn.ReLU(), nn.Linear(8, 4),
                         nn.ReLU())

def block2():
    net = nn.Sequential()
    for i in range(4):
        net.add_module(f'block {i}', block1())
    return net

rgnet = nn.Sequential(block2(), nn.Linear(4, 1))
rgnet(X)

结果:

tensor([[0.1278],
[0.1278]], grad_fn=)

我们已经设计了网络,让我们看看它是如何组织的

print(rgnet)

结果:

Sequential(
(0): Sequential(
(block 0): Sequential(
(0): Linear(in_features=4, out_features=8, bias=True)
(1): ReLU()
(2): Linear(in_features=8, out_features=4, bias=True)
(3): ReLU()
)
(block 1): Sequential(
(0): Linear(in_features=4, out_features=8, bias=True)
(1): ReLU()
(2): Linear(in_features=8, out_features=4, bias=True)
(3): ReLU()
)
(block 2): Sequential(
(0): Linear(in_features=4, out_features=8, bias=True)
(1): ReLU()
(2): Linear(in_features=8, out_features=4, bias=True)
(3): ReLU()
)
(block 3): Sequential(
(0): Linear(in_features=4, out_features=8, bias=True)
(1): ReLU()
(2): Linear(in_features=8, out_features=4, bias=True)
(3): ReLU()
)
)
(1): Linear(in_features=4, out_features=1, bias=True)
)

rgnet[0][1][0].bias.data

结果:tensor([-0.2244, 0.2439, -0.4510, 0.0626, -0.2900, -0.4520, 0.2992, 0.4947])

内置初始化

def init_normal(m):
    if type(m) == nn.Linear:
        nn.init.normal_(m.weight, mean=0, std=0.01)
        nn.init.zeros_(m.bias)

net.apply(init_normal)
net[0].weight.data[0], net[0].bias.data[0]

结果:(tensor([ 0.0045, -0.0102, -0.0113, 0.0015]), tensor(0.))

def init_constant(m):
    if type(m) == nn.Linear:
        nn.init.constant_(m.weight, 1)
        nn.init.zeros_(m.bias)

net.apply(init_constant)
net[0].weight.data[0], net[0].bias.data[0]

结果:(tensor([1., 1., 1., 1.]), tensor(0.))

对某些块应用不同的初始化方法

def xavier(m):
    if type(m) == nn.Linear:
        nn.init.xavier_uniform_(m.weight)

def init_42(m):
    if type(m) == nn.Linear:
        nn.init.constant_(m.weight, 42)

net[0].apply(xavier)
net[2].apply(init_42)
print(net[0].weight.data[0])
print(net[2].weight.data)

结果:

tensor([ 0.3996, -0.5920, 0.3828, -0.5140])
tensor([[42., 42., 42., 42., 42., 42., 42., 42.]])

自定义初始化

def my_init(m):
    if type(m) == nn.Linear:
        print(
            "Init",
            *[(name, param.shape) for name, param in m.named_parameters()][0])
        nn.init.uniform_(m.weight, -10, 10)
        m.weight.data *= m.weight.data.abs() >= 5

net.apply(my_init)
net[0].weight[:2]

结果:

Init weight torch.Size([8, 4])
Init weight torch.Size([1, 8])

tensor([[ 9.7716, -0.0000, -0.0000, 0.0000],
[-6.1675, -0.0000, 5.4320, 0.0000]], grad_fn=)

net[0].weight.data[:] += 1
net[0].weight.data[0, 0] = 42
net[0].weight.data[0]

结果:tensor([42., 1., 1., 1.])

参数绑定

shared = nn.Linear(8, 8)
net = nn.Sequential(nn.Linear(4, 8), nn.ReLU(), shared, nn.ReLU(), shared,
                    nn.ReLU(), nn.Linear(8, 1))
net(X)
print(net[2].weight.data[0] == net[4].weight.data[0])
net[2].weight.data[0, 0] = 100
print(net[2].weight.data[0] == net[4].weight.data[0])

结果:

tensor([True, True, True, True, True, True, True, True])
tensor([True, True, True, True, True, True, True, True])

自定义层

构造一个没有任何参数的自定义层

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

class CenteredLayer(nn.Module):
    def __init__(self):
        super().__init__()

    def forward(self, X):
        return X - X.mean() #输入-均值

layer = CenteredLayer()
layer(torch.FloatTensor([1, 2, 3, 4, 5]))

结果:tensor([-2., -1., 0., 1., 2.])

将层作为组件合并到构建更复杂的模型中

net = nn.Sequential(nn.Linear(8, 128), CenteredLayer())

Y = net(torch.rand(4, 8))
Y.mean()

结果:tensor(8.1491e-10, grad_fn=)

带参数的层

class MyLinear(nn.Module):
    def __init__(self, in_units, units):
        super().__init__()
        self.weight = nn.Parameter(torch.randn(in_units, units)) #randn初始化 再放入parameter
        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)
linear.weight

结果:

Parameter containing:
tensor([[-1.5141, -0.9043, 1.2935],
[ 0.1723, 0.5600, 0.4521],
[-0.7114, 0.8145, -0.9763],
[-0.3176, 1.5751, -0.2650],
[ 0.3745, 0.6907, 0.3630]], requires_grad=True)

读写文件

加载和保存张量

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

x = torch.arange(4)
torch.save(x, 'x-file')

x2 = torch.load('x-file')
x2

结果:tensor([0, 1, 2, 3])

存储一个张量列表,然后把它们读回内存

y = torch.zeros(4)
torch.save([x, y], 'x-files')
x2, y2 = torch.load('x-files')
(x2, y2)

结果:(tensor([0, 1, 2, 3]), tensor([0., 0., 0., 0.]))

写入或读取从字符串映射到张量的字典

mydict = {'x': x, 'y': y}
torch.save(mydict, 'mydict')
mydict2 = torch.load('mydict')
mydict2

结果:{‘x’: tensor([0, 1, 2, 3]), ‘y’: tensor([0., 0., 0., 0.])}

加载和保存模型参数

class MLP(nn.Module):
    def __init__(self):
        super().__init__()
        self.hidden = nn.Linear(20, 256)
        self.output = nn.Linear(256, 10)

    def forward(self, x):
        return self.output(F.relu(self.hidden(x)))

net = MLP()
X = torch.randn(size=(2, 20))
Y = net(X)

将模型的参数存储为一个叫做“mlp.params”的文件

torch.save(net.state_dict(), 'mlp.params')

实例化了原始多层感知机模型的一个备份。 直接读取文件中存储的参数

clone = MLP()
clone.load_state_dict(torch.load('mlp.params'))
clone.eval() #进入测试模式

结果:

MLP(
(hidden): Linear(in_features=20, out_features=256, bias=True)
(output): Linear(in_features=256, out_features=10, bias=True)
)

Y_clone = clone(X)
Y_clone == Y

结果:

tensor([[True, True, True, True, True, True, True, True, True, True],
[True, True, True, True, True, True, True, True, True, True]])

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值