用一组数据训练贝叶斯分类模型,用另一组数据测试训练出的模型,并用混淆矩阵和ROC曲线进行评价 Python代码
时间: 2024-01-27 16:44:25 浏览: 24
可以通过如下Python代码训练贝叶斯分类模型、测试模型、绘制混淆矩阵和ROC曲线:
```python
# 导入需要的库和模块
import numpy as np
from sklearn.naive_bayes import GaussianNB
from sklearn.metrics import confusion_matrix, plot_confusion_matrix, roc_curve, auc
import matplotlib.pyplot as plt
# 使用一组数据训练贝叶斯分类模型
train_data = np.array([[1, 2], [2, 3], [3, 4], [4, 5], [5, 6], [6, 7], [7, 8], [8, 9], [9, 10], [10, 11]])
train_label = np.array([0, 0, 0, 0, 1, 1, 1, 1, 1, 1])
gnb = GaussianNB()
gnb.fit(train_data, train_label)
# 使用另一组数据测试训练出的模型
test_data = np.array([[1, 3], [3, 5], [5, 7], [7, 9], [9, 11]])
test_label = np.array([0, 0, 1, 1, 1])
predict_label = gnb.predict(test_data)
# 绘制混淆矩阵
cm = confusion_matrix(test_label, predict_label)
plot_confusion_matrix(gnb, test_data, test_label)
plt.show()
# 绘制ROC曲线
fpr, tpr, thresholds = roc_curve(test_label, gnb.predict_proba(test_data)[:, 1])
roc_auc = auc(fpr, tpr)
plt.plot(fpr, tpr, lw=1, alpha=0.8, label='AUC = %0.2f' % (roc_auc))
plt.plot([0, 1], [0, 1], linestyle='--', lw=2, color='r', label='Random Chance')
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.title('ROC curve of GaussianNB')
plt.legend(loc="lower right")
plt.show()
```
请注意,这段代码仅为演示目的,应该根据实际数据进行调整。