Skip to content
Advertisement

Unable to convert tensorflow.python.framework.ops.Tensor object to numpy array for passoing it in sklearn.metrics.cohen_kappa_score function

I thought of implementing kappaScore metrics using sklearn.metrics.cohen_kappa_score

JavaScript

Error I get when I try to run this code:

JavaScript

Here the type of y_true and y_pred requires to be in list or numpy array

But the type of y_true and y_pred are,

JavaScript

When directly try to print it (i.e, without type() function), it shows like this:

JavaScript

Unable to use y_true.numpy() (Convert a tensor to numpy array in Tensorflow?) and tf.make_ndarray(y_true) (https://www.tensorflow.org/api_docs/python/tf/make_ndarray#:~:text=tf.make_ndarray(proto_tensor)) tried it..

How can I convert these datatypes in a way that, it can be passed to sklearn.metrics.cohen_kappa_score function? I don’t want to write a code for kappa score. Is it possible to convert?

Advertisement

Answer

There’s a way to solve this problem wrapping cohen_kappa_score in tf.py_function. It’s available in tensorflow 2.x, but I don’t know since which version of framework; py_function does all heavy lifting for you, wrapping a Python function into a TensorFlow operation that executes it eagerly.

JavaScript

First, define cohen_kappa_score_wrapper. It’s important, because last dense layer usually returns an array of probabilities of each class for each sample. But Cohen kappa score accepts integer labels of classes, so one has to convert probabilities into labels with np.argmax(). We’re still on the Python’s territory, so could just use numpy functions.

Then wrap cohen_kappa_score_wrapper with py_function: see kappaScore.

Complete example using MNIST:

JavaScript
JavaScript

Note Despite the docs states that wrapped function executes eagerly, it still works for me if I turn off eager execution: tf.compat.v1.disable_eager_execution(). I use tf2.7. But I’m not so confident about other versions of the framework/different environments. It could be tricky sometimes. Also, if you use tf1.x, it could be a different story.

Advertisement