利用機器學習進行分類(梯度演算法)

來源:互聯網
上載者:User

到這裡,公式就推導完畢了。

看個例子明白點:

希望可以將帶星號和帶加號區分開來


下面是主要代碼:

function [th,ll] = plotdots(x,y,z)% rows of X are training samples% rows of Y are corresponding 0/1 valueshold on;%% 畫原始點的圖for i = 1:size(x,1)  if(z(i)==0)     plot(x(i),y(i),'*');  elseif (z(i)==1)     plot(x(i),y(i),'+');  endendxy = [x,y];[th,ll] = logistic_grad_ascent(xy,z);t = x;X = [ones(size(xy,1),1), x];thx = th(1:2);thy = -th(3);y1 = X*thx./thy;plot(t,y1,'r-');end


logistic_grad_ascent函數:

這個函數的for迴圈就是上面推導公式的應用,也就是演算法的核心:

(1)hx的得到sigmoid的值,就是公式(1),

(2)theta是不斷迭代siyata(不想貼圖片了,囧),就是公式(8)

(3)ll(k)就是公式(5)

function [theta, ll] = logistic_grad_ascent(X,y)% rows of X are training samples% rows of Y are corresponding 0/1 values% output ll: vector of log-likelihood values at each iteration% ouptut theta: parametersalpha = 0.01;  %步長[m,n] = size(X);max_iters = 50000;   %迭代次數X = [ones(size(X,1),1), X]; % append col of ones for intercept termtheta = zeros(n+1, 1);  % initialize thetafor k = 1:max_iters  hx = sigmoid(X*theta);  theta = theta + alpha * X' * (y-hx);   ll(k) = sum( y .* log(hx) + (1 - y) .* log(1 - hx) );end


最後得到的結果.

可以拓展成三維四維的情況,不過四維以後就不是那麼好直觀看了。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.