我如何找到模型将输入分类为 [0,1] 的概率

How can i find the probability of a model classifying an input as [0,1]

我正在处理 class化问题,我想在其中找到 "probability of an input being classified as [1,0]" 和 "not [1,0]"

我尝试使用 SVC 的 predict_proba 方法,它给出了 class 的概率,而我并不是在寻找

from sklearn.svm import SVC

model = SVC(probability=True)
model.fit(final_data,foreclosure_y)
results = model.predict_proba(final_data_test)[0]

我希望我的输出是这样的

index,y
---------    
0,0.45
1,0.62
2,0.43
3,0.12
4,0.55

注意:以上输出采用 .csv 格式,其中 y 是 test_y

这里的 y 列是索引从 0 到 4 的每个实例的概率,可以 class 化为 0 或 1

例如:- 索引 0 有 0.45 的概率被 class 化为 0 或 1

注意

sum([0.58502114, 0.41497886])
# 1.0

predict_proba 给出 both 你的 classes 的概率(因此数组元素总和为 1),按照它们出现的顺序model.classes_;引用 docs(在这种情况下 总是 你最好的朋友):

Returns the probability of the sample for each class in the model. The columns correspond to the classes in sorted order, as they appear in the attribute classes_.

这里有一个玩具数据的例子来说明这个想法:

from sklearn.svm import SVC
model = SVC(probability=True)
X = [[1,2,3], [2,3,4]] # feature vectors
Y = [0, 1] # classes
model.fit(X, Y)

现在让我们得到训练集中第一个实例的预测概率[1,2,3]:

model.predict_proba(X)[0]
# array([0.39097541, 0.60902459])

好的,顺序是什么 - 即哪个概率属于哪个 class?

model.classes_
# array([0, 1])

因此,这意味着实例属于 class 0 的概率是数组 0.39097541 的第一个元素,而属于 class 的概率] 1是第二个元素0.60902459;再次,它们总和为 1,正如预期的那样:

sum([0.39097541, 0.60902459])
# 1.0

更新

现在,在您需要的输出中,我们不会同时放入两个概率;按照惯例,对于二进制 class 化,我们只包括属于 class 1 的每个实例的概率;以下是我们如何为上面显示的只有 2 个实例的玩具数据集 X 执行此操作:

pred = model.predict_proba(X)
pred
# array([[ 0.39097541,  0.60902459],
#        [ 0.60705475,  0.39294525]])

import pandas as pd
out = pd.DataFrame(pred[:,1],columns=['y']) # keep only the second element of the arrays in pred, i.e. the probability for class 1
print(out)

结果:

          y
0  0.609025
1  0.392945