11

I trained one model and then create one .pb file by freeze that model. so, my question is how to get weights from .pb file or i have to do more process for get weights

@mrry, please guide me.

2
  • Unfortunately I'm not mrry, but freezing a model gets you a GraphDef; you can parse a GraphDef in Python, which will have the values of constants (including your frozen weights). Commented Sep 11, 2017 at 17:34
  • ohk.. thank you so much .. Commented Sep 13, 2017 at 5:10

1 Answer 1

22

Let us first load the graph from .pb file.

import tensorflow as tf
from tensorflow.python.platform import gfile

GRAPH_PB_PATH = './model/tensorflow_inception_v3_stripped_optimized_quantized.pb' #path to your .pb file
with tf.Session(config=config) as sess:
  print("load graph")
  with gfile.FastGFile(GRAPH_PB_PATH,'rb') as f:
    graph_def = tf.GraphDef()
    graph_def.ParseFromString(f.read())
    sess.graph.as_default()
    tf.import_graph_def(graph_def, name='')
    graph_nodes=[n for n in graph_def.node]

Now when you freeze a graph to .pb file your variables are converted to Const type and the weights which were trainabe variables would also be stored as Const in .pb file. graph_nodes contains all the nodes in graph. But we are interested in all the Const type nodes.

wts = [n for n in graph_nodes if n.op=='Const']

Each element of wts is of NodeDef type. It has several atributes such as name, op etc. The values can be extracted as follows -

from tensorflow.python.framework import tensor_util

for n in wts:
    print "Name of the node - %s" % n.name
    print "Value - " 
    print tensor_util.MakeNdarray(n.attr['value'].tensor)

Hope this solves your concern.

Sign up to request clarification or add additional context in comments.

5 Comments

how do i load the pb file then then use it ? like network = load_pb_file(Alexnet.pb) network.run(image)
hello ? What is a pb file ? How can I use it ? I have an AlexNet.pb
@kong Yes, the pb file is the frozen file. Alexnet.pb is the one for you.
graph_def.ParseFromString
sess.graph.as_default()seems not to be needed as when session is opened with with it is automatically set as default one.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.