logistic regression 在octave上的小測試程序

參考了文章:
http://www.holehouse.org/mlclass/06_Logistic_Regression.html
http://blog.csdn.net/abcjennifer/article/details/7716281

binary logistic regression在minimize cost function時的計算過程與linear regression的形式上是一樣的,都是:
這裏寫圖片描述

區別就是裏面的h函數不一樣。
由於其形式的一樣,所以使用gradient descent 的時侯和linear regression的也是一樣的。我直接使用了exercise 2的代碼來做驗證。

假設一個函數 x2=3+1.5x1,用來產生數據,這條線上面或下面。上面用1表示,下面用0表示,得到數據樣本:
x數據,有兩維:x1,x2

1   4
1   4.4
1   4.6
1   5
2   5.5
2   5.8
2   6.2
2   6.3
3   7.3
3   7.7
4   8.7
4   9.3

y數據:

0
0
1
1
0
0
1
1
0
1
0
1

代碼:

% line function is : x2=3+1.5*x1

clear all; close all; clc

function z=sigmoid(v)
  z= 1 ./ (1 + e.^-v);
endfunction 

x = load('x.dat');
y = load('y.dat');
m = length(y); % number of training examples

x = [ones(m, 1) x]; % Add a column of ones to x
theta = zeros(size(x(1,:)))'; % initialize fitting parameters
MAX_ITR = 1500;
alpha = 0.06;

x
y

theta

for num_iterations = 1:MAX_ITR
    % This is a vectorized version of the 
    % gradient descent update formula
    % It's also fine to use the summation formula from the videos

    % Here is the gradient
    grad = (1/m).* x' * (sigmoid(x * theta) - y);

    % Here is the actual update
    theta = theta - alpha .* grad;

    % Sequential update: The wrong way to do gradient descent
    % grad1 = (1/m).* x(:,1)' * ((x * theta) - y);
    % theta(1) = theta(1) + alpha*grad1;
    % grad2 = (1/m).* x(:,2)' * ((x * theta) - y);
    % theta(2) = theta(2) + alpha*grad2;
end

theta


predict1 = [1, 1,3.5] *theta
predict2 = [1, 1,4.7] *theta
predict3 = [1, 2,6.1] *theta

可以看到,我只是在exercise2的代碼的基礎上,在循環的地方,用sigmoid包住了x與theta的計算結果。

輸出

theta =

  -2.6180
  -1.7516
   1.0481

predict1 = -0.70114
predict2 =  0.55663
predict3 =  0.27238

如果將迭代次數增加,會更加可信:
增加到15000的輸出:

theta =

  -16.1457
   -8.3833
    5.5103

predict1 = -5.2431
predict2 =  1.3692
predict3 =  0.70026
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章