pytorch打印模型结构和参数

两种方式

当我们使用pytorch进行模型训练或测试时,有时候希望能知道模型每一层分别是什么,具有怎样的参数。此时我们可以将模型打印出来,输出每一层的名字、类型、参数等。

常用的命令行打印模型结构的方法有两种:

  • 一是直接print
  • 二是使用torchsummary库的summary
    但是二者在输出上有着一些区别。首先说结论:
    print输出结果是每一层的名字、类别、以及构造时的参数,例如对于卷积层,还包括用户定义的stride、bias等;而torch summary则会打印类别、深度、输出Tensor的形状、参数数量等。
    这也是很重要的一点,print打印的每一层顺序,是模型init函数中定义的顺序,而torchsummary则是模型执行起来输入张量真正计算的顺序。

torch summary 安装:

示例

print:

summary:

打印每一层的输入输出结构

python 复制代码
import torch
from torch import nn
#from d2l import torch as d2l

net1D = nn.Sequential(nn.Conv1d(1,6,kernel_size=5,padding=2),nn.Sigmoid(),
                    nn.AvgPool1d(kernel_size=2,stride=2),
                    nn.Conv1d(6,16,kernel_size=5),nn.Sigmoid(),
                    nn.AvgPool1d(kernel_size=2,stride=2),
                    nn.Flatten(),
                    nn.Linear(16*5,120),nn.Sigmoid(), # 这边要根据上面的输出重新计算拉平后的大小
                    nn.Linear(120,84),nn.Sigmoid(),
                    nn.Linear(84,2)
                    )
Y=torch.rand(size=(1,1,28),dtype=torch.float32)  # 批次大小,通道数,长度
for layer in net1D:
    Y=layer(Y)
    print(layer.__class__.__name__, 'output shape: \t',Y.shape)
out 复制代码
Conv1d output shape:      torch.Size([1, 6, 28])
Sigmoid output shape:      torch.Size([1, 6, 28])
AvgPool1d output shape:      torch.Size([1, 6, 14])
Conv1d output shape:      torch.Size([1, 16, 10])
Sigmoid output shape:      torch.Size([1, 16, 10])
AvgPool1d output shape:      torch.Size([1, 16, 5])
Flatten output shape:      torch.Size([1, 80])
Linear output shape:      torch.Size([1, 120])
Sigmoid output shape:      torch.Size([1, 120])
Linear output shape:      torch.Size([1, 84])
Sigmoid output shape:      torch.Size([1, 84])
Linear output shape:      torch.Size([1, 2])
相关推荐
RAOY的AI笔记4 分钟前
ChatGPT账号安全设置教程:MFA、活跃会话、数据导出与异常登录处理
人工智能·安全·chatgpt
水如烟17 分钟前
孤能子视角:华夏“科学”回望·04兵法与治理–––“处”的关系场感知
人工智能
招财小梗19 分钟前
AI矩阵获客,品牌连锁落地方案揭秘
大数据·人工智能·矩阵
m4Rk_31 分钟前
【论文阅读】Agent 记忆机制(47):Nemori——用“预测误差”判断什么经验值得被记住
论文阅读·人工智能·学习·开源·github
230万光年的思念36 分钟前
分子动力学模拟参考文献
python
源码学社39 分钟前
股市复盘Skills全流程资料包:从手工复盘到AI赋能的进阶指南
人工智能·skills·股市复盘·股市复盘skills
hyuk的AI工坊42 分钟前
流式对话实战:LangChain4j + SSE 打字机效果全链路指南
人工智能
白色机械键盘1 小时前
领域大模型微调数据集构建实战
大数据·人工智能
极客互动API1 小时前
企业微信 iPad 协议服务搭建与 AI 回调实战
网络·汇编·人工智能·微信·企业微信·ipad
空堂与归1 小时前
token畅享?FreeToken单卡5090跑满血DeepSeek_V4Flash
人工智能·free token