NonLinear Regression & Lasso & Homotopy Method

9 篇文章 0 订阅
5 篇文章 0 订阅

Part One : Coordinate Descent for Lasso

The Lasso optimization problem can be formulated as
w ^ ∈ a r g m i n w ∈ R d ∑ i = 1 m ( h w ( x i ) − y i ) 2 + λ ∥ w ∥ 1 , \hat{w}\in{ argmin_{w\in R^{d}}\sum_{i=1}^{m}(h_{w}(x_{i})-y_{i})^{2}+\lambda\|w\|_{1}}, w^argminwRdi=1m(hw(xi)yi)2+λw1,
where h w ( x ) = w T x h_{w}(x)=w^{T}x hw(x)=wTx, and ∥ w ∥ 1 = ∑ i = 1 d ∣ w i ∣ \|w\|_{1}=\sum_{i=1}^{d}|w_{i}| w1=i=1dwi. Note that to align with Murpy’s formulation below, and for historical reasons, we are using the total square loss, rather than the average square loss, in the objective function.

Since the ℓ 1 \ell_{1} 1-regularization term in the objective function is non-differentiable, it’s not immediately clear how gradient descent or SGD could be used to solve this optimization problem directly.

Another approach to solving optimization problems is coordinate descent, in which at each step we optimize over one component of the unknown parameter vector, fixing all other components. The descent path so obtained is a sequence of steps, each of which is parallel to a coordinate axis in R d R^{d} Rd, hence the name. It turns out that for the Lasso optimization problem, we can find a closed form solution for optimization over a single component fixing all other components. This gives us the following algorithm, known as the shooting algorithm.

The "soft thresholding’’ function is defined as
soft ( a , δ ) = sign ( a ) ( ∣ a ∣ − δ ) + , \text{soft}\left(a,\delta\right)=\text{sign}(a)\left(\left|a\right|-\delta\right)_{+}, soft(a,δ)=sign(a)(aδ)+,
for any a , δ ∈ R a,\delta\in R a,δR.

NOTE: The algorithm does not account for the case that a j = c j = 0 a_{j}=c_{j}=0 aj=cj=0, which occurs when the j j jth column of X X X is identically 0 0 0. One can either eliminate the column (as it cannot possibly help the solution), or you can set w j = 0 w_{j}=0 wj=0 in that case since it is, as you can easily verify, the coordinate minimizer. Note also that Murphy is suggesting to initialize the optimization with the ridge regession solution. Although theoretically this is not necessary (with exact computations and enough time, coordinate descent will converge for lasso from any starting point), in practice it’s helpful to start as close to the solution as we’re able.

There are a few tricks that can make selecting the hyperparameter λ \lambda λ easier and faster. First, as we’ll see in a later problem, you can show that for any λ ≥ 2 ∥ X T ( y − y ˉ ) ∥ ∞ \lambda\ge2\|X^{T}(y-\bar{y})\|_{\infty} λ2XT(yyˉ), the estimated weight vector w ^ \hat{w} w^ is entirely zero, where y ˉ \bar{y} yˉ is the mean of values in the vector y y y, and ∥ ⋅ ∥ ∞ \|\cdot\|_{\infty} is the infinity norm (or supremum norm), which is the maximum over the absolute values of the components of a vector. Thus we need to search for an optimal λ \lambda λ in [ 0 , λ max ] \left[0,\lambda_{\text{max}}\right] [0,λmax], where λ max = 2 ∥ X T ( y − y ˉ ) ∥ ∞ \lambda_{\text{max}}=2\|X^{T}(y-\bar{y})\|_{\infty} λmax=2XT(yyˉ). (Note: This expression for λ max \lambda_{\text{max}} λmax assumes we have an unregularized bias term in our model. That is, our decision functions are of the form h w , b ( x ) = w T x + b h_{w,b}(x)=w^{T}x+b hw,b(x)=wTx+b. In our the experiments, we do not have an unregularized bias term, so we should use λ max = 2 ∥ X T y ∥ ∞ \lambda_{\text{max}}=2\|X^{T}y\|_{\infty} λmax=2XTy.)

