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

2024-10-02 18:16:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试在python中使用套索回归。 我正在使用scikit学习库中的套索函数。在

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

以下是我目前的培训代码

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是数据集市,我试图将某些列的系数保持为非零。在

在python中提供了这个参数,但是这个参数是怎么做到的?在

下面是我在R中的代码

^{pr2}$

Tags: 代码idtruedf参数responsenpscikit
1条回答
网友
1楼 · 发布于 2024-10-02 18:16:00

恐怕不行。当然这不是一个理论问题,只是一个设计决定。在

我的推理是基于可用的API的,虽然有时会有未记录的函数,但这次我不认为有您需要的,因为user-guide已经以1-factor-norm-of-all形式alpha*||w||_1发布了这个问题

根据您的设置,您可能会修改sklearn的代码(有点害怕CD调整),甚至使用scipy.optimize公司(尽管后者可能会慢一点)。在

下面是一些示例scipy.optimize公司接近。我去掉了intercept,简化了问题

""" 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])

输出:

^{pr2}$

相关问题 更多 >