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])
相关推荐
GitCode官方6 分钟前
开源鸿蒙跨平台直播|AI 时代,用 cj-tauri 开发鸿蒙 PC 应用
人工智能·华为·harmonyos·atomgit
老金带你玩AI36 分钟前
GPT-6.2更强更便宜了,为什么还有人骂?
人工智能
Thanks_ks44 分钟前
Python 的垃圾回收——引用计数撑起日常,分代回收收拾残局
python·内存管理·垃圾回收·循环引用·引用计数·gc 模块·weakref
CyrusYiVPP1 小时前
实测 uv 0.13.7:同一套包,pip 装 94 秒,它只用 19 秒
人工智能·python
泯泷1 小时前
OpenClaw 退潮背后,是 AI 圈“技术自嗨”的终结
人工智能·chatgpt·llm
罗西的思考1 小时前
【轻量化复刻大模型 / KIMI K3】Muon 优化器及 训练系统
人工智能·算法·机器学习
屿华AI1 小时前
AUTOSAR 实战-诊断工具 | 用 Claude Code 开发诊断测试工具:AI 协作开发实践
人工智能·测试工具
yiangL_1 小时前
Python 学习笔记:递归、turtle绘图、字符串与函数
笔记·python·学习
程序员韩星2 小时前
OpenAI 兼容接口返回 404,先查请求地址,再查模型名
前端·人工智能·http
Cosolar2 小时前
2026 年 Java AI Agent 生态全景盘点:50+ Java 开源项目的分类、实测与选型判断
人工智能·架构·agent