【问题标题】:SkLearn: how to add custom constraint to the Lasso implementation?SkLearn:如何向 Lasso 实现添加自定义约束?
【发布时间】:2022-12-17 14:17:36
【问题描述】:
我正在使用 scikit-learn's Lasso implementation 来解决给定的过度确定的问题,该问题对贝塔的稀疏性和收缩感兴趣。但是,我对我的特定问题有一个额外的要求,即为每列(或预测变量)添加一个按元素乘以解决方案的约束,以便每列的总和为零。
假设我有一个 A 超定的 Ax=b,我需要找到最好的 x。然后我使用套索,但我还需要 A*x 列的总和为零或接近零,即
A = pd.DataFrame(...)
x = ... # lasso solution at iter N
Axx = A*x # note this is element-wise multiplication and not MVM
# my constraint
if Axx.sum(axis=0).max() < 1e-10:
# accept candidate solution
return True
else:
# constraint not satisfied
return False
如何使用这个额外的特定于问题的约束来扩展linear_model.Lasso?
【问题讨论】:
标签:
python
machine-learning
scikit-learn
【解决方案1】:
您可以通过在 scikit-learn 的 Lasso 实现中使用约束参数来实现这一点。此参数允许您指定 Ax = b 形式的解的约束列表,其中 A 和 b 是矩阵或向量。
from sklearn.linear_model import Lasso
import numpy as np
# Define A and b
A = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
b = np.array([1, 2, 3])
# Define the column-wise constraint as Ax = 0
col_constraint = np.ones((A.shape[1], A.shape[1]))
b_constraint = np.zeros(A.shape[1])
# Solve the Lasso problem with the column-wise constraint
lasso = Lasso(alpha=1.0, constraints=[col_constraint, b_constraint])
x = lasso.fit(A, b)