简体   繁体   English

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

[英]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我想过使用sklearn.metrics.cohen_kappa_score来实现 kappaScore 指标

def kappaScore(y_true,y_pred):
    k = cohen_kappa_score(y_true,y_pred,weights='quadratic')
    return k

Error I get when I try to run this code:当我尝试运行此代码时出现错误:

OperatorNotAllowedInGraphError: in user code:

    /opt/conda/lib/python3.7/site-packages/keras/engine/training.py:853 train_function  *
        return step_function(self, iterator)
    /tmp/ipykernel_33/1006337667.py:2 kappaScore  *
        k = cohen_kappa_score(y_true,y_pred,weights='quadratic')
    /opt/conda/lib/python3.7/site-packages/sklearn/utils/validation.py:555 inner_f  *
        return f(**kwargs)
    /opt/conda/lib/python3.7/site-packages/sklearn/metrics/_classification.py:600 cohen_kappa_score  *
        confusion = confusion_matrix(y1, y2, labels=labels,
    /opt/conda/lib/python3.7/site-packages/sklearn/utils/validation.py:555 inner_f  *
        return f(**kwargs)
    /opt/conda/lib/python3.7/site-packages/sklearn/metrics/_classification.py:276 confusion_matrix  *
        y_type, y_true, y_pred = _check_targets(y_true, y_pred)
    /opt/conda/lib/python3.7/site-packages/sklearn/metrics/_classification.py:81 _check_targets  *
        check_consistent_length(y_true, y_pred)
    /opt/conda/lib/python3.7/site-packages/sklearn/utils/validation.py:253 check_consistent_length  *
        uniques = np.unique(lengths)
    <__array_function__ internals>:6 unique  **
        
    /opt/conda/lib/python3.7/site-packages/numpy/lib/arraysetops.py:261 unique
        ret = _unique1d(ar, return_index, return_inverse, return_counts)
    /opt/conda/lib/python3.7/site-packages/numpy/lib/arraysetops.py:322 _unique1d
        ar.sort()
    /opt/conda/lib/python3.7/site-packages/tensorflow/python/framework/ops.py:900 __bool__
        self._disallow_bool_casting()
    /opt/conda/lib/python3.7/site-packages/tensorflow/python/framework/ops.py:504 _disallow_bool_casting
        "using a `tf.Tensor` as a Python `bool`")
    /opt/conda/lib/python3.7/site-packages/tensorflow/python/framework/ops.py:491 _disallow_when_autograph_enabled
        " indicate you are trying to use an unsupported feature.".format(task))

    OperatorNotAllowedInGraphError: using a `tf.Tensor` as a Python `bool` is not allowed: AutoGraph did convert this function. This might indicate you are trying to use an unsupported feature.

Here the type of y_true and y_pred requires to be in list or numpy array这里y_truey_pred的类型需要在列表或 numpy 数组中

But the type of y_true and y_pred are,但是y_truey_pred的类型是,

y_true: <class 'tensorflow.python.framework.ops.Tensor'>
y_pred: <class 'tensorflow.python.framework.ops.Tensor'>

When directly try to print it (ie, without type() function), it shows like this:当直接尝试打印它(即,没有 type() 函数)时,它显示如下:

y_true: Tensor("IteratorGetNext:1", shape=(None, None), dtype=float32)
y_pred: Tensor("sequential_5/dense_5/Softmax:0", shape=(None, 5), dtype=float32)

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.. 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) ) 试过了..

How can I convert these datatypes in a way that, it can be passed to sklearn.metrics.cohen_kappa_score function?如何转换这些数据类型,使其可以传递给 sklearn.metrics.cohen_kappa_score function? I don't want to write a code for kappa score.我不想为 kappa 分数编写代码。 Is it possible to convert?是否可以转换?

There's a way to solve this problem wrapping cohen_kappa_score intf.py_function .有一种方法可以解决这个问题,将 cohen_kappa_score 包装在tf.py_function中。 It's available in tensorflow 2.x, but I don't know since which version of framework;它在 tensorflow 2.x 中可用,但我不知道从哪个版本的框架开始; py_function does all heavy lifting for you, wrapping a Python function into a TensorFlow operation that executes it eagerly. py_function为您完成所有繁重的工作,将 Python function 包装到急切执行它的 TensorFlow 操作中。

import tensorflow as tf
import numpy as np
from sklearn.metrics import cohen_kappa_score


def cohen_kappa_score_wrapper(y_true, y_pred):
  y_pred = np.argmax(y_pred, axis=1)
  return cohen_kappa_score(y_true, y_pred, weights='quadratic')


