Jump to content

Connect Leeroopedia MCP: Equip your AI agents to search best practices, build plans, verify code, diagnose failures, and look up hyperparameter defaults.

Implementation:Onnx Onnx Numpy Helper Conversion

From Leeroopedia


Knowledge Sources
Domains Data_Conversion, Tensor_Operations
Last Updated 2026-02-10 00:00 GMT

Overview

Concrete tool for converting between NumPy arrays and ONNX TensorProto objects provided by the ONNX numpy_helper module.

Description

The from_array function converts a NumPy array to a TensorProto protobuf, and to_array converts a TensorProto back to a NumPy array. These functions handle all ONNX data types, including standard types (float32, float64, int32, int64), low-precision types (float16, bfloat16), and extended types (float8e4m3fn, float8e5m2 via ml_dtypes). The to_array function also supports loading data from external files when the tensor uses external data storage.

Usage

Import from_array when creating initializer tensors for graph construction, and to_array when extracting tensor data from loaded models for inspection or computation.

Code Reference

Source Location

  • Repository: onnx
  • File: onnx/numpy_helper.py
  • Lines: 306-362 (from_array), 172-283 (to_array)

Signature

def from_array(
    array: np.ndarray,
    /,
    name: str | None = None,
) -> TensorProto:
    """Convert a NumPy array to a TensorProto.

    Args:
        array: NumPy array to convert.
        name: Optional tensor name.

    Returns:
        TensorProto containing the array data.
    """

def to_array(
    tensor: TensorProto,
    base_dir: str = "",
) -> np.ndarray:
    """Convert a TensorProto to a NumPy array.

    Args:
        tensor: TensorProto to convert.
        base_dir: Base directory for external data files.

    Returns:
        NumPy array with the tensor data.
    """

Import

from onnx import numpy_helper

I/O Contract

Inputs (from_array)

Name Type Required Description
array np.ndarray Yes NumPy array to convert
name str or None No Optional tensor name identifier

Outputs (from_array)

Name Type Description
return TensorProto Protobuf tensor with data, shape, and type from the NumPy array

Inputs (to_array)

Name Type Required Description
tensor TensorProto Yes Protobuf tensor to convert
base_dir str No Base directory for external data files (default: "")

Outputs (to_array)

Name Type Description
return np.ndarray NumPy array with tensor data

Usage Examples

Create an Initializer

import numpy as np
from onnx import numpy_helper

# Create weight tensor
weights = np.random.randn(10, 784).astype(np.float32)
tensor_proto = numpy_helper.from_array(weights, name="W")

# Use as initializer in make_graph
# graph = helper.make_graph([...], ..., initializer=[tensor_proto])

Extract Tensor Data

import onnx
from onnx import numpy_helper

model = onnx.load_model("model.onnx")

# Extract all initializer values
for init in model.graph.initializer:
    array = numpy_helper.to_array(init)
    print(f"{init.name}: shape={array.shape}, dtype={array.dtype}")

Related Pages

Implements Principle

Requires Environment

Uses Heuristic

Page Connections

Double-click a node to navigate. Hold to expand connections.
Principle
Implementation
Heuristic
Environment