The second trick is to use the fact that when λ \lambda λ and λ ′ \lambda' λ are close, the corresponding solutions w ^ ( λ ) \hat{w}(\lambda) w^(λ) and w ^ ( λ ′ ) \hat{w}(\lambda') w^(λ) are also close. Start with λ = λ max \lambda=\lambda_{\text{max}} λ=λmax, for which
we know w ^ ( λ max ) = 0 \hat{w}(\lambda_{\text{max}})=0 w^(λmax)=0. You can run the optimization anyway, and initialize the optimization at w = 0 w=0 w=0. Next, λ \lambda λ is reduced (e.g. by a constant factor close to 1 1 1), and the optimization problem is solved using the previous optimal point as the starting point. This is called warm starting the optimization. The
technique of computing a set of solutions for a chain of nearby λ \lambda λ's is called a continuation or homotopy method. The resulting set of parameter values w ^ ( λ ) \hat{w}(\lambda) w^(λ) as λ \lambda λ ranges over [ 0 , λ max  ] \left[0,\lambda_{\text{max }}\right] [0,λmax ] is known as a regularization path.

If we do not regularize, the loss function should be :
L ( w ) = ( Y − X w ) T ( Y − X w ) ∂ L ( w ) ∂ W j = − 2 ∑ i = 1 N X i j ( y i − w T X i ) = − 2 ∑ i = 1 N X i j ( y i − w j X i j − ( w T X i − w j X i j ) ) = w j 2 ∑ i = 1 N X i j 2 − 2 ∑ i = 1 N X i j ( y i − w T X i + w j X i j ) L(w) = (Y-Xw)^T (Y-Xw) \\ \frac{\partial L(w)}{\partial W_j} = -2\sum_{i=1}^N X_{ij}(y_i - w^TX_i) \\ = -2\sum_{i=1}^N X_{ij}(y_i - w_j X_{ij} - (w^TX_{i} - w_j X_{ij})) \\ = w_j 2\sum_{i=1}^N X_{ij}^{2} - 2\sum_{i=1}^N X_{ij}(y_i - w^TX_i + w_jX_{ij}) L(w)=(YXw)T(YXw)WjL(w)=2i=1NXij(yiwTXi)=2i=1NXij(yiwjXij(wTXiwjXij))=wj2i=1NXij22i=1NXij(yiwTXi+wjXij)

Let $a_j = 2\sum_{i=1}^N X_{ij}^{2}, c_j = 2\sum_{i=1}^N X_{ij}(y_i - w^TX_i + w_jX_{ij}) $ we can get :
∂ L ( w ) ∂ W j = a j w j − c j \frac{\partial L(w)}{\partial W_j} = a_{j}w_j - c_j WjL(w)=ajwjcj

Now, we add the regularization term :
L ( w , λ ) = L ( w ) + λ ∥ w ∥ 1 L(w, \lambda) = L(w) + \lambda \|w\|_{1} L(w,λ)=L(w)+λw1

So now we get :
KaTeX parse error: Expected & or \\ or \cr or \end at position 204: … \ & w_j > 0 \ \̲ ̲\end{cases}

