且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在 TensorFlow 中重命名已保存模型的变量范围

更新时间:2023-12-02 19:07:28

您可以使用 tf.contrib.framework.list_variablestf.contrib.framework.load_variable 如下实现你的目标:

You can use tf.contrib.framework.list_variables and tf.contrib.framework.load_variable as follows to achieve your goal :

with tf.Graph().as_default(), tf.Session().as_default() as sess:
  with tf.variable_scope('my-first-scope'):
    NUM_IMAGE_PIXELS = 784
    NUM_CLASS_BINS = 10
    x = tf.placeholder(tf.float32, shape=[None, NUM_IMAGE_PIXELS])
    y_ = tf.placeholder(tf.float32, shape=[None, NUM_CLASS_BINS])

    W = tf.Variable(tf.zeros([NUM_IMAGE_PIXELS,NUM_CLASS_BINS]))
    b = tf.Variable(tf.zeros([NUM_CLASS_BINS]))

    y = tf.nn.softmax(tf.matmul(x,W) + b)
    cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y), reduction_indices=[1]))
    saver = tf.train.Saver([W, b])
  sess.run(tf.global_variables_initializer())
  saver.save(sess, 'my-model')

vars = tf.contrib.framework.list_variables('.')
with tf.Graph().as_default(), tf.Session().as_default() as sess:

  new_vars = []
  for name, shape in vars:
    v = tf.contrib.framework.load_variable('.', name)
    new_vars.append(tf.Variable(v, name=name.replace('my-first-scope', 'my-second-scope')))

  saver = tf.train.Saver(new_vars)
  sess.run(tf.global_variables_initializer())
  saver.save(sess, 'my-new-model')