PyTorch神经网络

nn.Module

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


# 任何层与神经网络 都是nn.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):
        # X经过隐藏层,再经过激活函数,最后输出
        return self.out(F.relu(self.hidden(X)))


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

# 生成随机输入
X = torch.rand(2, 20)

net(X)
# 实例化
net = MLP()
print(net(X))


# 实现nn.Sequential相似的操作
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))
print(net(X))


# 在正向传播中执行代码
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)
        # 如果绝对值的求和大于1就除2
        while X.abs().sum() > 1:
            X /= 2
        return X.sum()


net = FixedHiddenMLP()
net(X)


# 混合搭配各种组合块的方法
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)

参数管理

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

# 单隐藏层的多层感知机
net = nn.Sequential(nn.Linear(4, 8),
                    nn.ReLU(), nn.Linear(8, 1))
X = torch.rand(size=(2, 4))
net(X)
# 参数访问,这里拿的是最后的一个输出层,这里是第三层
# 叫做state是因为权重就是自身的一个状态,这里会输出weight和bios
print(net[2].state_dict())
# 也可以直接访问weight和bios
print(type(net[2].bias))
print(net[2].bias)  # 因为它除了data属性以外还有梯度
print(net[2].bias.data)
print(net[2].weight.grad)  # 没有计算梯度所以为None

# 拿到整个网络的参数
print(*[(name, param.shape) for name, param in net[0].named_parameters()])  # 名字叫做weight和bias
print(*[(name, param.shape) for name, param in net.named_parameters()])
# 也可以通过名字访问
print(net.state_dict()['2.bias'].data)


# 从嵌套快收集参数
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)
print(rgnet)

自定义层

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):
        # 输入剪均值,其实计算均值化为0
        return X - X.mean()


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

net = nn.Sequential(nn.Linear(8, 128), CenteredLayer())
Y = net(torch.rand(4, 8))
Y.mean()


# 带参数的层
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):
        # 矩阵乘法+bias
        linear = torch.matmul(X, self.weight.data) + self.bias.data
        return F.relu(linear)


linear = MyLinear(5, 3)
print(linear.weight)

读写文件

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

# 构造长为4的向量
x = torch.arange(4)
# 在当前目录保存这个向量
torch.save(x, 'x-file')
# 可以重新加载回来
x2 = torch.load("x-file")
print(x2)

# 存储张量列表,然后读会内存
y = torch.zeros(4)
torch.save([x, y], 'x-files')
x2, y2 = torch.load('x-files')
print(x, y2)

# 写入或读取字符串映射到张量的字典,x对应x矩阵,y对应y字典
mydict = {'x': x, 'y': y}
torch.save(mydict, 'mydict')
mydict2 = torch.load('mydict')
print(mydict2)


# 加载保存模型参数
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.rand(size=(2, 20))
Y = net(X)
torch.save(net.state_dict(), 'mlp.params')

clone = MLP()
# 带走网络的信息和具体的参数
clone.load_state_dict(torch.load("mlp.params"))
# 设置为评估模型然后打印
print(clone.eval())
# 序列化后调用这个网络,然后进行传播
Y_clone = clone(X)
# 与之前的Y进行比较,这里是对每个元素进行比较
print(Y_clone == Y)

GPU计算

import torch
from torch import nn
from d2l import torch as d2l

# 分别是 第0个gpu第一个gpu
print(torch.device('cpu'), torch.cuda.device('cuda'), torch.cuda.device('cuda:1'))
# 查询可用的gpu数量
print(torch.cuda.device_count())

# 默认在cpu创建的
x = torch.tensor([1, 2, 3])
print(x.device)
# 这样就可以创建在GPU上了
X = torch.ones(2, 3, device=d2l.try_gpu())
print(X)
# 进行一次拷贝
Z = X.cuda(0)
print(X)
print(Z)
# 我们进行计算时,必须要保证计算的俩个元素都在同一个GPU上
print(X + Z)

# 做神经网络的计算
net = nn.Sequential(nn.Linear(3, 1))
# 移动到gpu上
net = net.to(device=d2l.try_gpu())
print("net:", net(X))
print(net[0].weight.data.device)
Last modification:July 18, 2024
如果觉得我的文章对你有用,请随意赞赏