默认情况下,scikit-learn的所有正则化线性回归技术都会随着alpha的增加将模型系数w拉向0。是否可以将系数拉向预定义值?在我的应用程序中,我有这样的值,这些值是从类似但更大的数据集的先前分析中获得的。换句话说,我能否从一个模型转移知识到另一个模型?
这个例子的结果非常相似,但你至少可以看出指定一个
LassoCV
的文档中写道:
The optimization objective for Lasso is:
(1 / (2 * n_samples)) * ||y - Xw||^2_2 + alpha * ||w||_1
理论上,通过更改上述内容,很容易将之前获得的系数w0
纳入其中。
问题在于实际优化是由Cython函数(1 / (2 * n_samples)) * ||y - Xw||^2_2 + alpha * ||w - w0||_1
enet_coordinate_descent
(通过lasso_path
和enet_path
调用)执行的。如果我想更改它,是否需要分叉、修改并重新编译整个sklearn.linear_model
包或重新实现整个优化例程?
示例
以下代码定义了一个包含4个特征和相应响应向量y
的数据集X
。import numpy as np
from sklearn.linear_model import LassoCV
n = 50
x1 = np.random.normal(10, 8, n)
x2 = np.random.normal(8, 6, n)
X = np.column_stack([x1, x1 ** 2, x2, x2 ** 2])
y = .8 * x1 + .2 * x2 + .7 * x2**2 + np.random.normal(0, 3, n)
cv = LassoCV(cv=10).fit(X, y)
得到的系数和 alpha
为
>>> print(cv.coef_)
[ 0.46262115 0.01245427 0. 0.70642803]
>>> print(cv.alpha_)
7.63613474003
如果我们事先知道两个系数的值w0 = np.array([.8, 0, .2, 0])
,那么如何将其合并?
基于@lejlot答案的最终解决方案
我最终采用了Adam而不是使用普通的GD。此解决方案仅适用于给定alpha
值的套索拟合,它不像LassoCV
自己找到alpha
值(但可以在其上方轻松添加一层CV)。
from autograd import numpy as np
from autograd import grad
from autograd.optimizers import adam
def fit_lasso(X, y, alpha=0, W0=None):
if W0 is None:
W0 = np.zeros(X.shape[1])
def l1_loss(W, i):
# i is only used for compatibility with adam
return np.mean((np.dot(X, W) - y) ** 2) + alpha * np.sum(np.abs(W - W0))
gradient = grad(l1_loss)
def print_w(w, i, g):
if (i + 1) % 250 is 0:
print("After %i step: w = %s" % (i + 1, np.array2string(w.T)))
W_init = np.random.normal(size=(X.shape[1], 1))
W = adam(gradient, W_init, step_size=.1, num_iters=1000, callback=print_w)
return W
n = 50
x1 = np.random.normal(10, 8, n)
x2 = np.random.normal(8, 6, n)
X = np.column_stack([x1, x1 ** 2, x2, x2 ** 2])
y = .8 * x1 + .2 * x2 + .7 * x2 ** 2 + np.random.normal(0, 3, n)
fit_lasso(X, y, alpha=30)
fit_lasso(X, y, alpha=30, W0=np.array([.8, 0, .2, 0]))
After 250 step: w = [[ 0.886 0.131 0.005 0.291]]
After 500 step: w = [[ 0.886 0.131 0.003 0.291]]
After 750 step: w = [[ 0.886 0.131 0.013 0.291]]
After 1000 step: w = [[ 0.887 0.131 0.013 0.292]]
After 250 step: w = [[ 0.868 0.129 0.728 0.247]]
After 500 step: w = [[ 0.803 0.132 0.717 0.249]]
After 750 step: w = [[ 0.801 0.132 0.714 0.249]]
After 1000 step: w = [[ 0.801 0.132 0.714 0.249]]
这个例子的结果非常相似,但你至少可以看出指定一个
W0
避免了模型杀死第三个系数。只有当你使用一个alpha
>20左右时,这种影响才会显现。