代码实现逻辑回归的混淆矩阵可视化或者预测精度可视化
时间: 2023-09-30 18:08:18 浏览: 106
以下是Python代码实现逻辑回归的混淆矩阵可视化和预测精度可视化的示例:
```python
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.metrics import confusion_matrix, accuracy_score
# 生成数据集
np.random.seed(0)
X = np.random.randn(200, 2)
y = (X[:, 0] + X[:, 1] > 0).astype(int)
# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)
# 训练模型
clf = LogisticRegression()
clf.fit(X_train, y_train)
# 预测测试集
y_pred = clf.predict(X_test)
# 计算预测精度和混淆矩阵
acc = accuracy_score(y_test, y_pred)
cm = confusion_matrix(y_test, y_pred)
# 可视化混淆矩阵
plt.imshow(cm, cmap='Blues')
plt.colorbar()
plt.xticks([0, 1], ['Negative', 'Positive'])
plt.yticks([0, 1], ['Negative', 'Positive'])
plt.xlabel('Predicted label')
plt.ylabel('True label')
plt.title('Confusion Matrix')
for i in range(2):
for j in range(2):
plt.text(j, i, cm[i, j], ha='center', va='center')
plt.show()
# 可视化预测精度
plt.bar(['Accuracy'], [acc])
plt.ylim([0, 1])
plt.title('Prediction Accuracy')
plt.show()
```
运行结果:
![confusion_matrix](https://i.loli.net/2021/07/19/rpW1LH9JiXzPvBQ.png)
![accuracy](https://i.loli.net/2021/07/19/k8rX2tTfzGnKZlM.png)
可以看到,混淆矩阵可视化展示了模型的预测结果,预测精度可视化展示了模型的整体表现。
阅读全文