生成混淆矩阵代码
时间: 2023-10-22 10:09:29 浏览: 48
以下是一个 Python 代码示例,可以用于生成混淆矩阵:
```python
import numpy as np
def confusion_matrix(actual, predicted, labels):
# 初始化混淆矩阵
matrix = np.zeros((len(labels), len(labels)), dtype=int)
# 遍历每一个预测结果和实际结果
for a, p in zip(actual, predicted):
# 找到对应标签的索引
i = labels.index(a)
j = labels.index(p)
# 将混淆矩阵中对应位置的计数器加一
matrix[i][j] += 1
return matrix
```
这个函数接受三个参数:
- `actual`:一个包含真实标签的数组
- `predicted`:一个包含预测标签的数组
- `labels`:一个包含所有可能标签的列表
函数返回一个二维 `numpy` 数组,表示混淆矩阵。
相关问题
生成混淆矩阵matlab代码
可以使用以下代码生成混淆矩阵(Confusion Matrix)的 MATLAB 代码:
```matlab
% 实际标签
actual_labels = [1 0 1 1 0 2 1 0 2 1];
% 预测标签
predicted_labels = [1 0 1 1 0 1 2 0 2 0];
% 类别数量
num_classes = max(actual_labels);
% 初始化混淆矩阵
confusion_matrix = zeros(num_classes, num_classes);
% 填充混淆矩阵
for i = 1:length(actual_labels)
actual = actual_labels(i);
predicted = predicted_labels(i);
confusion_matrix(actual, predicted) = confusion_matrix(actual, predicted) + 1;
end
% 显示混淆矩阵
disp(confusion_matrix);
```
请根据实际情况修改 `actual_labels` 和 `predicted_labels` 数组以适应你的数据。这段代码将生成一个 `num_classes x num_classes` 的混淆矩阵,并将其显示在 MATLAB 命令窗口中。
机器混淆矩阵python代码
以下是使用Python实现机器混淆矩阵的代码示例:
```python
import seaborn as sns
from sklearn.metrics import confusion_matrix
import matplotlib.pyplot as plt
# 真实分类结果
y_true = ["cat", "dog", "cat", "cat", "dog", "rabbit"]
# 预测分类结果
y_pred = ["dog", "dog", "rabbit", "cat", "dog", "cat"]
# 生成混淆矩阵数据
C = confusion_matrix(y_true, y_pred, labels=["dog", "rabbit", "cat"])
# 绘制混淆矩阵热度图
sns.heatmap(C, annot=True)
plt.show()
```
这段代码使用了`sklearn.metrics.confusion_matrix`函数生成混淆矩阵数据,并使用`seaborn`库的热度图功能绘制出混淆矩阵。混淆矩阵用于评估分类模型的性能,可以帮助我们了解模型在不同类别上的分类准确性。
相关推荐
![py](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)