利用python构建ONNX网络

2024-06-16 19:36
文章标签 python 构建 网络 onnx

本文主要是介绍利用python构建ONNX网络,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

利用python构建ONNX网络

利用python的API,构建一个简单的神经网络。
Y = f ( X , A , B ) Y = f(X, A, B) Y=f(X,A,B)

上述网络需要四个函数进行构建

  • make_tensor_value_info: declares a variable (input or output) given its shape and type,声明变量

  • make_node: creates a node defined by an operation (an operator type), its inputs and outputs。构建节点(算子类型)

  • make_graph: a function to create an ONNX graph with the objects created by the two previous functions。利用变量以及算子构建计算图

  • make_model: a last function which merges the graph and additional metadata。将计算图和一些额外的元数据构成一个完整的模型

例子

# importsfrom onnx import TensorProto
from onnx.helper import (make_model, make_node, make_graph,make_tensor_value_info)
from onnx.checker import check_model# inputs# 'X' is the name, TensorProto.FLOAT the type, [None, None] the shape
X = make_tensor_value_info('X', TensorProto.FLOAT, [None, None])
A = make_tensor_value_info('A', TensorProto.FLOAT, [None, None])
B = make_tensor_value_info('B', TensorProto.FLOAT, [None, None])# outputs, the shape is left undefinedY = make_tensor_value_info('Y', TensorProto.FLOAT, [None])# nodes# It creates a node defined by the operator type MatMul,
# 'X', 'A' are the inputs of the node, 'XA' the output.
node1 = make_node('MatMul', ['X', 'A'], ['XA'])
node2 = make_node('Add', ['XA', 'B'], ['Y'])# from nodes to graph
# the graph is built from the list of nodes, the list of inputs,
# the list of outputs and a name.graph = make_graph([node1, node2],  # nodes'lr',  # a name[X, A, B],  # inputs[Y])  # outputs# onnx graph
# there is no metadata in this case.onnx_model = make_model(graph)# Let's check the model is consistent,
# this function is described in section
# Checker and Shape Inference.
check_model(onnx_model)# the work is done, let's display it...
print(onnx_model)

空的形状None表示任意大小

序列化

保存

# The serialization
with open("linear_regression.onnx", "wb") as f:f.write(onnx_model.SerializeToString())

加载

from onnx import loadwith open("linear_regression.onnx", "rb") as f:onnx_model = load(f)# display
print(onnx_model)

数据的序列化

import numpy
from onnx.numpy_helper import from_arraynumpy_tensor = numpy.array([0, 1, 4, 5, 3], dtype=numpy.float32)
print(type(numpy_tensor))onnx_tensor = from_array(numpy_tensor)
print(type(onnx_tensor))serialized_tensor = onnx_tensor.SerializeToString()
print(type(serialized_tensor))with open("saved_tensor.pb", "wb") as f:f.write(serialized_tensor)

Initializer,为输入构建默认值

前面的模型将系数也做为模型的输入,这在使用时不便。

代码

import numpy
from onnx import numpy_helper, TensorProto
from onnx.helper import (make_model, make_node, make_graph,make_tensor_value_info)
from onnx.checker import check_model# initializers
value = numpy.array([0.5, -0.6], dtype=numpy.float32)
A = numpy_helper.from_array(value, name='A')value = numpy.array([0.4], dtype=numpy.float32)
C = numpy_helper.from_array(value, name='C')# the part which does not change
X = make_tensor_value_info('X', TensorProto.FLOAT, [None, None])
Y = make_tensor_value_info('Y', TensorProto.FLOAT, [None])
node1 = make_node('MatMul', ['X', 'A'], ['AX'])
node2 = make_node('Add', ['AX', 'C'], ['Y'])
graph = make_graph([node1, node2], 'lr', [X], [Y], [A, C])
onnx_model = make_model(graph)
check_model(onnx_model)print(onnx_model)

属性

from onnx import TensorProto
from onnx.helper import (make_model, make_node, make_graph,make_tensor_value_info)
from onnx.checker import check_model# unchanged
X = make_tensor_value_info('X', TensorProto.FLOAT, [None, None])
A = make_tensor_value_info('A', TensorProto.FLOAT, [None, None])
B = make_tensor_value_info('B', TensorProto.FLOAT, [None, None])
Y = make_tensor_value_info('Y', TensorProto.FLOAT, [None])# added
node_transpose = make_node('Transpose', ['A'], ['tA'], perm=[1, 0])# unchanged except A is replaced by tA
node1 = make_node('MatMul', ['X', 'tA'], ['XA'])
node2 = make_node('Add', ['XA', 'B'], ['Y'])# node_transpose is added to the list
graph = make_graph([node_transpose, node1, node2],'lr', [X, A, B], [Y])
onnx_model = make_model(graph)
check_model(onnx_model)# the work is done, let's display it...
print(onnx_model)

