到這裡,公式就推導完畢了。
看個例子明白點:
希望可以將帶星號和帶加號區分開來
下面是主要代碼:
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
最後得到的結果.
可以拓展成三維四維的情況,不過四維以後就不是那麼好直觀看了。