如何配置套索回归以不惩罚某些变量?

时间:2017-06-26 10:02:50

标签: python scikit-learn

我正在尝试在python中使用套索回归。 我目前正在使用scikit-learn库中的套索功能。

我希望我的模型在训练时不要惩罚某些变量。 (仅惩罚其余变量)

以下是我目前的培训代码

rg_mdt = linear_model.LassoCV(alphas=np.array(10**np.linspace(0, -4, 100)), fit_intercept=True, normalize=True, cv=10)
rg_mdt.fit(df_mdt_rgmt.loc[df_mdt_rgmt.CLUSTER_ID == k].drop(['RESPONSE', 'CLUSTER_ID'], axis=1), df_mdt_rgmt.loc[df_mdt_rgmt.CLUSTER_ID == k, 'RESPONSE'])

df_mdt_rgmt是数据集市,我试图将某些列的系数保持为非零。

R中的glmnet提供了“惩罚因子”参数,让我这样做,但我怎么能在python scikit-learn中做到这一点?

以下是我在R

中的代码
get.Lassomodel <- function(TB.EXP, TB.RSP){
  VT.PEN <- rep(1, ncol(TB.EXP))
  VT.PEN[which(colnames(TB.EXP) == "DC_RATE")] <- 0
  VT.PEN[which(colnames(TB.EXP) == "FR_PRICE_PW_REP")] <- 0

  VT.GRID <- 10^seq(0, -4, length=100)

  REG.MOD <- cv.glmnet(as.matrix(TB.EXP), as.matrix(TB.RSP), alpha=1, 
  lambda=VT.GRID, penalty.factor=VT.PEN, nfolds=10, intercept=TRUE)

  return(REG.MOD)
}

1 个答案:

答案 0 :(得分:2)

我担心你不能。当然,这不是一个理论问题,而只是一个设计决策。

我的推理基于可用的API,虽然有时会有无证件的功能,但这次我认为没有你需要的东西,因为user-guide已经发布了这个问题。 1-factor-all-all-form alpha*||w||_1

根据您的设置,您可能会修改sklearn的代码(有点害怕CD调整),甚至使用scipy.optimize实现自定义目标(尽管后者可能会慢一些)。

这是一个显示scipy.optimize方法的示例。我通过删除拦截来简化问题。

""" data """
import numpy as np
from sklearn import datasets
diabetes = datasets.load_diabetes()
A = diabetes.data[:150]
y = diabetes.target[:150]
alpha=0.1
weights=np.ones(A.shape[1])

""" sklearn """
from sklearn import linear_model
clf = linear_model.Lasso(alpha=alpha, fit_intercept=False)
clf.fit(A, y)

""" scipy """
from scipy.optimize import minimize
def lasso(x):  # following sklearn's definition from user-guide!
    return (1. / (2*A.shape[0])) * np.square(np.linalg.norm(A.dot(x) - y, 2)) + alpha * np.linalg.norm(weights*x, 1)

""" Test with weights = 1 """
x0 = np.zeros(A.shape[1])
res = minimize(lasso, x0, method='L-BFGS-B', options={'disp': False})
print('Equal weights')
print(lasso(clf.coef_), clf.coef_[:5])
print(lasso(res.x), res.x[:5])

""" Test scipy-based with special weights """
weights[[0, 3, 5]] = 0.0
res = minimize(lasso, x0, method='L-BFGS-B', options={'disp': False})
print('Specific weights')
print(lasso(res.x), res.x[:5])

输出:

Equal weights
12467.4614224 [-524.03922009  -75.41111354  820.0330707    40.08184085 -307.86020107]
12467.6514697 [-526.7102518   -67.42487561  825.70158417   40.04699607 -271.02909258]
Specific weights
12362.6078842 [ -6.12843589e+02  -1.51628334e+01   8.47561732e+02   9.54387812e+01
  -1.02957112e-05]