How to read individual layers' weight & bias values from ONNX model?

Viewed 4968

How to get weight/bias matrix values from ONNX model, I can currently get the inputs, Kernel size, stride and pad values from model.onnx. I load the model and then read the graph nodes to get the same:

import onnx
m = onnx.load('model.onnx')
print(m.graph.node)
3 Answers
from onnx import numpy_helper
MODEL_PATH = "....../resnet50"
_model = onnx.load(MODEL_PATH + "/model.onnx")
INTIALIZERS=_model.graph.initializer
Weight=[]
for initializer in INTIALIZERS:
    W= numpy_helper.to_array(initializer)
    Weight.append(W)

After posting an issue on official git repo, I got the answer to the question. We can access the weight values from initializers in m.graph.

weights = m.graph.initializer

To get the weight matrix, you need to use numpy_helper from onnx.

from onnx import numpy_helper
w1 = numpy_helper.to_array(weights[0])

The following code helps you to create a state dictionary from onnx model.

import onnx
from onnx import numpy_helper
onnx_model   = onnx.load("model.onnx")
INTIALIZERS  = onnx_model.graph.initializer
onnx_weights = {}
for initializer in INTIALIZERS:
    W = numpy_helper.to_array(initializer)
    onnx_weights[initializer.name] = W
Related