【问题标题】:Machine learning Logistic Regression L2 regularization机器学习 Logistic 回归 L2 正则化
【发布时间】:2021-12-24 07:14:27
【问题描述】:

我正在尝试对我的数据实施 L2 正则化 我的函数是这样写的

 def logicalregP3(xtr,ytr,learning_rate,iteration,lamda):
   
    m=xtrain.T.shape[1]
    n=xtrain.T.shape[0]
   
    W= np.zeros((n,1))
  
    B = 0
    cost_list = []
    for i in range (iteration):
        z= np.array(np.dot(W.T, xtr.T),dtype=np.float32)+B
     
        a= 1/(1 + np.exp(-z))

    
        cost=-(1/m)*np.sum(ytr.T*np.log(a)+(1-ytr.T)*np.log(1-a))+(lamda*np.sum(W))
        # Gradient Descent
        
        regular=(lamda/(2*m))*W
        dW=(1/m)*np.dot(a-ytr.T,xtr)+regular
        dB=(1/m)*np.sum(a-ytr.T)      
        W=W-learning_rate*dW.T
        B=B-learning_rate*dB
        print("cost ", i ," ", cost)
   
        cost_list.append(cost)
       
            
    return W,B,cost_list

然后我用这些值调用函数

iterations=2000
learning_rate=0.0015
lamda=0.00001
Wp3,Bp3,cost_listp3=logicalregP3(xtrain,ytrain,learning_rate, iterations,lamda)

我的代码输出:

cost  0   0.6931471824645996
cost  1   2.6271848720002735
cost  2   2.5287339955351484
cost  3   2.461344902235327
cost  4   2.4144645825946607
cost  5   2.3812474056254485
cost  6   2.357244340813794
cost  7   2.339536539714837
cost  8   2.3261846933514745
cost  9   2.3158827015378978
cost  10   2.307739196600699
cost  11   2.3011379381265
cost  12   2.2956485144978704
cost  13   2.290966932838124
cost  14   2.28687647957537

当我绘制图表时:这是成本的输出:

我的代码输出正常还是梯度下降有问题?

【问题讨论】:

  • 我认为这是因为您将 weights 初始化为零(考虑过但今天也在练习),尝试类似 np.random.randn(n, 1) * 0.01
  • 我认为这不是这里最大的问题,但更好的初始化可以帮助收敛是的
  • @ValentinGoldité 我虽然他说的只是第一个“碰撞”。

标签: python machine-learning logistic-regression


【解决方案1】:

其实L2正则化不是lambda * np.sum(W)而是lambda * np.linalg.norm(W, ord=2)。在您的情况下,我假设梯度下降效果很好,但您无法检查它,因为您的成本不代表此处最小化的数量。

【讨论】: