Python ``tensorflow.math.confusion_matrix()`` 混淆矩阵函数与实例


发布日期 : 2022-06-25 04:11:16 UTC

访问量: 10 次浏览

Python – tensorflow.math.confusion\_matrix()

TensorFlow是谷歌设计的开源Python库,用于开发机器学习模型和深度学习神经网络。
confusion\_matrix() 用于从预测和标签中找到混淆矩阵。

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

参数:

  • labels: 它是一个一维张量,包含分类任务的真实标签。
  • predictions: 它也是一个与标签形状相同的一维张量。它的值代表预测的类别。
  • num\_classes(可选): 它是分类任务可能有的标签/类的数量。如果不提供,num\_classes 将比预测或标签的最大值多一个。
  • weight(可选): 这是一个与预测值相同的张量,其值定义了每个预测的相应权重。
  • dtype(可选): 它定义了返回混淆矩阵的dtype。默认的是 tensorflow.dtypes.int32
  • name(可选): 定义了操作的名称。

返回值:

它返回一个形状为 [n,n] 的混淆矩阵,其中n是可能的标签数量。

示例 1:

# 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('Predictions: ',predictions)

# Evaluating confusion matrix
res = tf.math.confusion_matrix(labels,predictions)

# Printing the result
print('Confusion_matrix: ',res)

输出:

labels: tf.Tensor([1 3 4], shape=(3,), dtype=int32)
Predictions: 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:
这个例子提供了所有预测的权重。

# 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('Predictions: ',predictions)
print('Weights: ',weights)

# Evaluating confusion matrix
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)
Predictions: 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)