李沐深度学习-模型构造

import torch
import torch.nn as nn
import numpy as np
import sys

sys.path.append("路径")
import d2lzh_pytorch as d2l


class MLP(nn.Module):
    def __init__(self, **kwargs):
        super(MLP, self).__init__()
        self.hidden = nn.Linear(784, 256)
        self.act = nn.ReLU()
        self.output = nn.Linear(256, 10)

    def forward(self, x):
        x = self.act(self.hidden(x))  # 传输样本数据特征
        return self.output(x)
        # 返回[n,10]大小的张量矩阵


# 实例化MLP类得到模型变量net
X = torch.randn(2, 784)
net = MLP()

'''
--------------------------------------实现一个和Sequential类具有相同的功能的MySequential类
'''


class MySequential(nn.Module):
    from collections import OrderedDict
    def __init__(self, *args):
        super(MySequential, self).__init__()
        if len(args) == 1 and isinstance(args[0], OrderedDict):
            for key, module in args[0].items():
                self.add_module(key, module)  # add_module 方法会将module添加进self._modules(一个OrderedDict)
        else:
            # 传入的是一些Module
            for idx, module in enumerate(args):
                self.add_module(str(idx), module)

    def forward(self, input):
        # self._module返回一个OrderedDict,保证会按照成员添加时的顺序遍历成员
        for module in self._modules.values():
            input = module(input)
        return input


# 用MySequential类来实现前面描述得MLP类,并使用随机初始化的模型做一次前向计算
net2 = MySequential(
    nn.Linear(784, 256),
    nn.ReLU(),
    nn.Linear(256, 10)
)

'''
---------------------------------------------ModuleList
操作就像是List操作,不论是定义方式还是添加元素方式
'''
net3 = nn.ModuleList([nn.Linear(784, 256), nn.ReLU()])
net3.append(nn.Linear(256, 10))
print(net3[-1])

'''
--------------------------------ModuleDict
接收一个子模块的字典作为水,也可以进行类似字典方式进行访问
'''
net4 = nn.ModuleDict({
    'linear': nn.Linear(784, 256),
    'act': nn.ReLU()
})
net4['output'] = nn.Linear(256, 10)
print(net4['linear'])  # 访问网络子模块
print(net4.output)

'''
--------------------------------------------集成Module类进行复杂模型构造
通过get_constant函数创建训练中不被迭代的参数:即常数参数
在前向计算中,除了使用创建的常数参数之外,还使用Tensor的函撒和python的控制流,并多次调用相同的层。
'''


class FancyMLP(nn.Module):
    def __init__(self):
        super(FancyMLP, self).__init__()
        # 定义常数参数
        self.rand_weight = torch.randn((20, 20), requires_grad=True)
        self.linear = nn.Linear(20, 20)

    def forward(self, x):
        x = self.linear(x)  # 第一层线性计算
        # 使用创建的常数参数,以及nn.functional.relu()函数
        x = nn.functional.relu(torch.mm(x, self.rand_weight) + 1)

        # 复用全连接层,等价于两个全连接层共享参数
        x = self.linear(x)
        # 控制流,需要调用item()函数来返回标量进行比较

        while x.norm().item() > 1:
            x /= 2
        if x.norm().item() < 0.8:
            x *= 10
        return x.sum()


Y = torch.rand(2, 20)
net5 = FancyMLP()
print(net5)
print(net5(Y))


# 因为FancyMLP和Sequential 类都是Module类的子类,所以可以嵌套调用它们
class NestMLP(nn.Module):
    def __init__(self):
        super(NestMLP, self).__init__()
        self.net = nn.Sequential(nn.Linear(40, 30), nn.ReLU())

    def forward(self, x):
        return self.net(x)


# NestMLP,FancyMLP,都是集成的Module类,都是他的子类,所以Sequential可以嵌套调用,但是维度需要有顺序
'''
------------这种嵌套情况有很大用处,比如设置丢弃时,nn.Dropout() 是直接在Sequential类中的
不同的类可以设置不同的网络子层,并设置不同子层部分对应的前向处理逻辑,
这样就可以进行复杂网络层的设计,而不是简单的线性层设计
'''
net6 = nn.Sequential(NestMLP(), nn.Linear(30, 20), FancyMLP())
Z = torch.rand(2, 40)
print(net6)
print(net6(Z))

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值