3

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)
25b3nk
  • 164
  • 2
  • 16

3 Answers3

6
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)
2

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
1

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])
25b3nk
  • 164
  • 2
  • 16