Python SVM 二分类任务 ROC 曲线绘制代码详解
///'# -- coding: utf-8 --//nimport numpy as np//nimport matplotlib.pyplot as plt//nfrom sklearn import svm, datasets//nfrom sklearn.metrics import roc_curve, auc ###计算roc和auc//nfrom sklearn import model_selection//n//n# Import some data to play with//niris = datasets.load_iris()//nX = iris.data#得到样本集//ny = iris.target#得到标签集//n//n##变为2分类//nX, y = X[y != 2], y[y != 2]#通过取y不等于2来取两种类别//n# Add noisy features to make the problem harder添加扰动//nrandom_state = np.random.RandomState(0)//nn_samples, n_features = X.shape//nX = np.c_[X, random_state.randn(n_samples, 200 * n_features)]//n//n# shuffle and split training and test sets划分样本集//ntrain_data, test_data, train_label, test_label = model_selection.train_test_split(X, y, test_size=.3,random_state=0)//n#train_data用于训练的样本集, test_data用于测试的样本集, train_label训练样本对应的标签集, test_label测试样本对应的标签集//n# Learn to predict each class against the other分类器设置//nsvm = svm.SVC(kernel='linear', probability=True,random_state=random_state)#使用核函数为线性核,参数默认,创建分类器//n###通过decision_function()计算得到的test_predict_label的值,用在roc_curve()函数中//ntest_predict_label = svm.fit(train_data, train_label).decision_function(test_data)//n#首先通过fit来对训练样本和训练样本标签进行训练得到模型,然后通过decision_function来获得模型对于测试样本集预测的标签集//nprint(test_predict_label)//n//n# Compute ROC curve and ROC area for each class#计算tp,fp//n#通过测试样本输入的标签集和模型预测的标签集进行比对,得到fp,tp,不同的fp,tp是算法通过一定的规则改变阈值获得的//nfpr,tpr,threshold = roc_curve(test_label, test_predict_label) ###计算真正率和假正率//nprint(fpr)//nprint(tpr)//nprint(threshold)//nroc_auc = auc(fpr,tpr) ###计算auc的值,auc就是曲线包围的面积,越大越好//nlw = 2//nplt.figure(figsize=(10,10))//nplt.plot(fpr, tpr, color='darkorange',//nlw=lw, label='ROC curve (area = %0.2f)' % roc_auc) ###假正率为横坐标,真正率为纵坐标做曲线//nplt.plot([0, 1], [0, 1], color='navy', lw=lw, linestyle='--')//nplt.xlim([0.0, 1.0])//nplt.ylim([0.0, 1.05])//nplt.xlabel('False Positive Rate')//nplt.ylabel('True Positive Rate')//nplt.rcParams['font.sans-serif'] = ['KaiTi']//nplt.title('Receiver operating characteristic curve//n 201530508 李涵博')//nplt.legend(loc=/'lower right/')//nplt.grid(color = 'purple',linestyle='-.')//nplt.show()//n/
原文地址: http://www.cveoy.top/t/topic/pA2C 著作权归作者所有。请勿转载和采集!