How to rank the instances based on prediction probability in sklearn

与世无争的帅哥 提交于 2019-12-08 14:00:40

Cross_val predict is a function which does not return the classifier (in your case the SVC) as part of its output. Therefore you don't get access to the latter and its methods and attributes.

To perform cross-validation and calculate probabilities use scikit-learn's GridSearchCV or RandomizedSearchCV. If you want just a simple cross-validation, pass a parameter dictionary with only one parameter. Once you have the probabilities you can use either pandas or numpy to sort them according to a particular class (1 in the example below).

from sklearn.svm import SVC
from sklearn.model_selection import GridSearchCV
from sklearn import datasets
import pandas as pd
import numpy as np

iris = datasets.load_iris()
X = iris.data
y = iris.target

parameters = {'kernel':(['rbf'])}
svc = SVC(gamma="scale", probability=True)
clf = GridSearchCV(svc, parameters, cv=10)
clf.fit(iris.data, iris.target)

probabilities = pd.DataFrame(clf.predict_proba(X), columns=clf.classes_)
probabilities['Y'] = iris.target
probabilities.columns.name = 'Classes'
probabilities.head()

# Sorting in ascending order by the probability of class 1. 
# Showing only the first five rows.
# Note that all information (indices, values) is in one place
probabilities.sort_values(1).head()
Out[49]: 
Classes         0         1         2  Y
100      0.006197  0.000498  0.993305  2
109      0.009019  0.001023  0.989959  2
143      0.006664  0.001089  0.992248  2
105      0.010763  0.001120  0.988117  2
144      0.006964  0.001295  0.991741  2

# Alternatively using numpy
indices = np.argsort(probabilities.values[:,1])
proba = probabilities.values[indices, :]

print(indices)
[100 109 143 105 144 122 135 118 104 107 102 140 130 117 120 136 132 131
 128 124 125 108  22 148 112  13 115  14  32  37  33 114  35  40  16   4
  42 103   2   0   6  36 139  19 145  38  17  47  48  28  49  15  46 129
  10  21   7  27  12  39   8  11   1   3   9  45  34 116  29 137   5  31
  26  30 141  43  18 111  25  20  41  44  24  23 147 134 113 101 142 110
 146 121 149  83 123 127  77 119 133 126 138  70  72 106  52  76  56  86
  68  63  54  98  50  84  66  85  78  91  73  51  57  58  93  55  87  75
  65  79  90  64  61  60  97  74  94  59  96  81  88  53  95  99  89  80
  71  82  69  92  67  62]

# Showing only the first five values of the sorted probabilities for class 1
print(proba[:5, 1])
[0.00049785 0.00102258 0.00108851 0.00112034 0.00129501]
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!