當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Python tensorflow.math.confusion_matrix()用法及代碼示例

TensorFlow是Google設計的開源Python庫,用於開發機器學習模型和深度學習神經網絡。 confusion_matrix()用於從預測和標簽中找到混淆矩陣。

用法:tensorflow.math.confusion_matrix( labels, predictions, num_classes, weights, dtype,name)
 

參數:

  • labels:這是一維張量,其中包含用於分類任務的真實標簽。
  • predictions:它也是與標簽形狀相同的一維張量。它的值代表預測的類。
  • num_classes(可選):這可能是標簽/類分類任務可能具有的數量。如果未提供,則num_classes將比預測值或標簽中的最大值大一碼。
  • weight(optional):它是與預測形狀相同的張量,其值定義了每個預測的相應權重。
  • dtype(optional):它定義了返回的混淆矩陣的dtype。如果tensorflow.dtypes.int32,則取消注冊。
  • name(optional):定義操作的名稱。

返回值:
它返回形狀為[n,n]的混淆矩陣,其中n是可能的標簽數。

範例1:



Python3


# importing the library
import tensorflow as tf
  
# Initializing the input tensor
labels = tf.constant([1,3,4],dtype = tf.int32)
predictions = tf.constant([1,2,3],dtype = tf.int32)
  
# Printing the input tensor
print('labels:',labels)
print('Predictins:',predictions)
  
# Evaluating confusion matric
res = tf.math.confusion_matrix(labels,predictions)
  
# Printing the result
print('Confusion_matrix:',res)

輸出:

labels: tf.Tensor([1 3 4], shape=(3,), dtype=int32)
Predictins: tf.Tensor([1 2 3], shape=(3,), dtype=int32)
Confusion_matrix: tf.Tensor(
[[0 0 0 0 0]
 [0 1 0 0 0]
 [0 0 0 0 0]
 [0 0 1 0 0]
 [0 0 0 1 0]], shape=(5, 5), dtype=int32)

範例2:此示例為所有預測提供權重。

Python3


# importing the library
import tensorflow as tf
  
# Initializing the input tensor
labels = tf.constant([1,3,4],dtype = tf.int32)
predictions = tf.constant([1,2,4],dtype = tf.int32)
weights = tf.constant([1,2,2], dtype = tf.int32)
  
# Printing the input tensor
print('labels:',labels)
print('Predictins:',predictions)
print('Weights:',weights)
  
# Evaluating confusion matric
res = tf.math.confusion_matrix(labels, predictions, weights=weights)
  
# Printing the result
print('Confusion_matrix:',res)

輸出:

labels: tf.Tensor([1 3 4], shape=(3,), dtype=int32)
Predictins: tf.Tensor([1 2 4], shape=(3,), dtype=int32)
Weights: tf.Tensor([1 2 2], shape=(3,), dtype=int32)
Confusion_matrix: tf.Tensor(
[[0 0 0 0 0]
 [0 1 0 0 0]
 [0 0 0 0 0]
 [0 0 2 0 0]
 [0 0 0 0 2]], shape=(5, 5), dtype=int32)


注:本文由純淨天空篩選整理自aman neekhara大神的英文原創作品 Python – tensorflow.math.confusion_matrix()。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。