把confusion_matrix函数的python代码给我
时间: 2023-06-09 18:07:15 浏览: 57
以下是confusion_matrix函数的Python代码:
```python
from sklearn.metrics import confusion_matrix
y_true = [0, 1, 0, 1, 0, 1, 0, 1]
y_pred = [0, 1, 1, 1, 0, 0, 1, 0]
confusion_matrix = confusion_matrix(y_true, y_pred)
print(confusion_matrix)
```
这段代码使用了scikit-learn库中的confusion_matrix函数,接收两个参数:真实标签和预测标签,并返回混淆矩阵。最后通过print函数输出混淆矩阵。
相关问题
把confusion_matrix函数的python源码给我
以下是 `confusion_matrix` 函数的 Python 源代码:
```python
def confusion_matrix(actual, predicted, classes):
"""
Calculate confusion matrix and store result as a dictionary.
Parameters:
actual (list): List of actual labels.
predicted (list): List of predicted labels.
classes (list): List of all possible labels.
Returns:
dict: Confusion matrix as dictionary.
"""
matrix = {}
for i in range(len(classes)):
row = {}
for j in range(len(classes)):
row[classes[j]] = 0
matrix[classes[i]] = row
for i in range(len(actual)):
if actual[i] in classes and predicted[i] in classes:
matrix[actual[i]][predicted[i]] += 1
return matrix
```
这是一个计算混淆矩阵的函数,它接受三个参数:`actual`、`predicted` 和 `classes`。 `actual` 和 `predicted` 是两个包含实际和预测标签的列表,而 `classes` 是所有可能标签的列表。函数通过遍历实际标签和预测标签,计算混淆矩阵并将结果存储在一个字典中,最后返回该字典。
plot_confusion_matrix python代码
以下是一个简单的 Python 代码,用于绘制混淆矩阵:
```python
import numpy as np
import matplotlib.pyplot as plt
from sklearn.metrics import confusion_matrix
def plot_confusion_matrix(y_true, y_pred, classes,
normalize=False,
title=None,
cmap=plt.cm.Blues):
"""
This function prints and plots the confusion matrix.
Normalization can be applied by setting `normalize=True`.
"""
cm = confusion_matrix(y_true, y_pred)
if normalize:
cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
print("Normalized confusion matrix")
else:
print('Confusion matrix, without normalization')
print(cm)
plt.imshow(cm, interpolation='nearest', cmap=cmap)
plt.title(title)
plt.colorbar()
tick_marks = np.arange(len(classes))
plt.xticks(tick_marks, classes, rotation=45)
plt.yticks(tick_marks, classes)
fmt = '.2f' if normalize else 'd'
thresh = cm.max() / 2.
for i, j in np.ndindex(cm.shape):
plt.text(j, i, format(cm[i, j], fmt),
horizontalalignment="center",
color="white" if cm[i, j] > thresh else "black")
plt.tight_layout()
plt.ylabel('True label')
plt.xlabel('Predicted label')
plt.show()
```
这个函数使用了 scikit-learn 库中的 confusion_matrix 函数,用于计算混淆矩阵。它还使用了 matplotlib 库来绘制混淆矩阵的图形。您可以将真实标签和预测标签作为参数传递给该函数,以及一个类列表,用于标识每个类别。您还可以选择是否对混淆矩阵进行归一化,并为图形添加标题。