如何解决tf.contrib.metrics.cohen-kappa?

时间:2019-08-02 09:43:20

标签: tensorflow

我正在尝试对此code进行试验,但是它不起作用。

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

错误

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.

1 个答案:

答案 0 :(得分:0)

您收到该错误,是因为您没有在初始化tf变量的会话中调用损失函数。尝试这个。它应该可以工作:

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