Hunar
Hunar

Reputation: 399

Attempting to use uninitialized value error even if I initialize local and global variables

I am trying to use tensorflow metrics to find recall and/or precision, here is my code:

    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)

but every time I get Attempting to use uninitialized value, after doing some googling I found some answers in here: TensorFlow: “Attempting to use uninitialized value” in variable initialization and here: tensorflow Variable Initialization error : Attempting to use uninitialized value Variable I did the same as they suggest but none of that solved my problem? here is the error code:

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)]]

Upvotes: 0

Views: 109

Answers (1)

pfm
pfm

Reputation: 6328

Your code is not runnable (it misses some variables/operations), but as explained in the answers you quote, you need to first define your graph before initializing the variables in it. You might find this part of the official doc useful.

    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)

Upvotes: 1

Related Questions