簡體   English   中英

在Matlab中使用L2正則化實現邏輯回歸

[英]Implementing logistic regression with L2 regularization in Matlab

Matlab使用mnrfit內置了邏輯回歸,但是我需要使用L2正則化實現邏輯回歸。 我對如何進行完全不知所措。 我已經找到了一些帶有大量方程式的好的論文和網站參考,但是不確定如何實現優化所需的梯度下降算法。

在Matlab中是否有容易獲得的示例代碼。 我已經找到了一些庫和軟件包,但是它們都是較大的軟件包的一部分,並且調用了許多復雜的函數,僅通過跟蹤就可能迷失方向。

這是帶注釋的一段代碼,用於進行邏輯回歸的純梯度下降。 要引入正則化,您將需要更新成本和梯度方程。 在此代碼中,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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM