0

I am trying to experiment with this code but it does't work.

import keras.backend as K
import tensorflow as tf
def _cohen_kappa(y_true, y_pred, num_classes, weights=None, metrics_collections=None, updates_collections=None, name=None):
    kappa, update_op = tf.contrib.metrics.cohen_kappa(y_true, y_pred, num_classes, weights, metrics_collections, updates_collections, name)
    K.get_session().run(tf.local_variables_initializer())
    with tf.control_dependencies([update_op]):
        kappa = tf.identity(kappa)
    return kappa

labels = tf.constant([1,0,0,1],name = 'labels')
predictions_idx = tf.constant([1,0,0,1],name = 'predictions_idx')

init = tf.group(tf.global_variables_initializer(), tf.local_variables_initializer())


loss = _cohen_kappa(labels,predictions_idx,2)

with tf.Session() as session:                    # Create a session and print the output
    session.run(init)                            # Initializes the variables
    print(session.run(loss)) 

Error

FailedPreconditionError: 2 root error(s) found.
  (0) Failed precondition: Attempting to use uninitialized value cohen_kappa_1/po
     [[{{node cohen_kappa_1/po/read}}]]
     [[cohen_kappa_1/counts_in_table/Cast_3/_5]]
  (1) Failed precondition: Attempting to use uninitialized value cohen_kappa_1/po
     [[{{node cohen_kappa_1/po/read}}]]
0 successful operations.
0 derived errors ignored.
Rajan Sharma
  • 2,211
  • 3
  • 21
  • 33

1 Answers1

0

You are getting that error because you are not calling the loss function in the session where you are initializing tf variables. Try this. It should work:

import keras.backend as K
import tensorflow as tf
def _cohen_kappa(y_true, y_pred, num_classes, weights=None, metrics_collections=None, updates_collections=None, name=None):
    kappa, update_op = tf.contrib.metrics.cohen_kappa(y_true, y_pred, num_classes, weights, metrics_collections, updates_collections, name)
    K.get_session().run(tf.local_variables_initializer())
    with tf.control_dependencies([update_op]):
        kappa = tf.identity(kappa)
    return kappa

labels = tf.constant([1,0,0,1],name = 'labels')
predictions_idx = tf.constant([1,0,0,1],name = 'predictions_idx')

with tf.Session() as session:                # Create a session and print the output
    loss = _cohen_kappa(labels,predictions_idx,2)
    init = tf.group(tf.global_variables_initializer(), tf.local_variables_initializer())
    session.run(init)                            # Initializes the variables
    print(session.run(loss))