used pretraing model in tensorflow .ckpt file

2019-07-28 21:34发布

问题:

I have a ckpt file . I just want to get the weights of the cnn that I have trained from a ckpt checkpoint file.? inception_resnet_v2_2016_08_30

import tensorflow as tf
saver = tf.train.Saver()
sess = tf.Session()
saver.restore(sess, "inception_resnet_v2_2016_08_30.ckpt")

from tensorflow.core.framework import graph_pb2
from tensorflow.core.protobuf import saver_pb2
from tensorflow.python import pywrap_tensorflow
from tensorflow.python.client import session
from tensorflow.python.framework import graph_util
from tensorflow.python.framework import importer
from tensorflow.python.platform import app
from tensorflow.python.platform import gfile
from tensorflow.python.training import saver as saver_lib
with session.Session() as sess:
var_list = {}
reader =pywrap_tensorflow.NewCheckpointReader("./inception_resnet_v2_2016_08_30.ckpt")
var_to_shape_map = reader.get_variable_to_shape_map()
for key in var_to_shape_map:
    try:
       tensor = sess.graph.get_tensor_by_name(key + ":0")
    except KeyError:
            continue
    var_list[key] = tensor
    saver = saver_lib.Saver(var_list=var_list)
    saver.restore(sess, input_checkpoint)
    if initializer_nodes:
       sess.run(initializer_nodes)

回答1:

The tf.train.Saver.restore() method only works if you have already built the graph structure (including a set of tf.Variable objects) into which the checkpoint will be restored. You have (at least) two options for solving this problem:

  1. Use tf.train.NewCheckpointReader("inception_resnet_v2_2016_08_30.ckpt") to open the checkpoint file. You can call the get_tensor() method on the returned object to look up a saved variable by name, or the get_variable_to_shape_map() method to get a list of the available variables.

  2. If you have one, load a MetaGraph for the checkpointed mode, which includes the graph structure and a mapping from that graph structure to the variables in the checkpoint.