给我一个数据到混淆矩阵的代码
时间: 2024-02-23 16:59:30 浏览: 26
下面是一个简单的Python代码示例,用于将数据集的预测结果转换为混淆矩阵。
假设我们有一个二分类问题,有100个样本,预测结果存储在一个名为predictions的数组中,真实标签存储在一个名为labels的数组中。我们可以使用sklearn.metrics中的confusion_matrix函数来计算混淆矩阵,具体代码如下:
```python
from sklearn.metrics import confusion_matrix
# 定义预测结果和真实标签
predictions = [0, 1, 0, 1, 1, 0, 1, 0, 0, 1, ...] # 长度为100的数组
labels = [0, 1, 0, 1, 1, 0, 1, 0, 1, 1, ...] # 长度为100的数组
# 计算混淆矩阵
cm = confusion_matrix(labels, predictions)
# 输出混淆矩阵
print(cm)
```
运行结果将会输出一个2x2的混淆矩阵,例如:
```
[[45 5]
[10 40]]
```
其中,左上角的元素表示真正例的数量(True Positive, TP),右上角的元素表示假正例的数量(False Positive, FP),左下角的元素表示假反例的数量(False Negative, FN),右下角的元素表示真反例的数量(True Negative, TN)。
相关问题
给我一matlib 混淆矩阵的代码
下面是使用Python的Matplotlib库绘制混淆矩阵的示例代码:
```python
import matplotlib.pyplot as plt
import numpy as np
# 定义混淆矩阵
confusion_matrix = np.array([[50, 10], [5, 35]])
# 绘制混淆矩阵图表
plt.imshow(confusion_matrix, cmap=plt.cm.Blues)
# 添加图表标题、标签等
plt.title("Confusion Matrix")
plt.xlabel("Predicted Label")
plt.ylabel("True Label")
# 调整坐标轴刻度、标签等
tick_marks = np.arange(len(confusion_matrix))
plt.xticks(tick_marks, ["Positive", "Negative"])
plt.yticks(tick_marks, ["Positive", "Negative"])
plt.colorbar()
# 添加数据标签
thresh = confusion_matrix.max() / 2.
for i, j in np.ndindex(confusion_matrix.shape):
plt.text(j, i, format(confusion_matrix[i, j], "d"),
horizontalalignment="center",
color="white" if confusion_matrix[i, j] > thresh else "black")
# 显示图表
plt.show()
```
运行上述代码,将会绘制出一个混淆矩阵的图表。其中,图表的颜色深浅表示混淆矩阵中的数值大小,数据标签表示混淆矩阵中的数值。可以根据实际情况调整混淆矩阵的数值、标签、标题、颜色等。
给出一个统计三分类混淆矩阵数据的pytorch代码
以下是一个统计三分类混淆矩阵数据的 PyTorch 代码:
```python
import torch
import numpy as np
from sklearn.metrics import confusion_matrix
# 定义真实标签和预测标签
y_true = torch.tensor([0, 0, 1, 1, 2, 2])
y_pred = torch.tensor([0, 1, 1, 2, 2, 0])
# 计算混淆矩阵
cm = confusion_matrix(y_true.numpy(), y_pred.numpy())
print(cm)
# 计算分类准确率
acc = np.trace(cm) / np.sum(cm)
print(acc)
```
以上代码中,首先定义了真实标签 `y_true` 和预测标签 `y_pred`。然后使用 `confusion_matrix` 函数计算混淆矩阵,并输出结果。最后,根据混淆矩阵计算出分类准确率并输出结果。