Ошибка «нет переменной для сохранения» в тензорном потоке при сохранении сеанса - PullRequest
0 голосов
/ 27 июня 2018

Я пытался сохранить сеанс в модели, чтобы я мог использовать его позже, но каждый раз получаю сообщение об ошибке. Мой код выглядит так:

with tf.Session() as sess:
    sess.run(init)
    for j in range(3):
        for i in range(xtest.shape[0]):

            _, indices = sess.run(pred, feed_dict={x_train: xtrain, x_test: xtest[i,:]})
            pred_label = getMajorityPredictions(ytrain, indices) 
            actual_val = get_char( int( (ytest[i]).argmax() ) )

            # print("test: ", i, "prediction:       ", get_char(pred_label), "          actual:            ",   actual_val)
            # print(pred_label, actual_val, type(pred_label), type(actual_val), sep=" --> ")
            if get_char(pred_label) == actual_val:
                accuracy += 1/len(xtest)

            # print((i / (xtest.shape[0])) * 100)
            # os.system("cls")
                print("accuracy: ",accuracy)

    savedPath = saver.save(sess, "/tmp/model.ckpt")
    print("Model saved at: " ,savedPath)

и ошибка такая:

Traceback (most recent call last):
File "prac3.py", line 74, in <module>
    saver = tf.train.Saver()
File "C:\Python36\lib\site-packages\tensorflow\python\training\saver.py", line 1239, in __init__
    self.build()
File "C:\Python36\lib\site-packages\tensorflow\python\training\saver.py", line 1248, in build
    self._build(self._filename, build_save=True, build_restore=True)
File "C:\Python36\lib\site-packages\tensorflow\python\training\saver.py", line 1272, in _build
    raise ValueError("No variables to save")
ValueError: No variables to save

Ответы [ 2 ]

0 голосов
/ 27 июня 2018
x_train = tf.placeholder(tf.float32, shape=[None, 4096])           
y_train = tf.placeholder(tf.float32, shape=[None, 62])
x_test = tf.placeholder(tf.float32, shape=[4096])           
y_test = tf.placeholder(tf.float32, shape=[None, 62])

l1_distance = tf.abs(tf.subtract(x_train, x_test))
dis_l1 = tf.reduce_sum(l1_distance, axis=1)
pred = tf.nn.top_k(tf.negative(dis_l1), k=5)

xtrain, ytrain = TRAIN_SIZE(2852)
xtest, ytest = TEST_SIZE(557)

init = tf.global_variables_initializer()
accuracy = 0
saver = tf.train.Saver()
# --------------------- to create model 
with tf.Session() as sess:
    sess.run(init)
    for j in range(3):
        for i in range(xtest.shape[0]):

            _, indices = sess.run(pred, feed_dict={x_train: xtrain, x_test: xtest[i,:]})
            pred_label = getMajorityPredictions(ytrain, indices) 
            actual_val = get_char( int( (ytest[i]).argmax() ) )

            # print("test: ", i, "prediction:       ", get_char(pred_label), "          actual:            ",   actual_val)
            # print(pred_label, actual_val, type(pred_label), type(actual_val), sep=" --> ")
            if get_char(pred_label) == actual_val:
                accuracy += 1/len(xtest)

            # print((i / (xtest.shape[0])) * 100)
            # os.system("cls")
                print("accuracy: ",accuracy)

    savedPath = saver.save(sess, "/tmp/model.ckpt")
    print("Model saved at: " ,savedPath)
0 голосов
/ 27 июня 2018

Код, который вы указали, не дает много информации об ошибке. Возможно, вам придется проверить предыдущий код, чтобы увидеть, есть ли у вас переменные для сохранения. Вы можете проверить tf.global_variables () и посмотреть, если список пуст.

Кроме того, вы можете захотеть поместить отступ перед сохраненным параметром savePath = saver.save (sess, "/tmp/model.ckpt"), как вы использовали с tf.Session в качестве sess, поэтому сеанс фактически закрывается, когда вы находятся за пределами этого блока, и вы столкнетесь с проблемой «попытки использовать закрытый сеанс».

...