2012-02-20 69 views
4

Matlab已經使用mnrfit建立邏輯迴歸,但是我需要實現具有L2正則化的邏輯迴歸。我對如何繼續完全不知所措。我發現了一些很好的論文和網站參考文獻,但是不知道如何實現優化所需的梯度下降算法。在Matlab中使用L2正則化實現邏輯迴歸

在Matlab中是否有一個容易獲得的示例代碼。我找到了一些庫和包,但它們都是大包的一部分,並且調用了許多令人費解的函數,可能只是通過跟蹤而丟失。

+0

你可能最好使用一些預製的優化器比實現你自己的。 LBFGS和共軛梯度是精確優化LR模型而不是香草梯度下降的最廣泛使用的算法。見例如[這個工具箱](http://www.di.ens.fr/~mschmidt/Software/minFunc.html)。 – 2012-02-20 22:43:38

+0

如果您正確地標記您的問題(即使用matlab標籤),您可以使其他人更容易找到此問題並提高您獲得答案的機會。 – tr9sh 2012-02-21 16:30:30

+0

這個問題實際上可能會在統計堆棧交換中得到更好的答案。 – 2012-02-21 16:57:15

回答

2

這是一個註釋的一段代碼,用於Logistic迴歸的普通梯度下降。要引入正則化,您需要更新成本和梯度方程。在這段代碼中,THETA是參數,X是類預測,y是類標籤和alpha爲學習率

我希望這有助於:)

function [theta,J_store] = logistic_gradientDescent(theta, X, y,alpha,numIterations) 

% Initialize some useful values 
m = length(y); % number of training examples 
n = size(X,2); %number of features 

J_store = 0; 
%J_store = zeros(numIterations,1); 


for iter=1:numIterations 

    %predicts the class labels using the current weights (theta) 
    Z = X*theta; 
    h = sigmoid(Z); 

    %This is the normal cost function equation 
    J = (1/m).*sum(-y.*log(h) - (1-y).*log(1-h)); 


    %J_store(iter) = J; 



    %This is the equation to obtain the given the current weights, without regularisation 
    grad = [(1/m) .* sum(repmat((h - y),1,n).*X)]'; 


    theta = theta - alpha.*grad; 


end 

end