簡體   English   中英

Tensorflow2.0 - 如何將張量轉換為 numpy() 數組

[英]Tensorflow2.0 - How to convert Tensor to numpy() array

我正在運行 tf2.0 並且根本無法打印混淆矩陣值。 問題描述如下。

  @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!

到目前為止一切順利,混淆矩陣將被正確計算。

但它根本不可能像這樣打印出來:

print(str(self.test_conf_matrix.numpy()))

我得到的錯誤是:

AttributeError: 'Tensor' object has no attribute 'numpy'

但是既然 tf2 和 eagerExecution 這應該是這樣做的,對吧? 參見: TF2.0 教程

根據tf.function的定義,

“將函數編譯為可調用的 TensorFlow 圖”。

由於tf.function強加了 TensorFlow 圖,因此您不能使用tf.*方法之外的任何內容。

這意味着任何 Python 代碼都不能在tf.function中使用,只能在tf.*方法中使用。

當您想使用 map 函數迭代tf.data.Dataset時,會發生同樣的現象。 您要在tf.data.Dataset上使用的map函數不能包含任意 python 代碼,除非您專門使用tf.py_function

出於性能原因,這些操作專門在圖形模式下執行,因此,您不能調用屬於“急切執行”類別的方法,例如.numpy()

看: 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.))

這對我來說很好。

你做一個類似的功能

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM