分析技术 | 建立预测模型及模型的ROC曲线绘制

2020/5/27,受一名同学所托,为他的肿瘤Hub基因分析文章做一个预测模型和模型的ROC曲线、AUC值来验证Hub基因的可靠性。如果Hub基因有意义的话,用Hub基因作为特征建立的预测模型就应该能有效地分类癌组织或者正常组织。

本文结构如下:

  1. 数据预处理及读取
  2. 预测模型建模
  3. 计算每一类的ROC,micro-average ROC和macro-average ROC
  4. 特定类和多分类ROC曲线绘制
  5. ROC曲线结果解读

1. 数据预处理及读取

首先,数据清洗和Hub基因筛选,他们已经把Hub基因找到了,换句话说可以直接跳过数据清洗和特征工程阶段。

image

一共10个关键基因,分为三类,高恶度癌(3)、低恶度癌(2)、正常对照组织(1),分别为9、20、20个样本。

1.1 导入所需的Python包

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import numpyas np
import matplotlib.pyplotas plt
from itertoolsimport cycle
from sklearnimport svm
from sklearn.metricsimport roc_curve, auc
from sklearn.model_selectionimport train_test_split
from sklearn.preprocessingimport label_binarize
from sklearn.multiclassimport OneVsRestClassifier
from numpyimport interp

1.2 读取数据

首先创建两个.txt文件分别储存图2的特征值内容和标签内容,features.txt 和 label_2.txt(当然也可以直接用Pandas读取表格,个人习惯)然后用Python读入数据。

# 加载数据
X = np.loadtxt('./features.txt')
y = np.loadtxt('./label_3.txt')
image
# 矩阵转置,使每行表示一个样本,每列表示一个特征(基因)
X = X.T
# 标签改为one-hot编码,classes的值为原始label的值
y = label_binarize(y, classes=[1, 2, 3])
# 设置种类
n_classes = y.shape[1]
image

2. 预测模型建立

# 设置随机种子
random_state = np.random.RandomState(0)
n_samples, n_features = X.shape
# 打乱顺序并分配测试集占整个数据集的规模,这里是1:1
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=.5,random_state=0)
# Learn to predict each class against the other
classifier = OneVsRestClassifier(svm.SVC(kernel='linear', probability=True,
                                random_state=random_state))
y_score = classifier.fit(X_train, y_train).decision_function(X_test)

3. 计算每一类的ROC,micro-average ROC和macro-average ROC

3.1 每一类的ROC

# 计算每一类的ROC
fpr =dict()
tpr =dict()
roc_auc =dict()
for iin range(n_classes):
fpr[i], tpr[i], _ = roc_curve(y_test[:, i], y_score[:, i])
roc_auc[i] = auc(fpr[i], tpr[i])
image

3.2 micro-average ROC

# Compute micro-average ROC curve and ROC area
fpr["micro"], tpr["micro"], _ = roc_curve(y_test.ravel(), y_score.ravel())
roc_auc["micro"] = auc(fpr["micro"], tpr["micro"])

3.3 macro-average ROC

# Compute macro-average ROC curve and ROC area
# First aggregate all false positive rates
all_fpr = np.unique(np.concatenate([fpr[i]for iin range(n_classes)]))
# Then interpolate all ROC curves at this points
mean_tpr = np.zeros_like(all_fpr)
for iin range(n_classes):
mean_tpr += interp(all_fpr, fpr[i], tpr[i])
# Finally average it and compute AUC
mean_tpr /= n_classes
fpr["macro"] = all_fpr
tpr["macro"] = mean_tpr
roc_auc["macro"] = auc(fpr["macro"], tpr["macro"])

4. 特定类和多分类ROC曲线绘制

4.1 特定类ROC绘制

我在这里定义了一个函数,需要用主函数设置which_class,选择绘制哪一类的ROC

def roc_singleclass(which_class=1):
plt.figure()
lw =2 # 图的线条宽度
    plt.plot(fpr[which_class], tpr[which_class], color='darkorange',
            lw=lw, label='ROC curve (area = %0.2f)' % roc_auc[which_class])
plt.plot([0, 1], [0, 1], color='navy', lw=lw, linestyle='--')
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 example')
plt.legend(loc="lower right")
plt.show()
image

4.2 多分类ROC曲线绘制

# Plot all ROC curves
lw =2
plt.figure()
plt.plot(fpr["micro"], tpr["micro"],
        label='micro-average ROC curve (area = {0:0.2f})'
              ''.format(roc_auc["micro"]),
        color='deeppink', linestyle=':', linewidth=4)
plt.plot(fpr["macro"], tpr["macro"],
        label='macro-average ROC curve (area = {0:0.2f})'
              ''.format(roc_auc["macro"]),
        color='navy', linestyle=':', linewidth=4)
colors = cycle(['aqua', 'darkorange', 'cornflowerblue'])
for i, colorin zip(range(n_classes), colors):
plt.plot(fpr[i], tpr[i], color=color, lw=lw,
            label='ROC curve of class {0} (area = {1:0.2f})'
                  ''.format(i, roc_auc[i]))
plt.plot([0, 1], [0, 1], 'k--', lw=lw)
plt.xlim([0.0, 1.0])
plt.ylim([0.0, 1.05])
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.title('Some extension of Receiver operating characteristic to multi-class')
plt.legend(loc="lower right")
plt.show()
image

5. ROC曲线结果解读

ROC、AUC、micro/macro-average ROC curve的理论部分可以看这个ROC理论,本节简要解读一下多类别ROC图的结果:
这个是直接三分类的训练集:测试集=1:1的ROC曲线,class0代表鉴别正常组织和两种癌组织,class1代表鉴别低恶度癌和另外两种组织,class2代表鉴别高恶度癌和另外两种组织,可以看出class2的AUC值为1,表明Hub基因建立的模型确实可以有效鉴别ATC和另外两种预后较好的组织。

参考资料

[1] sklearn中文官方文档:支持向量机
[2] Receiver Operating Characteristic (ROC)
[3] Receiver Operating Characteristic (ROC) with cross validation

你可能感兴趣的:(分析技术 | 建立预测模型及模型的ROC曲线绘制)