16-模型构造 动手深度学习

#16神经网络基础
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)#2是批量大小 20是输入维度
print(net(x))

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)))

net1 = MLP()
print(net(x))

class MySequential(nn.Module):
    def __init__(self,*args):#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

net2 = 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=True)
        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()

net3 = FixedHiddenMLP()
print(net3(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())
print(chimera(x))
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值