【问题标题】:Why the auc is so different from logistic regression of sklearn and R为什么 auc 与 sklearn 和 R 的逻辑回归如此不同
【发布时间】:2016-10-18 18:12:21
【问题描述】:

我使用相同的数据集在 R 和 python sklearn 中训练逻辑回归模型。数据集不平衡。 而且我发现 auc 完全不同。 这是python的代码:

model_logistic = linear_model.LogisticRegression() #auc 0.623
model_logistic.fit(train_x, train_y)
pred_logistic = model_logistic.predict(test_x) #mean:0.0235 var:0.023
print "logistic auc: ", sklearn.metrics.roc_auc_score(test_y,pred_logistic)

这是R的代码:

glm_fit <- glm(label ~ watch_cnt_7 + bid_cnt_7 + vi_cnt_itm_1 + 
ITEM_PRICE  + add_to_cart_cnt_7 + offer_cnt_7 +     
 dwell_dlta_4to2 + 
 vi_cnt_itm_2 + asq_cnt_7 + watch_cnt_14to7 + dwell_dlta_6to4 + 
auct_type + vi_cnt_itm_3 + vi_cnt_itm_7 + vi_dlta_4to2 + 
vi_cnt_itm_4 + vi_dlta_6to4 + tenure + sum_SRCH_item_7 + 
vi_cnt_itm_6 + dwell_itm_3 + 
offer_cnt_14to7 + #
dwell_itm_2 + dwell_itm_6 + CNDTN_ROLLUP_ID +
dwell_itm_5 + dwell_itm_4 + dwell_itm_1+ 
bid_cnt_14to7 + item_prchsd_cnt_14to7 +  #
dwell_itm_7  + median_day_rate + vb_ratio
, data = train, family=binomial())
p_lm<-predict(glm_fit, test[1:nc-1],type = "response" )
pred_lm <- prediction(p_lm,test$label)
auc <- performance(pred_lm,'auc')@y.values

python 的 auc 为 0.623,而 R 为 0.887。 所以我想知道 sklearn 逻辑回归有什么问题以及如何解决它。谢谢。

【问题讨论】:

  • 一方面,1:nc-1 是错误的
  • 那个错误没什么大不了的。 1:nc-1 将与 0:(nc-1) 相同,用作选择时,将等效于 1:(nc-1)。
  • 如果您创建了一个可重现的小示例,将会很有帮助。例如,您可以在 R 中创建一个小的简单数据集,然后在 Python 和 R 中读取并运行。此外,确认两个模型中的逻辑回归系数相同会很有帮助。
  • 我在训练前更改了模型的参数:model = linear_model.LogisticRegression(C=10000,class_weight='auto', random_state=42,fit_intercept=True) 并且新的 auc 变为 0.83。

标签: python r scikit-learn logistic-regression glm


【解决方案1】:

在 python 脚本中,您应该使用predict_proba 来获取两个类的概率估计值,并将正类的第二列作为roc_auc_score 的输入,因为 ROC 曲线是通过改变概率阈值绘制的。

pred_logistic = model_logistic.predict_proba(test_x)[:,1]

【讨论】:

  • 非常感谢您的回复,auc sklearn 的回报比 R 的 glm 高 0.90。我还想向您寻求建议,放入 sklearn 逻辑模型中的参数的差异会对结果(如 auc)产生很大影响吗?非常感谢。
  • @yanachen,LogisticRegression 中有几个参数。我建议您调整penaltyCclass_weight。此外,缩放特征也可能对线性模型产生影响。
猜你喜欢
  • 1970-01-01
  • 2021-06-15
  • 2021-03-11
  • 2016-03-06
  • 2018-04-14
  • 2021-12-19
  • 2023-04-04
  • 1970-01-01
  • 2023-04-07
相关资源
最近更新 更多