Principle:Onnx Onnx Numpy Tensor Conversion
| Knowledge Sources | |
|---|---|
| Domains | Data_Conversion, Tensor_Operations |
| Last Updated | 2026-02-10 00:00 GMT |
Overview
A bidirectional conversion mechanism between NumPy arrays and ONNX TensorProto objects for data exchange between Python numerical computing and the ONNX model format.
Description
ONNX models store tensor data in the TensorProto protobuf format, while Python-based data processing and model evaluation typically use NumPy arrays. The NumPy tensor conversion utilities provide lossless bidirectional conversion between these two representations, supporting all ONNX data types including standard types (float32, int64), low-precision types (float16, bfloat16), and extended types (float8 variants via the ml_dtypes package).
from_array converts a NumPy array to a TensorProto for use as an initializer or test input, while to_array converts a TensorProto back to a NumPy array for inspection or computation.
Usage
Use these conversions when creating model initializers (weight tensors) from NumPy data, when extracting tensor data from models for analysis, or when preparing input data for the reference evaluator. Note that ReferenceEvaluator.run accepts NumPy arrays directly in its feed dictionary; from_array is primarily used for constructing initializers.
Theoretical Basis
The conversion maps between two tensor representations:
Failed to parse (syntax error): {\displaystyle \text{from\_array}: \text{np.ndarray} \rightarrow \text{TensorProto} } Failed to parse (syntax error): {\displaystyle \text{to\_array}: \text{TensorProto} \rightarrow \text{np.ndarray} }
The conversion preserves:
- Data values (bit-exact for all types)
- Shape information
- Data type (mapped between NumPy dtypes and TensorProto.DataType)