【问题标题】:Find optimal Lasso/L1 regularization strength using cross validation for logistic regression in scikit learn在 scikit learn 中使用逻辑回归的交叉验证找到最佳 Lasso/L1 正则化强度
【发布时间】:2020-09-21 07:59:45
【问题描述】:

对于我的逻辑回归模型,我想使用交叉验证(例如:5 倍)来评估最佳 L1 正则化强度,而不是单个测试训练集,如下所示:

from sklearn.model_selection import train_test_split
train_x, test_x, train_y, test_y = train_test_split(X_scaled,y, stratify=y, test_size=0.3, 
   random_state=2)

#Evaluate L1 regularization strengths for reducing features in final model 
C = [10, 1, .1, 0.05,.01,.001] # As C decreases, more coefficients go to zero

for c in C:
    clf = LogisticRegression(penalty='l1', C=c, solver='liblinear', class_weight="balanced")
    clf.fit(train_x, train_y)
    pred_y=clf.predict(test_x) 
    print("Model performance with Inverse Regularization Parameteter, C = 1/λ VALUE: ", c)
    cr=metrics.classification_report(test_y, pred_y)
    print(cr)
    print('')

有人可以告诉我如何使用交叉验证(即,不重复上述代码 5 次和不同的随机状态)在 5 个不同的测试训练集上执行此操作吗?

【问题讨论】:

  • 通过“distinct”,您是指将原始 X_scaled 数据集随机拆分为不同(但重叠)的训练集,还是将您的 x_train 进一步细分为 5 个不包含重叠的集实例?
  • 我的意思是 X 和 y 中的 5 个随机分层分割。也就是说,由于样本是随机拆分的,因此允许重叠。

标签: python scikit-learn cross-validation lasso-regression


【解决方案1】:

实际上,classification_report 作为指标在sklearn.model_selection.cross_val_score 内部并未定义为评分指标。所以,我将在下面的代码中使用f1_micro:

from sklearn.model_selection import cross_val_score

#Evaluate L1 regularization strengths for reducing features in final model 
C = [10, 1, .1, 0.05,.01,.001] # As C decreases, more coefficients go to zero

for c in C:
    clf = LogisticRegression(penalty='l1', C=c, solver='liblinear', class_weight="balanced")
    # using data before splitting (X_scaled) and (y)
    scores = cross_val_score(clf, X_scaled, y, cv=5, scoring="f1_micro")  #<-- add this
    print(scores)  #<-- add this

变量scores 现在是一个包含五个值的列表,表示您的分类器在原始数据的五个不同拆分中的f1_micro 值。

如果您想在sklearn.model_selection.cross_val_score 中使用另一个评分指标,您可以使用以下命令获取所有可用的评分指标:

print(metrics.SCORERS.keys())

此外,您可以使用多个评分指标;以下同时使用f1_micro 和f1_macro:

from sklearn.model_selection import cross_validate

cross_validate(clf, X_scaled, y, cv=5, scoring=["f1_micro", "f1_macro"])  

【讨论】:

  • 太棒了 - 我已经将 cross_val_score 用于其他指标,并且从未考虑过使用正则化强度。
  • 能否请您完整更新上面的代码以填补空白?
  • 是的,当然。给你
  • @Anwaric - 经过额外审查,我对上述建议有点不满意,因为它仅评估了 L1 正则化强度对 X 和 y 数据的单个随机拆分的影响(上面示例中的 random_state = 2 )。如何重新调整此代码,使其跨数据的多个随机分层拆分进行 L1 正则化强度评估?这是我最初的问题——在我给你的回复中可能不是很清楚。
  • 我已经编辑了我的答案...我已经评论了不再需要的部分。另外,我还添加了一些注释
猜你喜欢
  • 2021-02-07
  • 2018-04-02
  • 2016-02-21
  • 2017-09-11
  • 2017-02-20
  • 2020-09-27
  • 2014-07-30
  • 1970-01-01
  • 2021-01-25
相关资源
最近更新 更多