文章原创,最近更新:2018-06-6
1.逻辑回归阈值对结果的影响
课程来源: python数据分析与机器学习实战-唐宇迪
课程资料:这里所涉及到的练习资料creditcard.csv相关的链接以及密码如下:
链接: https://pan.baidu.com/s/1APgU4cTAaM9zb8_xAIc41Q 密码: xgg7
在当前的指标下,去做逻辑回归,有做阈值得到一个结果,算出其中的recall值,能不能使得模型的评估标准可以进行人为的控制一下呢?还是要回到Logistic函数.
之前有提到案例比如,0.7>0.5是1类别,0.4<0.5是0类别,那我能不能通过一个改变,这个0.5是谁制定的呢?好像是系统默认的,把0.5当成是一个平均值.那能不能将0.5人为的做一些变化呢?
当然也是可以的.
比如在sigmoid函数上画一条横线,具体如下:
为了让标准更加严格一些,只有>0.6才预测成1类,比如:0.7>0.6预测成1类,0.55<0.6预测成0类.
当前模型最终的一个结果是可以人为可控的,可以自己设置一些阈值,我们把刚才y=0.6,这个叫自定义阈值.
如果将这个阈值自定义成y=09,那么筛选就会更加严格一些,只有那些具备异常可能性的,才把它当成一个异常的.
如果把阈值放低一些,那么这种情况下就相当于宁可错杀一万也不放过一个的感觉.对于样本而言,不管它的预测值是什么样的?比如y=0.1,只要>0.1就设置为异常.
那么在python中怎么样认为的设置阈值呢?
- 与之前阈值设置的区别
1)之前在python中预测值的设置是类别值,代码是如下:
y_pred_undersample = lr.predict(X_test.values)
2)现在预测的是相当于概率值,代码是如下:
y_pred_undersample_proba = lr.predict_proba(X_test_undersample.values)
备注:有了概率值可以跟指定的一系列阈值进行比较.
- 阈值的设定
thresholds = [0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9]
- 指定画图域
plt.figure(figsize=(10,10))
完整案例代码如下:
lr = LogisticRegression(C = 0.01, penalty = 'l1')
lr.fit(X_train_undersample,y_train_undersample.values.ravel())
y_pred_undersample_proba = lr.predict_proba(X_test_undersample.values)
thresholds = [0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9]
plt.figure(figsize=(10,10))
j = 1
for i in thresholds:
y_test_predictions_high_recall = y_pred_undersample_proba[:,1] > i
plt.subplot(3,3,j)
j += 1
# Compute confusion matrix
cnf_matrix = confusion_matrix(y_test_undersample,y_test_predictions_high_recall)
np.set_printoptions(precision=2)
print("Recall metric in the testing dataset: ", cnf_matrix[1,1]/(cnf_matrix[1,0]+cnf_matrix[1,1]))
# Plot non-normalized confusion matrix
class_names = [0,1]
plot_confusion_matrix(cnf_matrix
, classes=class_names
, title='Threshold >= %s'%i)
输出结果如下:
Recall metric in the testing dataset: 1.0
Recall metric in the testing dataset: 1.0
Recall metric in the testing dataset: 1.0
Recall metric in the testing dataset: 0.986394557823
Recall metric in the testing dataset: 0.931972789116
Recall metric in the testing dataset: 0.884353741497
Recall metric in the testing dataset: 0.836734693878
Recall metric in the testing dataset: 0.748299319728
Recall metric in the testing dataset: 0.571428571429
通过结果可以看出,随着阈值的上升,它的recall值的变化,recall值由1.0下降到0.57.图上可以看出,不同的阈值,混淆矩阵是长什么样子的.
- 阈值>=0.1
它的recall值是147/(147+0),当前检测的样本所有的异常值都检查到了.而误杀值149.精度很低,评估一个模型的时候需要多层次进行评估.不能把所有的样本都预测成异常样本.
阈值>=0.2以及阈值>=0.3
它的recall值是满的,精度值还是很低.阈值>=0.4以上
误杀值越来越少,精度偏高了一些.但是阈值设置太大也不可以,比如阈值>=0.9,要求太严了,有些就检测不到了.recall值就会偏低,只有大约60%左右.只有阈值>=0.5的结果看起来不错.
在实际回归进行建模的时候,也要从实际的角度进行出发,阈值应该怎么进行一个设定.比如误杀率不能高于百分之十,然后可以根据自己的实际需求去选择这些参数.