如何使SGDClassifier反映不确定性
如何让 sklearn的 SGDClassifier
显示它预测结果的不确定性呢?
我想确认一下,SGDClassifier
在输入数据不完全对应任何标签时,会不会报告50%的概率。然而,我发现这个分类器总是100%确定。
我用以下脚本进行测试:
from sklearn.linear_model import SGDClassifier
c = SGDClassifier(loss="log")
#c = SGDClassifier(loss="modified_huber")
X = [
# always -1
[1,0,0],
[1,0,0],
[1,0,0],
[1,0,0],
# always +1
[0,0,1],
[0,0,1],
[0,0,1],
[0,0,1],
# uncertain
[0,1,0],
[0,1,0],
[0,1,0],
[0,1,0],
[0,1,0],
[0,1,0],
[0,1,0],
[0,1,0],
]
y = [
-1,
-1,
-1,
-1,
+1,
+1,
+1,
+1,
-1,
+1,
-1,
+1,
-1,
+1,
-1,
+1,
]
def lookup_prob_class(c, dist):
a = sorted(zip(dist, c.classes_))
best_prob, best_class = a[-1]
return best_prob, best_class
c.fit(X, y)
probs = c.predict_proba(X)
print 'probs:'
for dist, true_value in zip(probs, y):
prob, value = lookup_prob_class(c, dist)
print '%.02f'%prob, value, true_value
如你所见,我的训练数据总是将 -1 关联到输入数据 [1,0,0],将 +1 关联到 [0,0,1],而 [0,1,0] 则是50/50。
因此,我期待 predict_proba()
对输入 [0,1,0] 返回0.5的结果。但实际上,它报告的概率是100%。这是为什么呢?我该如何解决这个问题?
有趣的是,把 SGDClassifier
换成 DecisionTreeClassifier
或 RandomForestClassifier
的话,确实能得到我期待的输出。
1 个回答
5
这段话提到了一些不确定性:
>>> c.predict_proba(X)
array([[ 9.97254333e-01, 2.74566740e-03],
[ 9.97254333e-01, 2.74566740e-03],
[ 9.97254333e-01, 2.74566740e-03],
[ 9.97254333e-01, 2.74566740e-03],
[ 1.61231111e-06, 9.99998388e-01],
[ 1.61231111e-06, 9.99998388e-01],
[ 1.61231111e-06, 9.99998388e-01],
[ 1.61231111e-06, 9.99998388e-01],
[ 1.24171982e-04, 9.99875828e-01],
[ 1.24171982e-04, 9.99875828e-01],
[ 1.24171982e-04, 9.99875828e-01],
[ 1.24171982e-04, 9.99875828e-01],
[ 1.24171982e-04, 9.99875828e-01],
[ 1.24171982e-04, 9.99875828e-01],
[ 1.24171982e-04, 9.99875828e-01],
[ 1.24171982e-04, 9.99875828e-01]])
如果你想让模型表现得更不确定,就需要对它进行更强的约束。这可以通过调整 alpha
参数来实现:
>>> c = SGDClassifier(loss="log", alpha=1)
>>> c.fit(X, y)
SGDClassifier(alpha=1, class_weight=None, epsilon=0.1, eta0=0.0,
fit_intercept=True, l1_ratio=0.15, learning_rate='optimal',
loss='log', n_iter=5, n_jobs=1, penalty='l2', power_t=0.5,
random_state=None, shuffle=False, verbose=0, warm_start=False)
>>> c.predict_proba(X)
array([[ 0.58782817, 0.41217183],
[ 0.58782817, 0.41217183],
[ 0.58782817, 0.41217183],
[ 0.58782817, 0.41217183],
[ 0.53000442, 0.46999558],
[ 0.53000442, 0.46999558],
[ 0.53000442, 0.46999558],
[ 0.53000442, 0.46999558],
[ 0.55579239, 0.44420761],
[ 0.55579239, 0.44420761],
[ 0.55579239, 0.44420761],
[ 0.55579239, 0.44420761],
[ 0.55579239, 0.44420761],
[ 0.55579239, 0.44420761],
[ 0.55579239, 0.44420761],
[ 0.55579239, 0.44420761]])
alpha
是对高特征权重的一种惩罚,也就是说,alpha
值越高,权重的增长就越受到限制,线性模型的值就会变得不那么极端,逻辑概率的估计也会更接近 ½。通常,这个参数是通过交叉验证来调整的。