一个完整的数据挖掘模型,最后都要进行模型评估,对于二分类来说,AUC,ROC这两个指标用到最多,所以 利用sklearn里面相应的函数进行模块搭建。
具体实现的代码可以参照下面博友的代码,评估svm的分类指标。注意里面的一些细节需要注意,一个是调用roc_curve 方法时,指明目标标签,否则会报错。具体是这个参数的设置pos_label ,以前在unionbigdata实习时学到的。
重点是以下的代码需要根据实际改写:
mean_tpr = 0.0
mean_fpr = np.linspace(0, 1, 100)
all_tpr = []
y_target = np.r_[train_y,test_y]
cv = StratifiedKFold(y_target, n_folds=6)
#画ROC曲线和计算AUC
fpr, tpr, thresholds = roc_curve(test_y, predict,pos_label = 2)##指定正例标签,pos_label = ###########在数之联的时候学到的,要制定正例
mean_tpr += interp(mean_fpr, fpr, tpr) #对mean_tpr在mean_fpr处进行插值,通过scipy包调用interp()函数
mean_tpr[0] = 0.0 #初始处为0
roc_auc = auc(fpr, tpr)
#画图,只需要plt.plot(fpr,tpr),变量roc_auc只是记录auc的值,通过auc()函数能计算出来
plt.plot(fpr, tpr, lw=1, label='ROC %s (area = %0.3f)' % (classifier, roc_auc))
然后是博友的参考代码:
-
-
-
-
-
-
- print(__doc__)
-
- import numpy as np
- from scipy import interp
- import matplotlib.pyplot as plt
-
- from sklearn import svm, datasets
- from sklearn.metrics import roc_curve, auc
- from sklearn.cross_validation import StratifiedKFold
-
-
-
-
-
- iris = datasets.load_iris()
- X = iris.data
- y = iris.target
- X, y = X[y != 2], y[y != 2]
- n_samples, n_features = X.shape
-
-
- random_state = np.random.RandomState(0)
- X = np.c_[X, random_state.randn(n_samples, 200 * n_features)]
-
-
-
-
-
-
-
- cv = StratifiedKFold(y, n_folds=6)
- classifier = svm.SVC(kernel='linear', probability=True,
- random_state=random_state)
-
- mean_tpr = 0.0
- mean_fpr = np.linspace(0, 1, 100)
- all_tpr = []
-
- for i, (train, test) in enumerate(cv):
-
- probas_ = classifier.fit(X[train], y[train]).predict_proba(X[test])
-
-
-
-
-
-
- fpr, tpr, thresholds = roc_curve(y[test], probas_[:, 1])
- mean_tpr += interp(mean_fpr, fpr, tpr)
- mean_tpr[0] = 0.0
- roc_auc = auc(fpr, tpr)
-
- plt.plot(fpr, tpr, lw=1, label='ROC fold %d (area = %0.2f)' % (i, roc_auc))
-
-
- plt.plot([0, 1], [0, 1], '--', color=(0.6, 0.6, 0.6), label='Luck')
-
- mean_tpr /= len(cv)
- mean_tpr[-1] = 1.0
- mean_auc = auc(mean_fpr, mean_tpr)
-
-
-
- plt.plot(mean_fpr, mean_tpr, 'k--',
- label='Mean ROC (area = %0.2f)' % mean_auc, lw=2)
-
- plt.xlim([-0.05, 1.05])
- plt.ylim([-0.05, 1.05])
- plt.xlabel('False Positive Rate')
- plt.ylabel('True Positive Rate')
- plt.title('Receiver operating characteristic example')
- plt.legend(loc="lower right")
- plt.show()