生成一个显示混淆矩阵的代码
时间: 2023-05-12 11:06:06 浏览: 64
以下是一个生成混淆矩阵的 Python 代码:
```python
import numpy as np
from sklearn.metrics import confusion_matrix
# 生成随机的真实标签和预测标签
y_true = np.random.randint(0, 2, size=100)
y_pred = np.random.randint(0, 2, size=100)
# 计算混淆矩阵
cm = confusion_matrix(y_true, y_pred)
# 打印混淆矩阵
print(cm)
```
这段代码使用了 scikit-learn 库中的 confusion_matrix 函数来计算混淆矩阵,然后打印出来。
相关问题
生成混淆矩阵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
from sklearn.metrics import confusion_matrix
import seaborn as sns
import matplotlib.pyplot as plt
# 实际标签
actual = [1, 0, 1, 1, 0, 1, 0, 0, 0, 1]
# 预测标签
predicted = [1, 0, 0, 1, 0, 1, 0, 1, 1, 0]
# 计算混淆矩阵
cm = confusion_matrix(actual, predicted)
# 可视化混淆矩阵
sns.heatmap(cm, annot=True, cmap="Blues", fmt="d")
plt.title("Confusion Matrix")
plt.xlabel("Predicted Labels")
plt.ylabel("Actual Labels")
plt.show()
```
该代码将生成一个热图,显示实际标签和预测标签之间的混淆矩阵。混淆矩阵的对角线上的数字表示正确分类的样本数,而其他位置的数字表示错误分类的样本数。在热图中,颜色越深表示样本数越多。
相关推荐
![txt](https://img-home.csdnimg.cn/images/20210720083642.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)