即使初始化局部变量和全局变量,也尝试使用未初始化的值错误

时间:2018-10-16 07:36:55

标签: python-3.x tensorflow

我正在尝试使用张量流指标来查找召回率和/或精度,这是我的代码:

    print("Starting session...")
    with tf.Session() as sess:
        sess.run(tf.global_variables_initializer())
        sess.run(tf.local_variables_initializer())
        sess.run(train_init_op)
        tot_acc = 0
        print("Starting training...")
        for i in range(num_epochs):
            sample_counter = 0
            l, _, acc = sess.run([loss, optimizer, accuracy], feed_dict={keep_prob: 0.7})
            tot_acc += acc
            print("Epoch: {}, loss: {:.3f}, training accuracy: {:.2f}%".format(i, l, acc * 100))
        print("Average training set accuracy over {} epoch is {:.2f}%".format(num_epochs,
                                                                                    (tot_acc / num_epochs) * 100))

        print("Starting Validation...")
        sess.run(valid_init_op)
        tot_acc = 0
        for i in range(valid_iters):
            acc = sess.run([accuracy], feed_dict={keep_prob: 1.0})
            tot_acc += acc[0]
            print("Iter: {}, validation accuracy: {:.2f}%".format(i, acc[0] * 100))
        print("Average validation set accuracy over {} iterations is {:.2f}%".format(valid_iters,
                                                                           (tot_acc / valid_iters) * 100))
        sess.run(valid_init_op)
        val_img, val_label = next_element
        finalprediction = tf.argmax(train_predict, 1)
        actualprediction = tf.argmax(val_label, 1)
        confusion = tf.confusion_matrix(labels=actualprediction, predictions=finalprediction, 
                                        num_classes=num_classes, dtype=tf.int32, name="Confusion_Matrix")
        recall = tf.metrics.recall(labels=actualprediction, predictions=finalprediction, name="Recall")


        cm = np.zeros([2,2], dtype=int)
        rc = np.zeros([1,2], dtype=int)
        for i in range(valid_iters):
            while True:
                try:
                    conf_matrix = sess.run(confusion, feed_dict={keep_prob: 1.0})
                    rec = sess.run(recall, feed_dict={keep_prob: 1.0})
                    cm += conf_matrix
                    rc += rec
                except tf.errors.OutOfRangeError:
                    print("End of append.")
                break
        print("confusion matrix: ", cm)
        print("Recall: ", rc)

但是每当我得到Attempting to use uninitialized value时,经过一番谷歌搜索之后,我在这里找到了一些答案: TensorFlow: “Attempting to use uninitialized value” in variable initialization 和这里: tensorflow Variable Initialization error : Attempting to use uninitialized value Variable 我做了他们建议的一样的事情,但是没有一个解决我的问题吗?这是错误代码:

FailedPreconditionError: Attempting to use uninitialized value Recall_3/true_positives/count
     [[Node: Recall_3/true_positives/count/read = Identity[T=DT_FLOAT, _class=["loc:@Recall_3/true_positives/AssignAdd"], _device="/job:localhost/replica:0/task:0/device:CPU:0"](Recall_3/true_positives/count)]]

1 个答案:

答案 0 :(得分:1)

您的代码不可运行(它缺少某些变量/操作),但是正如您引用的答案中所解释的那样,您需要先定义图形,然后再初始化图形中的变量。您可能会发现this part of the official doc有用。

    val_img, val_label = next_element
    finalprediction = tf.argmax(train_predict, 1)
    actualprediction = tf.argmax(val_label, 1)
    confusion = tf.confusion_matrix(labels=actualprediction, predictions=finalprediction, 
                                    num_classes=num_classes, dtype=tf.int32, name="Confusion_Matrix")
    recall = tf.metrics.recall(labels=actualprediction, predictions=finalprediction, name="Recall")


print("Starting session...")
with tf.Session() as sess:
    # Notice that the call to the variables initializer is made after the call to
    # to tf.metrics.recall and therefore after the recall variables have been added to the graph.


    sess.run(tf.global_variables_initializer())
    sess.run(tf.local_variables_initializer())
    sess.run(train_init_op)
    tot_acc = 0
    print("Starting training...")
    for i in range(num_epochs):
        sample_counter = 0
        l, _, acc = sess.run([loss, optimizer, accuracy], feed_dict={keep_prob: 0.7})
        tot_acc += acc
        print("Epoch: {}, loss: {:.3f}, training accuracy: {:.2f}%".format(i, l, acc * 100))
    print("Average training set accuracy over {} epoch is {:.2f}%".format(num_epochs,
                                                                                (tot_acc / num_epochs) * 100))

    print("Starting Validation...")
    sess.run(valid_init_op)
    tot_acc = 0
    for i in range(valid_iters):
        acc = sess.run([accuracy], feed_dict={keep_prob: 1.0})
        tot_acc += acc[0]
        print("Iter: {}, validation accuracy: {:.2f}%".format(i, acc[0] * 100))
    print("Average validation set accuracy over {} iterations is {:.2f}%".format(valid_iters,
                                                                       (tot_acc / valid_iters) * 100))
    sess.run(valid_init_op)

    cm = np.zeros([2,2], dtype=int)
    rc = np.zeros([1,2], dtype=int)
    for i in range(valid_iters):
        while True:
            try:
                conf_matrix = sess.run(confusion, feed_dict={keep_prob: 1.0})
                rec = sess.run(recall, feed_dict={keep_prob: 1.0})
                cm += conf_matrix
                rc += rec
            except tf.errors.OutOfRangeError:
                print("End of append.")
            break
    print("confusion matrix: ", cm)
    print("Recall: ", rc)