def kappaScore(y_true, y_pred):
  return tf.py_function(
      func=cohen_kappa_score_wrapper,
      inp=[y_true, y_pred],
      Tout=tf.float32
    )


model.compile('adam', 'sparse_categorical_crossentropy', metrics=[kappaScore])

First, define cohen_kappa_score_wrapper .首先,定义cohen_kappa_score_wrapper It's important, because last dense layer usually returns an array of probabilities of each class for each sample.这很重要,因为最后一个密集层通常会返回每个样本的每个 class 的概率数组。 But Cohen kappa score accepts integer labels of classes, so one has to convert probabilities into labels with np.argmax() .但是 Cohen kappa 分数接受 integer 类标签,因此必须使用np.argmax()将概率转换为标签。 We're still on the Python's territory, so could just use numpy functions.我们仍然在 Python 的领域,所以可以使用 numpy 函数。

Then wrap cohen_kappa_score_wrapper with py_function : see kappaScore .然后用py_function cohen_kappa_score_wrapper参见kappaScore

Complete example using MNIST:使用 MNIST 的完整示例:

import keras 
import tensorflow as tf
from keras.layers import Input, LSTM, RepeatVector, TimeDistributed, Dense
from keras import Model
import numpy as np

from sklearn.metrics import cohen_kappa_score
from keras.datasets import mnist

(x_train, x_test), (y_train, y_test) = mnist.load_data()
model = keras.Sequential([
   keras.layers.Flatten(),
   keras.layers.Dense(128, activation='relu'),
   keras.layers.Dense(10, activation='softmax'),
])

def cohen_kappa_score_wrapper(y_true, y_pred):
  y_pred = np.argmax(y_pred, axis=1)
  return cohen_kappa_score(y_true, y_pred, weights='quadratic')


def kappaScore(y_true, y_pred):
  return tf.py_function(
      func=cohen_kappa_score_wrapper,
      inp=[y_true, y_pred], #  weights='quadratic']
      Tout=tf.float32
    )

model.compile('adam', 'sparse_categorical_crossentropy', metrics=[kappaScore])
model.fit(x_train / 255., x_test)
60000/60000 [==============================] - 5s 90us/sample - loss: 0.2612 - kappaScore: 0.9202
<keras.callbacks.History at 0x7fcea289cc50>

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() .注意尽管文档声明包装的 function 急切执行,但如果我关闭急切执行它仍然对我有用: tf.compat.v1.disable_eager_execution() I use tf2.7 .我使用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.此外,如果您使用tf1.x ,情况可能会有所不同。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 ValueError:特征应该是`Tensor`的字典。 给定类型: <class 'tensorflow.python.framework.ops.Tensor'> - ValueError: features should be a dictionary of `Tensor`s. Given type: <class 'tensorflow.python.framework.ops.Tensor'> Tensorflow Batchnormalization - 类型错误:轴必须是整数或列表,类型给定:<class 'tensorflow.python.framework.ops.Tensor'> - Tensorflow Batchnormalization - TypeError: axis must be int or list, type given: <class 'tensorflow.python.framework.ops.Tensor'> 如何在 Tensorflow 2.0 中打印 tensorflow.python.framework.ops.Tensor 的值? - How to print value of tensorflow.python.framework.ops.Tensor in Tensorflow 2.0? 将张量转换为 Tensorflow 中的 numpy 数组? - Convert a tensor to numpy array in Tensorflow? tensorflow.python.framework.errors_impl.InvalidArgumentError:无法将 dtype 资源的张量转换为 numpy 数组 - tensorflow.python.framework.errors_impl.InvalidArgumentError: cannot convert a Tensor of dtype resource to a numpy array AttributeError: &#39;tensorflow.python.framework.ops.EagerTensor&#39; 对象没有属性 &#39;to_tensor&#39; - AttributeError: 'tensorflow.python.framework.ops.EagerTensor' object has no attribute 'to_tensor' ValueError:无法在 Keras/Tensorflow Python 中将 NumPy 数组转换为张量(不支持的 object 类型列表) - ValueError: Failed to convert a NumPy array to a Tensor (Unsupported object type list) in Keras/Tensorflow Python ValueError:无法将 NumPy 数组转换为张量(不支持的 object 类型浮点数) - ValueError: Unable to convert NumPy array to a Tensor (Unsupported object type float) Tensorflow TypeError: 无法转换 object 类型<class 'tensorflow.python.framework.sparse_tensor.sparsetensor'>张量</class> - Tensorflow TypeError: Failed to convert object of type <class 'tensorflow.python.framework.sparse_tensor.SparseTensor'> to Tensor 如何在张量流中将图像张量转换为 numpy 数组? - How to convert image tensor in to numpy array in tensorflow?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM