【问题标题】:Selecting columns of dataframe where Lasso coefficient is nonzero选择套索系数非零的数据框列
【发布时间】:2020-10-01 01:22:24
【问题描述】:

我使用 scikit 和 pandas 对数据集进行了 LASSO 回归。我想尝试使 OLS 适合 LASSO 选择的功能。我有类似的东西

lassomodel = LassoCV(alphas = [1, 0.1, 0.001, 0.0005]).fit(X_train, y_train)

lassomodel.coef_ 

我想获取所有 LASSO 系数不等于零的特征的数据帧或 numpy 数组。

【问题讨论】:

    标签: python pandas numpy scikit-learn lasso-regression


    【解决方案1】:

    IIUC,您可以在系数不等于 0 的 X_train 上使用布尔索引

    如果 X_train 是一个 numpy 数组,那么你可以这样做:

    X_train[:,lassomodel.coef_!=0]
    

    如果 X_train 是 pandas 数据框,那么您可以这样做:

    X_train.iloc[:,lassomodel.coef_!=0]
    

    【讨论】:

    • 不幸的是,我收到以下错误:TypeError: '(slice(None, None, None),array([ huge array of truth values]))' is an invalid key
    • 添加 .iloc 有效 X_train.iloc[:, lasso.coef_!=0]
    • @lgegre 我以为 X_train 是一个数组,我的错,将在答案中添加此选项以使其更清晰
    猜你喜欢
    • 2018-09-21
    • 1970-01-01
    • 1970-01-01
    • 2020-04-27
    • 2013-04-12
    • 1970-01-01
    相关资源
    最近更新 更多