用scikit-plot可视化训练好的机器学习模型(包括多分类的ROC曲线、混淆矩阵等)

目录

一、安装

二、案例绘图

1)评估指标可视化

1、混淆矩阵

2、多类别ROC曲线

3、KS 统计图

4、PR曲线

5、silhouette analysis分析

6、分类器的矫正曲线

2)模型可视化

1、不同训练样本下的训练和测试学习曲线图

2、可视化特征重要性

3)聚类可视化

1、聚类的肘步图

4)降维可视化

1、 PCA 分量的解释方差比

2、PCA降维之后的散点图


scikit-learn (sklearn)是Python环境下常见的机器学习库,包含了常见的分类、回归和聚类算法。在训练模型之后,常见的操作是对模型进行可视化,则需要使用Matplotlib进行展示。

scikit-plot是一个基于sklearnMatplotlib的库,主要的功能是对训练好的模型进行可视化,功能比较简单易懂。

一、安装

pip install scikit-plot -i https://pypi.tuna.tsinghua.edu.cn/simple

二、案例绘图

1)评估指标可视化

1、混淆矩阵

import scikitplot as skplt
rf = RandomForestClassifier()
rf = rf.fit(X_train, y_train)
y_pred = rf.predict(X_test)

skplt.metrics.plot_confusion_matrix(y_test, y_pred, normalize=True)
plt.show()

2、多类别ROC曲线

import scikitplot as skplt
nb = GaussianNB()
nb = nb.fit(X_train, y_train)
y_probas = nb.predict_proba(X_test)

skplt.metrics.plot_roc(y_test, y_probas)
plt.show()

3、KS 统计图

import scikitplot as skplt
lr = LogisticRegression()
lr = lr.fit(X_train, y_train)
y_probas = lr.predict_proba(X_test)

skplt.metrics.plot_ks_statistic(y_test, y_probas)
plt.show()

4、PR曲线

import scikitplot as skplt
nb = GaussianNB()
nb.fit(X_train, y_train)
y_probas = nb.predict_proba(X_test)

skplt.metrics.plot_precision_recall(y_test, y_probas)
plt.show()

"""
import scikitplot as skplt
# 设置全局字体为新罗马字体和修改字体大小(在开始绘图之前,即置于顶部)
plt.rcParams['font.family'] = 'Times New Roman'
plt.rcParams['font.size'] = 12

skplt.metrics.plot_precision_recall(y_test, y_score,figsize=(6, 4.5),
                                    title="Precision-recall curve of IP dataset")
plt.legend(prop={'size': 8.5})
plt.show()
"""

5、silhouette analysis分析

import scikitplot as skplt
kmeans = KMeans(n_clusters=4, random_state=1)
cluster_labels = kmeans.fit_predict(X)

skplt.metrics.plot_silhouette(X, cluster_labels)
plt.show()

6、分类器的矫正曲线

import scikitplot as skplt
rf = RandomForestClassifier()
lr = LogisticRegression()
nb = GaussianNB()
svm = LinearSVC()
rf_probas = rf.fit(X_train, y_train).predict_proba(X_test)
lr_probas = lr.fit(X_train, y_train).predict_proba(X_test)
nb_probas = nb.fit(X_train, y_train).predict_proba(X_test)
svm_scores = svm.fit(X_train, y_train).decision_function(X_test)
probas_list = [rf_probas, lr_probas, nb_probas, svm_scores]
clf_names = ['Random Forest', 'Logistic Regression',
              'Gaussian Naive Bayes', 'Support Vector Machine']

skplt.metrics.plot_calibration_curve(y_test,
                                      probas_list,
                                      clf_names)
plt.show()

2)模型可视化

1、不同训练样本下的训练和测试学习曲线图

import scikitplot as skplt
rf = RandomForestClassifier()

skplt.estimators.plot_learning_curve(rf, X, y)
plt.show()

2、可视化特征重要性

import scikitplot as skplt
rf = RandomForestClassifier()
rf.fit(X, y)

skplt.estimators.plot_feature_importances(
     rf, feature_names=['petal length', 'petal width',
                        'sepal length', 'sepal width'])
plt.show()

3)聚类可视化

1、聚类的肘步图

import scikitplot as skplt
kmeans = KMeans(random_state=1)

skplt.cluster.plot_elbow_curve(kmeans, cluster_ranges=range(1, 30))
plt.show()

4)降维可视化

1、 PCA 分量的解释方差比

import scikitplot as skplt
pca = PCA(random_state=1)
pca.fit(X)

skplt.decomposition.plot_pca_component_variance(pca)
>plt.show()

2、PCA降维之后的散点图

import scikitplot as skplt
pca = PCA(random_state=1)
pca.fit(X)

skplt.decomposition.plot_pca_2d_projection(pca, X, y)
plt.show()

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
要生成混淆矩阵ROC曲线,并进行可视化,你可以使用scikit-learn库中的confusion_matrix和roc_curve函数。下面是一个使用已经保存的模型生成混淆矩阵ROC曲线的示例代码: ```python from sklearn.metrics import confusion_matrix, roc_curve, roc_auc_score import matplotlib.pyplot as plt import seaborn as sns import numpy as np import joblib # 加载已经保存的模型 model = joblib.load('model.joblib') # 加载测试数据 X_test = np.load('X_test.npy') y_test = np.load('y_test.npy') # 预测概率 y_pred_proba = model.predict_proba(X_test) # 预测类别 y_pred = np.argmax(y_pred_proba, axis=1) # 计算混淆矩阵 cm = confusion_matrix(y_test, y_pred) # 可视化混淆矩阵 sns.heatmap(cm, annot=True, cmap='Blues') plt.title('Confusion Matrix') plt.xlabel('Predicted Label') plt.ylabel('True Label') plt.show() # 计算ROC曲线和AUC分数 fpr, tpr, thresholds = roc_curve(y_test, y_pred_proba[:, 1]) roc_auc = roc_auc_score(y_test, y_pred_proba[:, 1]) # 可视化ROC曲线 plt.plot(fpr, tpr, label='ROC curve (area = %0.2f)' % roc_auc) plt.plot([0, 1], [0, 1], 'k--') plt.xlim([0.0, 1.0]) plt.ylim([0.0, 1.05]) plt.xlabel('False Positive Rate') plt.ylabel('True Positive Rate') plt.title('Receiver Operating Characteristic (ROC)') plt.legend(loc="lower right") plt.show() ``` 在上面的示例代码中,我们首先加载了已经保存的模型。接着,我们加载了测试数据,并使用predict_proba方法获取模型的预测概率,使用argmax方法获取预测类别。然后,我们使用confusion_matrix函数计算混淆矩阵,并使用heatmap函数将其可视化。最后,我们使用roc_curve函数计算ROC曲线和AUC分数,并使用plot函数将其可视化

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

清纯世纪

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值