Skip to content

Commit

Permalink
add a tool to extract weights from tf models
Browse files Browse the repository at this point in the history
  • Loading branch information
qfgaohao committed Jun 18, 2018
1 parent b1f1fb0 commit 7749c62
Showing 1 changed file with 31 additions and 0 deletions.
31 changes: 31 additions & 0 deletions extract_tf_weights.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import tensorflow as tf
from tensorflow.python.platform import gfile
from tensorflow.python.framework import tensor_util
import sys
import pickle


def read_weights(frozen_model):
weights = {}
with tf.Session() as sess:
with gfile.FastGFile(frozen_model, 'rb') as f:
graph_def = tf.GraphDef()
graph_def.ParseFromString(f.read())
tf.import_graph_def(graph_def)
for n in graph_def.node:
if n.op == 'Const':
weights[n.name] = tensor_util.MakeNdarray(n.attr['value'].tensor)
print("Name:", n.name, "Shape:", weights[n.name].shape)
return weights


if len(sys.argv) < 3:
print("Usage: python extract_tf_weights.py <frozen_model.pb> <weights_file.pickle>")

frozen_model = sys.argv[1]
weights_file = sys.argv[2]

weights = read_weights(frozen_model)
with open(weights_file, "wb") as f:
pickle.dump(weights, f)
print(f"Saved weights to {weights_file}.")

0 comments on commit 7749c62

Please sign in to comment.