深度学习24:PyTorch:Sequential构建模型

目录标题

可以通过torch.nn.Sequential来构建模型,将各层按顺序传入

一、代码

python 复制代码
import torch
import torch.nn as nn

from torchsummary import summary

#  1.定义数据
x = torch.randn(10, 3)

# 2. 构建模型
model = nn.Sequential(
    nn.Linear(in_features=3, out_features=4),
    nn.Tanh(),
    nn.Linear(in_features=4, out_features=4),
    nn.ReLU(),
    nn.Linear(in_features=4, out_features=2),
    nn.Softmax(dim=1),
)


# 定义一个参数初始化的函数
def init_params(layer):
    if isinstance(layer, nn.Linear):
        nn.init.xavier_uniform_(layer.weight)
        nn.init.constant_(layer.bias, val=0.1)


# 3. 参数初始化
model.apply(init_params)

# 4. 前向传播
output = model(x)
print(output)

summary(model, input_size=(3,), batch_size=10, device='cpu')


#打印如下
tensor([[0.2617, 0.7383],
        [0.4800, 0.5200],
        [0.2728, 0.7272],
        [0.3490, 0.6510],
        [0.4847, 0.5153],
        [0.5021, 0.4979],
        [0.1817, 0.8183],
        [0.4712, 0.5288],
        [0.2881, 0.7119],
        [0.4895, 0.5105]], grad_fn=<SoftmaxBackward0>)
----------------------------------------------------------------
        Layer (type)               Output Shape         Param #
================================================================
            Linear-1                    [10, 4]              16
              Tanh-2                    [10, 4]               0
            Linear-3                    [10, 4]              20
              ReLU-4                    [10, 4]               0
            Linear-5                    [10, 2]              10
           Softmax-6                    [10, 2]               0
================================================================
Total params: 46
Trainable params: 46
Non-trainable params: 0
----------------------------------------------------------------
Input size (MB): 0.00
Forward/backward pass size (MB): 0.00
Params size (MB): 0.00
Estimated Total Size (MB): 0.00
----------------------------------------------------------------
相关推荐
前端的阶梯5 小时前
AI Agent 之 工具(Tool)
人工智能
孟健5 小时前
用 HyperFrames 解决前端视频生成难题:国产 Flash 模型实测 3 条 1080p 视频
前端·人工智能·开源
两万五千个小时5 小时前
Agent 记忆不是聊天记录,而是为未来准备的上下文 ——Anthropic 的四层记忆架构与 Dream 思想
人工智能·程序员
汤姆宝库5 小时前
RoPE旋转位置编码的实现与长上下文外推
python·深度学习·机器学习
汤姆宝库6 小时前
语料清洗流水线的实现:启发式过滤、MinHash去重与质量分级
人工智能
火山引擎开发者社区6 小时前
不会 FFmpeg 也能做视频后期?AI MediaKit Skill 帮你实现
人工智能
tellmewhoisi6 小时前
深度学习0:数学知识:(L1正则化和L2正则化)
人工智能·深度学习
AI_Gump6 小时前
AutoGLM 两年演进深度解读:一篇讲透智谱的手机 Agent 路线
人工智能·智能手机
玄枢AI6 小时前
AI把待办整理成JSON后,用Python检查漏字段、类型错误和未知值
人工智能
VIP_CQCRE6 小时前
GPT Image 2.6 选型别只看首张:用盲评与合格图耗时比较 Flare、Sunburst
软件测试·图像处理·人工智能