python-pytorch 如何使用python库Netron查看模型结构(以pytorch官网模型为例)0.9.2

Netron查看模型结构

  • 2024年4月27日14:32:30----0.9.2

参照模型

以pytorch官网的tutorial为观察对象,链接是https://pytorch.org/tutorials/intermediate/char_rnn_classification_tutorial.html

模型代码如下

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

class RNN(nn.Module):
    def __init__(self, input_size, hidden_size, output_size):
        super(RNN, self).__init__()

        self.hidden_size = hidden_size

        self.i2h = nn.Linear(input_size, hidden_size)
        self.h2h = nn.Linear(hidden_size, hidden_size)
        self.h2o = nn.Linear(hidden_size, output_size)
        self.softmax = nn.LogSoftmax(dim=1)

    def forward(self, input, hidden):
        hidden = F.tanh(self.i2h(input) + self.h2h(hidden))
        output = self.h2o(hidden)
        output = self.softmax(output)
        return output, hidden

    def initHidden(self):
        return torch.zeros(1, self.hidden_size)

n_hidden = 128
rnn = RNN(n_letters, n_hidden, n_categories)

安装Netron

pip install netron即可

其他安装方式参考链接

https://blog.csdn.net/m0_49963403/article/details/136242313

写netron代码

随便找一个地方打个点,如sample方法中

python 复制代码
import netron
max_length = 20

# Sample from a category and starting letter
def sample(category, start_letter='A'):
    with torch.no_grad():  # no need to track history in sampling
        category_tensor = categoryTensor(category)
        input = inputTensor(start_letter)
        hidden = rnn.initHidden()

        output_name = start_letter

        for i in range(max_length):
#             print("category_tensor",category_tensor.size())
#             print("input[0]",input[0].size())
#             print("hidden",hidden.size())
            
            output, hidden = rnn(category_tensor, input[0], hidden)
            torch.onnx.export(rnn,(category_tensor, input[0], hidden) , f='AlexNet1.onnx')   #导出 .onnx 文件
            netron.start('AlexNet1.onnx') #展示结构图
        
            break
#             print("output",output.size())
#             print("hidden",hidden.size())
#             print("====================")
        
            topv, topi = output.topk(1)
            topi = topi[0][0]
            if topi == n_letters - 1:
                break
            else:
                letter = all_letters[topi]
                output_name += letter
            input = inputTensor(letter)

        return output_name

# Get multiple samples from one category and multiple starting letters
def samples(category, start_letters='ABC'):
    for start_letter in start_letters:
        print(sample(category, start_letter))
        break

samples('Russian', 'RUS')

运行查看结果

结果是在浏览器中,运行成功后会显示:

Serving 'AlexNet.onnx' at http://localhost:8080

打开这个网页就可以看见模型结构,如下图

需要关注的地方

  1. 关于参数
    如果模型是一个参数的情况下,如下使用就可以了
python 复制代码
import torch
from torchvision.models import AlexNet
import netron
model = AlexNet()
input = torch.ones((1,3,224,224))
torch.onnx.export(model, input, f='AlexNet.onnx')
netron.start('AlexNet.onnx')

如果模型有多个参数的情况下,则需要如下用括号括起来,如本文中的例子

python 复制代码
torch.onnx.export(rnn,(category_tensor, input[0], hidden) , f='AlexNet1.onnx')   #导出 .onnx 文件
netron.start('AlexNet1.onnx') #展示结构图
  1. 如果运行过程中发现报错找不到模型
    有可能是你手动删除了生成的模型,最好的方法是重新生成这个模型,再运行
相关推荐
jz_ddk5 分钟前
[学习] C语言数学库函数背后的故事:`double erf(double x)`
c语言·开发语言·学习
萧曵 丶15 分钟前
Rust 所有权系统:深入浅出指南
开发语言·后端·rust
xiaolang_8616_wjl20 分钟前
c++文字游戏_闯关打怪2.0(开源)
开发语言·c++·开源
收破烂的小熊猫~28 分钟前
《Java修仙传:从凡胎到码帝》第四章:设计模式破万法
java·开发语言·设计模式
蹦蹦跳跳真可爱5891 小时前
Python----OpenCV(图像増强——高通滤波(索贝尔算子、沙尔算子、拉普拉斯算子),图像浮雕与特效处理)
人工智能·python·opencv·计算机视觉
nananaij1 小时前
【Python进阶篇 面向对象程序设计(3) 继承】
开发语言·python·神经网络·pycharm
雷羿 LexChien1 小时前
从 Prompt 管理到人格稳定:探索 Cursor AI 编辑器如何赋能 Prompt 工程与人格风格设计(上)
人工智能·python·llm·编辑器·prompt
阿蒙Amon1 小时前
为什么 12 版仍封神?《C# 高级编程》:从.NET 5 到实战架构,进阶者绕不开的必修课
开发语言·c#
无小道1 小时前
c++-引用(包括完美转发,移动构造,万能引用)
c语言·开发语言·汇编·c++