版本和元数据

from onnx import load, helperwith open("linear_regression.onnx", "rb") as f:onnx_model = load(f)onnx_model.model_version = 15
onnx_model.producer_name = "something"
onnx_model.producer_version = "some other thing"
onnx_model.doc_string = "documentation about this model"
prop = onnx_model.metadata_propsdata = dict(key1="value1", key2="value2")
helper.set_model_props(onnx_model, data)print(onnx_model)

Functions

定义一个函数,相比于计算图,更像一个模板

import numpy
from onnx import numpy_helper, TensorProto
from onnx.helper import (make_model, make_node, set_model_props, make_tensor,make_graph, make_tensor_value_info, make_opsetid,make_function)
from onnx.checker import check_modelnew_domain = 'custom'
opset_imports = [make_opsetid("", 14), make_opsetid(new_domain, 1)]# Let's define a function for a linear regressionnode1 = make_node('MatMul', ['X', 'A'], ['XA'])
node2 = make_node('Add', ['XA', 'B'], ['Y'])linear_regression = make_function(new_domain,            # domain name'LinearRegression',     # function name['X', 'A', 'B'],        # input names['Y'],                  # output names[node1, node2],         # nodesopset_imports,          # opsets[])                     # attribute names# Let's use it in a graph.X = make_tensor_value_info('X', TensorProto.FLOAT, [None, None])
A = make_tensor_value_info('A', TensorProto.FLOAT, [None, None])
B = make_tensor_value_info('B', TensorProto.FLOAT, [None, None])
Y = make_tensor_value_info('Y', TensorProto.FLOAT, [None])graph = make_graph([make_node('LinearRegression', ['X', 'A', 'B'], ['Y1'], domain=new_domain),make_node('Abs', ['Y1'], ['Y'])],'example',[X, A, B], [Y])onnx_model = make_model(graph, opset_imports=opset_imports,functions=[linear_regression])  # functions to add)
check_model(onnx_model)# the work is done, let's display it...
print(onnx_model)

带属性的function

import numpy
from onnx import numpy_helper, TensorProto, AttributeProto
from onnx.helper import (make_model, make_node, set_model_props, make_tensor,make_graph, make_tensor_value_info, make_opsetid,make_function)
from onnx.checker import check_modelnew_domain = 'custom'
opset_imports = [make_opsetid("", 14), make_opsetid(new_domain, 1)]# Let's define a function for a linear regression
# The first step consists in creating a constant
# equal to the input parameter of the function.
cst = make_node('Constant',  [], ['B'])att = AttributeProto()
att.name = "value"# This line indicates the value comes from the argument
# named 'bias' the function is given.
att.ref_attr_name = "bias"
att.type = AttributeProto.TENSOR
cst.attribute.append(att)node1 = make_node('MatMul', ['X', 'A'], ['XA'])
node2 = make_node('Add', ['XA', 'B'], ['Y'])linear_regression = make_function(new_domain,            # domain name'LinearRegression',     # function name['X', 'A'],             # input names['Y'],                  # output names[cst, node1, node2],    # nodesopset_imports,          # opsets["bias"])               # attribute names# Let's use it in a graph.X = make_tensor_value_info('X', TensorProto.FLOAT, [None, None])
A = make_tensor_value_info('A', TensorProto.FLOAT, [None, None])
B = make_tensor_value_info('B', TensorProto.FLOAT, [None, None])
Y = make_tensor_value_info('Y', TensorProto.FLOAT, [None])graph = make_graph([make_node('LinearRegression', ['X', 'A'], ['Y1'], domain=new_domain,# bias is now an argument of the function and is defined as a tensorbias=make_tensor('former_B', TensorProto.FLOAT, [1], [0.67])),make_node('Abs', ['Y1'], ['Y'])],'example',[X, A], [Y])onnx_model = make_model(graph, opset_imports=opset_imports,functions=[linear_regression])  # functions to add)
check_model(onnx_model)# the work is done, let's display it...
print(onnx_model)

Parsing

模型的检验

import onnx.parser
import onnx.checkerinput = '''<ir_version: 8,opset_import: [ "" : 15]>agraph (float[I,4] X, float[4,2] A, int[4] B) => (float[I] Y) {XA = MatMul(X, A)Y = Add(XA, B)}'''
try:onnx_model = onnx.parser.parse_model(input)onnx.checker.check_model(onnx_model)
except Exception as e:print(e)

形状推断

import onnx.parser
from onnx import helper, shape_inferenceinput = '''<ir_version: 8,opset_import: [ "" : 15]>agraph (float[I,4] X, float[4,2] A, float[4] B) => (float[I] Y) {XA = MatMul(X, A)Y = Add(XA, B)}'''
onnx_model = onnx.parser.parse_model(input)
inferred_model = shape_inference.infer_shapes(onnx_model)print(inferred_model)

这篇关于利用python构建ONNX网络的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1067350

相关文章

python: 多模块(.py)中全局变量的导入

文章目录 global关键字可变类型和不可变类型数据的内存地址单模块(单个py文件)的全局变量示例总结 多模块(多个py文件)的全局变量from x import x导入全局变量示例 import x导入全局变量示例 总结 global关键字 global 的作用范围是模块(.py)级别: 当你在一个模块(文件)中使用 global 声明变量时,这个变量只在该模块的全局命名空

嵌入式QT开发:构建高效智能的嵌入式系统

摘要: 本文深入探讨了嵌入式 QT 相关的各个方面。从 QT 框架的基础架构和核心概念出发,详细阐述了其在嵌入式环境中的优势与特点。文中分析了嵌入式 QT 的开发环境搭建过程,包括交叉编译工具链的配置等关键步骤。进一步探讨了嵌入式 QT 的界面设计与开发,涵盖了从基本控件的使用到复杂界面布局的构建。同时也深入研究了信号与槽机制在嵌入式系统中的应用,以及嵌入式 QT 与硬件设备的交互,包括输入输出设

Linux 网络编程 --- 应用层

一、自定义协议和序列化反序列化 代码: 序列化反序列化实现网络版本计算器 二、HTTP协议 1、谈两个简单的预备知识 https://www.baidu.com/ --- 域名 --- 域名解析 --- IP地址 http的端口号为80端口,https的端口号为443 url为统一资源定位符。CSDNhttps://mp.csdn.net/mp_blog/creation/editor

【Python编程】Linux创建虚拟环境并配置与notebook相连接

1.创建 使用 venv 创建虚拟环境。例如,在当前目录下创建一个名为 myenv 的虚拟环境: python3 -m venv myenv 2.激活 激活虚拟环境使其成为当前终端会话的活动环境。运行: source myenv/bin/activate 3.与notebook连接 在虚拟环境中,使用 pip 安装 Jupyter 和 ipykernel: pip instal

Retrieval-based-Voice-Conversion-WebUI模型构建指南

一、模型介绍 Retrieval-based-Voice-Conversion-WebUI(简称 RVC)模型是一个基于 VITS(Variational Inference with adversarial learning for end-to-end Text-to-Speech)的简单易用的语音转换框架。 具有以下特点 简单易用:RVC 模型通过简单易用的网页界面,使得用户无需深入了

【机器学习】高斯过程的基本概念和应用领域以及在python中的实例

引言 高斯过程(Gaussian Process,简称GP)是一种概率模型,用于描述一组随机变量的联合概率分布,其中任何一个有限维度的子集都具有高斯分布 文章目录 引言一、高斯过程1.1 基本定义1.1.1 随机过程1.1.2 高斯分布 1.2 高斯过程的特性1.2.1 联合高斯性1.2.2 均值函数1.2.3 协方差函数(或核函数) 1.3 核函数1.4 高斯过程回归(Gauss

ASIO网络调试助手之一:简介

多年前,写过几篇《Boost.Asio C++网络编程》的学习文章,一直没机会实践。最近项目中用到了Asio,于是抽空写了个网络调试助手。 开发环境: Win10 Qt5.12.6 + Asio(standalone) + spdlog 支持协议: UDP + TCP Client + TCP Server 独立的Asio(http://www.think-async.com)只包含了头文件,不依

【学习笔记】 陈强-机器学习-Python-Ch15 人工神经网络(1)sklearn

系列文章目录 监督学习:参数方法 【学习笔记】 陈强-机器学习-Python-Ch4 线性回归 【学习笔记】 陈强-机器学习-Python-Ch5 逻辑回归 【课后题练习】 陈强-机器学习-Python-Ch5 逻辑回归(SAheart.csv) 【学习笔记】 陈强-机器学习-Python-Ch6 多项逻辑回归 【学习笔记 及 课后题练习】 陈强-机器学习-Python-Ch7 判别分析 【学

poj 3181 网络流,建图。

题意: 农夫约翰为他的牛准备了F种食物和D种饮料。 每头牛都有各自喜欢的食物和饮料,而每种食物和饮料都只能分配给一头牛。 问最多能有多少头牛可以同时得到喜欢的食物和饮料。 解析: 由于要同时得到喜欢的食物和饮料,所以网络流建图的时候要把牛拆点了。 如下建图: s -> 食物 -> 牛1 -> 牛2 -> 饮料 -> t 所以分配一下点: s  =  0, 牛1= 1~

nudepy,一个有趣的 Python 库!

更多资料获取 📚 个人网站:ipengtao.com 大家好,今天为大家分享一个有趣的 Python 库 - nudepy。 Github地址:https://github.com/hhatto/nude.py 在图像处理和计算机视觉应用中,检测图像中的不适当内容(例如裸露图像)是一个重要的任务。nudepy 是一个基于 Python 的库,专门用于检测图像中的不适当内容。该