w j = { ( c j + λ ) / a j ,    c j &lt; − λ , 0 ,    c j ∈ [ − λ , λ ] ( c j − λ ) / a j ,    c j &gt; − λ w_j = \begin{cases}(c_j + \lambda)/a_j, \quad \ \ &amp; c_j&lt;-\lambda, \\ 0, \quad \ \ &amp; c_j\in [-\lambda, \lambda] \\ (c_j - \lambda)/a_j , \quad \ \ &amp; c_j &gt; -\lambda \\ \end{cases} wj=(cj+λ)/aj,  0,  (cjλ)/aj,  cj<λ,cj[λ,λ]cj>λ

We write the expression of $a_j , c_j $ in matrix form :
a j = 2 X . j T X . j c j = 2 X . j T y − 2 X . j T X w + 2 w j X . j T X . j a_j = 2X_{.j}^TX_{.j} \\ c_j = 2X_{.j}^Ty - 2X_{.j}^TXw + 2w_j X_{.j}^TX_{.j} aj=2X.jTX.jcj=2X.jTy2X.jTXw+2wjX.jTX.j

The let’s write a function that computes the Lasso solution for a given λ \lambda λ using the shooting algorithm. For convergence criteria, continue coordinate descent until a pass through the coordinates reduces the objective function by less than 1 0 − 8 10^{-8} 108, or have taken 1000 passes through the coordinates.

Import Modules

import numpy as np
import pandas as pd
from random import shuffle

Cyclic coordinate Descent for Lasso

def soft_f(a, delta) :
    if a >0 :
        result = max(abs(a)-delta, 0)
    elif a == 0 :
        result = 0
    else :
        result = -max(abs(a)-delta, 0)
    
    return result
def Lasso_Loss_fun(X, Y, w, lambda_reg) :
    temp = Y - np.dot(X, w)
    return np.dot(temp.T, temp) + lambda_reg*np.sum(np.absolute(w))
def Lasso_Co_Descent(X, Y, lambda_reg, init) :
    num_Co = X.shape[1]
    if init == 1 :
        w = np.dot(np.dot(np.linalg.inv(np.dot(X.T, X) +  lambda_reg*np.identity(num_Co)), X.T), Y)
    else :
        w = np.ones(num_Co)
    
    count = 0
    obj_fun_result = []
    obj_fun_result.append(Lasso_Loss_fun(X,Y,w,lambda_reg))
    
    while count <1000 :
        for i in range(num_Co) :
            if w[i] != 0 :
                a = 2*np.dot(X.T[i], X.T[i])
                c = 2*np.dot(X.T[i], Y) - 2*np.dot(np.dot(X.T[i], X), w) + 2*w[i]*np.dot(X.T[i], X.T[i])
                if(a == 0 or c==0) :
                    w[i] = 0
                else :
                    w[i] = soft_f(c/a, lambda_reg/a)
            else :
                w[i] = 0
                 
        count = count + 1
        obj_fun_result.append(Lasso_Loss_fun(X, Y, w, lambda_reg))
        if abs(obj_fun_result[count]-obj_fun_result[count-1]) < 1e-8  :
            break
            
    
    return w, np.array(obj_fun_result)

Randomized Coordinate Descent for Lasso

def Lasso_Co_Randomized_Descent(X, Y, lambda_reg, init) :
    num_Co = X.shape[1]
    if init == 1 :
        w = np.dot(np.dot(np.linalg.inv(np.dot(X.T, X) +  lambda_reg*np.identity(num_Co)), X.T), Y)
    else :
        w = np.ones(num_Co)
    
    count = 0
    obj_fun_result = []
    obj_fun_result.append(Lasso_Loss_fun(X,Y,w,lambda_reg))
    sequence = list(range(0, num_Co))
    
    while count<1000 :
        shuffle(sequence)
        for i in sequence :
            if w[i] != 0 :
                a = 2*np.dot(X.T[i], X.T[i])
                c = 2*np.dot(X.T[i], Y) - 2*np.dot(np.dot(X.T[i], X), w) + 2*w[i]*np.dot(X.T[i], X.T[i])
                if(a == 0 or c == 0) :
                    w[i] = 0
                else :
                    w[i] = soft_f(c/a, lambda_reg/a)
                    
            else :
                w[i] = 0
                    
        count = count + 1
        obj_fun_result.append(Lasso_Loss_fun(X, Y, w, lambda_reg))
        if abs(obj_fun_result[count]-obj_fun_result[count-1]) < 1e-8 :
            break
            
    
    return w, np.array(obj_fun_result)

Compare these two method :

from setup_problem import load_problem
from ridge_regression import RidgeRegression,plot_prediction_functions
#Load the training and validation data
lasso_data_fname = "lasso_data.pickle"
x_train, y_train, x_val, y_val, target_fn, coefs_true, featurize = load_problem(lasso_data_fname)

# Generate features
X_train = featurize(x_train)
X_val = featurize(x_val)

If we use Murphy Initial

w1, Or_Loss = Lasso_Co_Descent(X_train, y_train, 0.01, 1)
w2, Ra_Loss = Lasso_Co_Randomized_Descent(X_train, y_train, 0.01, 1)
w3, Or_Loss_new = Lasso_Co_Descent(X_train, y_train, 0.1, 1)
w4, Ra_Loss_new = Lasso_Co_Randomized_Descent(X_train, y_train, 0.1, 1)
import matplotlib.pyplot as plt
fig=plt.figure()
ax=fig.add_subplot(111)
ax.plot(Or_Loss, label = 'Cyclic $\lambda = 0.01$')
ax.plot(Ra_Loss, label = 'Random $\lambda = 0.01$')
plt.grid()
plt.xlabel('Number of Steps')
plt.ylabel('Training Lasso Loss Value')
plt.title('Training Lasso Loss: Cyclic Descsent and Murphy Initial')
plt.legend()
<matplotlib.legend.Legend at 0x1a1b408710>

在这里插入图片描述

fig=plt.figure()
ax=fig.add_subplot(111)
ax.plot(Or_Loss_new, label = 'Cyclic $\lambda = 0.1$')
ax.plot(Ra_Loss_new, label = 'Random $\lambda = 0.1$')
plt.grid()
plt.xlabel('Number of Steps')
plt.ylabel('Training Lasso Loss Value')
plt.title('Training Lasso Loss: Cyclic Descsent and Murphy Initial')
plt.legend()
<matplotlib.legend.Legend at 0x1a219a7f98>

在这里插入图片描述

If we do not use Murphy Initial

w5, Or_Loss_non = Lasso_Co_Descent(X_train, y_train, 0.01, 0)
w6, Ra_Loss_non = Lasso_Co_Randomized_Descent(X_train, y_train, 0.01, 0)
w7, Or_Loss_new_non = Lasso_Co_Descent(X_train, y_train, 0.1, 0)
w8, Ra_Loss_new_non = Lasso_Co_Randomized_Descent(X_train, y_train, 0.1, 0)
fig=plt.figure()
ax=fig.add_subplot(111)
ax.plot(Or_Loss_non[50:], label = 'Cyclic $\lambda = 0.01$')
ax.plot(Ra_Loss_non[50:], label = 'Random $\lambda = 0.01$')
plt.grid()
plt.xlabel('Number of Steps')
plt.ylabel('Training Lasso Loss Value')
plt.title('Training Lasso Loss: Cyclic Descsent and Non Initial')
plt.legend()
<matplotlib.legend.Legend at 0x1a22682ba8>

在这里插入图片描述

fig=plt.figure()
ax=fig.add_subplot(111)
ax.plot(Or_Loss_new_non[50:], label = 'Cyclic $\lambda = 0.1$')
ax.plot(Ra_Loss_new_non[50:], label = 'Random $\lambda = 0.1$')
plt.grid()
plt.xlabel('Number of Steps')
plt.ylabel('Training Lasso Loss Value')
plt.title('Training Lasso Loss: Cyclic Descsent and non Initial')
plt.legend()
<matplotlib.legend.Legend at 0x1a22965c50>

在这里插入图片描述

Grid Search for the best parameter

def compute_square_loss(X_train, Y_train, x_val, y_val, reg) :
    w, loss_list = Lasso_Co_Descent(X_train, y_train, reg, 1)
    residual = np.dot(x_val, w) - y_val
    square_loss = np.dot(residual.T, residual)
    return square_loss
square_loss_list = []
para_array = np.arange(0.1, 3, 0.05)
for i in range(len(para_array)) :
    square_loss_list.append(compute_square_loss(X_train, y_train, X_val, y_val, para_array[i]))
square_loss_array = np.array(square_loss_list)
square_loss_df = pd.DataFrame({'square loss' : square_loss_array}, index = para_array)
square_loss_df.plot()
<matplotlib.axes._subplots.AxesSubplot at 0x1a22cc7240>

在这里插入图片描述

Plot the Best Lasso Model together with Ridge and Target Function

w, loss_list = Lasso_Co_Descent(X_train, y_train, 1, 1)
from sklearn.linear_model import Ridge
plt.clf()
fig, ax = plt.subplots(figsize = (10,6))
plt.scatter(x_train, y_train, s=3, color='k', label='Training data')

x = np.arange(0,1,.001)
ax.plot(x, target_fn(x), 'r', label='Target function (i.e. Bayes prediction function)')

Ridge_estimator = Ridge(alpha = 2.35)
Ridge_estimator.fit(X_train, y_train)
x = np.sort(np.concatenate([np.arange(0,1,.001), x_train]))
X = featurize(x)
ax.plot(x,  Ridge_estimator.predict(X))
ax.plot(x,  np.dot(X, w))

plt.legend(['Target Function', 'Prediction with Ridge $\lambda$ = 2.35', 'Prediction with Lasso $\lambda = 1$', 'Training Data'], loc =1)
plt.title('Prediction Functions')
plt.xlabel('')
plt.show()
<Figure size 432x288 with 0 Axes>

在这里插入图片描述

Part Two : Homotopy Method

def avg_square_loss(X, Y, w) :
    residual = np.dot(X, w) - Y
    return np.dot(residual.T, residual)/X.shape[0] 
def Lasso_Co_Descent_Homotopy(X, Y, lambda_reg, W) :

    count = 0
    w = W
    obj_fun_result = []
    obj_fun_result.append(Lasso_Loss_fun(X,Y,w,lambda_reg))
    
    while count <1000 :
        for i in range(num_Co) :
            if w[i] != 0 :
                a = 2*np.dot(X.T[i], X.T[i])
                c = 2*np.dot(X.T[i], Y) - 2*np.dot(np.dot(X.T[i], X), w) + 2*w[i]*np.dot(X.T[i], X.T[i])
                if(a == 0 or c==0) :
                    w[i] = 0
                else :
                    w[i] = soft_f(c/a, lambda_reg/a)
            else :
                w[i] = 0
                 
        count = count + 1
        obj_fun_result.append(Lasso_Loss_fun(X, Y, w, lambda_reg))
        if abs(obj_fun_result[count]-obj_fun_result[count-1]) < 1e-8  :
            break
            
    
    return w
def homotopy_method(X_train, Y_train, x_val, y_val, lambda_max) :
    pre_w = np.ones(X_train.shape[1])
    w_list = []
    lambda_list = []
    avg_sqr_loss = []
    
    for i in range(30) :
        lambda_reg = lambda_max*((0.8)**(i))
        lambda_list.append(lambda_reg)
        curr_w = Lasso_Co_Descent_Homotopy(X_train, Y_train, lambda_reg, pre_w)
        w_list.append(curr_w)
        loss = avg_square_loss(x_val, y_val, curr_w)
        avg_sqr_loss.append(loss)
        pre_w = curr_w
        
    return lambda_list, avg_sqr_loss
lambda_list , avg_sqr_loss= homotopy_method(X_train, y_train, X_val, y_val, 2)
square_loss_array_H = np.array(avg_sqr_loss)
square_loss_H_df = pd.DataFrame({'avg square loss' : square_loss_array_H}, index = np.array(lambda_list))
square_loss_H_df.plot()
<matplotlib.axes._subplots.AxesSubplot at 0x1a23556b70>

在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值