[英]Tensorflow2.0 - How to convert Tensor to numpy() array
I'm running tf2.0 and simply can not print the confusion matrix values.我正在运行 tf2.0 并且根本无法打印混淆矩阵值。 The problem is described below.
问题描述如下。
@tf.function
def test_step(self, x , y):
predictions = model(x, training=False)
loss = self.loss(y, predictions)
y, predictions = tf.reshape(y,[-1,]), tf.reshape(predictions, [-1,])
# Cast into class labels
predictions = math_ops.cast(predictions > 0.5, predictions.dtype)
....
self.test_conf_matrix = tf.math.confusion_matrix(y, predictions, num_classes=2) <--- important line!
Everything is going well so far, and the confusion matrix will be computed properly.到目前为止一切顺利,混淆矩阵将被正确计算。
But it is simply not possible to print it out in the end like:但它根本不可能像这样打印出来:
print(str(self.test_conf_matrix.numpy()))
The error I get is:我得到的错误是:
AttributeError: 'Tensor' object has no attribute 'numpy'
But since tf2 and eagerExecution this should be done this way, right?但是既然 tf2 和 eagerExecution 这应该是这样做的,对吧? See: TF2.0 Tutorial
参见: TF2.0 教程
According to the definition of tf.function
,根据
tf.function
的定义,
"Compiles a function into a callable TensorFlow graph".
“将函数编译为可调用的 TensorFlow 图”。
Since the tf.function
imposes a TensorFlow graph, you cannot use anything outside of the tf.*
methods.由于
tf.function
强加了 TensorFlow 图,因此您不能使用tf.*
方法之外的任何内容。
That means that any arbitrary python code cannot be used inside a tf.function
, only what is already available in the tf.*
methods.这意味着任何 Python 代码都不能在
tf.function
中使用,只能在tf.*
方法中使用。
The same exact phenomenon happens when you want to iterate on a tf.data.Dataset
with a map function.当您想使用 map 函数迭代
tf.data.Dataset
时,会发生同样的现象。 That map
function you want to use on tf.data.Dataset
cannot contain arbitrary python code, unless you specifically use a tf.py_function
.您要在
tf.data.Dataset
上使用的map
函数不能包含任意 python 代码,除非您专门使用tf.py_function
。
These operation are specifically executed in graph mode for performance reasons, and thus, you cannot call methods that belong to the 'eager execution' category, such as .numpy()
.出于性能原因,这些操作专门在图形模式下执行,因此,您不能调用属于“急切执行”类别的方法,例如
.numpy()
。
Look at : https://www.tensorflow.org/api_docs/python/tf/numpy_function看: https ://www.tensorflow.org/api_docs/python/tf/numpy_function
def my_numpy_func(x):
# x will be a numpy array with the contents of the input to the
# tf.function
return np.sinh(x)
@tf.function(input_signature=[tf.TensorSpec(None, tf.float32)])
def tf_function(input):
y = tf.numpy_function(my_numpy_func, [input], tf.float32)
return y * y
tf_function(tf.constant(1.))
This works for me fine.这对我来说很好。
You make a function something like你做一个类似的功能
def print_cm(cm):
print(cm)
@tf.function()
def test_step(self, x , y):
....
self.test_conf_matrix = tf.math.confusion_matrix(y, predictions, num_classes=2) # <--- important line!
# make print as numpy array under tf.function decorator
print_cm(test_conf_matrix)) # just call function
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.