tf.train.import_meta_graph():无法加载某些变量值

时间:2018-08-29 17:17:48

标签: python tensorflow

我正在使用tensorflow 1.10.0。我一直遵循tutorial来保存和加载简单的经过训练的MLP模型。保存数据可以完美地完成并创建以下文件:

  • train.ckpt.data-00000-of-00001
  • train.ckpt.index
  • train.ckpt.meta

当我尝试使用以下方法加载train_optaccmetric变量时:

import tensorflow as tf

with tf.Session() as sess:
    load_mod = tf.train.import_meta_graph('/home/akshay/train.ckpt.meta')
    load_mod.restore(sess, tf.train.latest_checkpoint('/home/akshay/'))
    print (tf.get_default_graph().get_tensor_by_name('train_opt:0'))

我收到以下错误:

Traceback (most recent call last):
File "recover_tftrain.py", line 6, in <module>
print (tf.get_default_graph().get_tensor_by_name('accmetric:0'))
File "/home/arpita/anaconda2/lib/python2.7/site- 
packages/tensorflow/python/framework/ops.py", line 3515, in get_tensor_by_name
return self.as_graph_element(name, allow_tensor=True, allow_operation=False)
File "/home/arpita/anaconda2/lib/python2.7/site- 
packages/tensorflow/python/framework/ops.py", line 3339, in as_graph_element
return self._as_graph_element_locked(obj, allow_tensor, allow_operation)
File "/home/arpita/anaconda2/lib/python2.7/site-packages/tensorflow/python/framework/ops.py", line 3381, in _as_graph_element_locked
"graph." % (repr(name), repr(op_name)))
KeyError: "The name 'accmetric:0' refers to a Tensor which does not exist. 
The operation, 'accmetric', does not exist in the graph."

但是,损失变量可以完美加载:

Tensor("loss:0", shape=(), dtype=float32)

仅可以加载某些特定变量吗?还是有范围问题?

完整代码:

from create_batches import Batch
import extractData
import tensorflow as tf

# prepare input data and output labels for neural network
datafile = '/home/akshay/Desktop/datafile.csv'
labelfile = '/home/akshay/Desktop/labelfile.csv'

num_input = 2000
num_hidden1 = 200
num_hidden2 = 200
num_hidden3 = 200
num_output = 25
batch_size = 200
epochs = 25

batch = Batch(extractData.create_data(datafile), extractData.create_labels(labelfile), batch_size)

# create tensorflow networks
vowel_inp = tf.placeholder(dtype = tf.float32, shape = [None, 40000], name = "text_inp")
label_oup = tf.placeholder(dtype = tf.int32, shape = [None], name = "label_oup")

vowel_flat = tf.contrib.layers.flatten(vowel_inp)

# fully connected layers
hidden_1 = tf.layers.dense(inputs = vowel_flat, units = num_hidden1, name = "hidden1", activation = tf.nn.sigmoid)
hidden_2 = tf.layers.dense(inputs = hidden_1, units = num_hidden2, name = "hidden2", activation = tf.nn.sigmoid)
hidden_3 = tf.layers.dense(inputs = hidden_2, units = num_hidden3, name = "hidden3", activation = tf.nn.sigmoid)
train_oup = tf.layers.dense(inputs = hidden_3, units = num_output, name = "output")

# define a cost function
xentropy = tf.losses.sparse_softmax_cross_entropy(labels = label_oup, logits = train_oup)

# define a loss function
loss = tf.reduce_mean(xentropy, name = "loss")

# define an optimizer
train_opt = tf.train.AdagradOptimizer(learning_rate = 0.001).minimize(loss, name="train_opt")

# define accuracy metric
acc, acc_metric_update = tf.metrics.accuracy(label_oup, tf.argmax(train_oup, 1), name="accmetric")
loss_val, acc_val = 0, 0
sess = tf.Session()
sess.run(tf.local_variables_initializer())
sess.run(tf.global_variables_initializer())

saver = tf.train.Saver()

for j in range(epochs):
        batch.reset()
        for i in range(int(2000/batch_size)):
                x, y = batch.getBatch()
                y = y.reshape(batch_size)
                feed_dict = {vowel_inp: x, label_oup: y}
                loss_val, _, acc_val = sess.run([loss, train_opt, acc_metric_update], feed_dict=feed_dict)

        if j%25==0:
                print ('Epoch:', j, 'Accuracy Val:', acc_val)

print ("Final score:",sess.run(acc))

#save the model
print ('Model saved in: ', saver.save(sess, '/home/akshay/train.ckpt'))

sess.close()

0 个答案:

没有答案