-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlrFastDescent.m
91 lines (76 loc) · 2.13 KB
/
lrFastDescent.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
function [theta cost] = lrFastDescent(x, y, option)
% Logistic Regression Solver: Fast Descent
% http://en.wikipedia.org/wiki/Steepest_descent
% http://cs229.stanford.edu/section/matlab/logistic_grad_ascent.m
% x -- input data, size = [m, n], m:samples number, n:feature dimension;
% y -- labels data, size = [m, 1], values=[-1 1], m:samples number;
% theta -- parameters, size = [n+1, 1], n:elements nubmer;
% cost -- cost
% option -- option struct
% max_itr: max iterators
% min_eps: min eps
% C: penalty factor
% debug: show debug message
% author -- amadeuzou AT gmail
% date -- 11/19/2013, Beijing, China
if nargin == 2
option.C = 1;
option.max_itr = 100;
option.min_eps = 1e-3;
option.debug = 1;
end
if ~isfield(option, 'C')
option.C = 1;
end
if ~isfield(option, 'max_itr')
option.max_itr = 100;
end
if ~isfield(option, 'min_eps')
option.min_eps = 1e-3;
end
if ~isfield(option, 'debug')
option.debug = 1;
end
[m, n] = size(x);
x = [ones(m, 1), x];
theta = zeros(n+1, 1);
J = [];
lambda0 = 0;
step0 = 0.1;
itr = 0;
err = 0;
while(1)
% gradient
%g = (1/m).*x' * (y-h);
[cost g] = lrCostFunc(x, y, theta, option.C);
% descent direction
d = -g;
% linear search
param.x = x;
param.y = y;
param.theta = theta;
param.d = d;
param.C = option.C;
lamb = lrLinearSearch(@lrCostFuncLambda, param, lambda0, step0);
theta = theta + lamb.*d;
% cost record
J = [J; cost];
itr = itr + 1;
err = norm(lamb*d);
if(option.debug)
disp(['itr = ', num2str(itr), ', cost = ', num2str(cost), ', err = ', num2str(err)]);
end
if itr >= option.max_itr || err <= option.min_eps || norm(g)<=option.min_eps
break;
end
end
% draw cost cure
if(option.debug)
figure(1024)
plot(1:length(J), J, 'b-');
xlabel('iterators');
ylabel('cost');
end
function cost = lrCostFuncLambda(param, lambda)
theta = param.theta + lambda.*param.d;
cost = lrCostFunc(param.x, param.y, theta, param.C);