Skip to content

Commit 00ead02

Browse files
Exercise3 - Week4 Finished
1 parent 218ac82 commit 00ead02

File tree

4 files changed

+27
-5
lines changed

4 files changed

+27
-5
lines changed

machine-learning-ex3/ex3/lrCostFunction.m

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,14 @@
3535
% temp(1) = 0; % because we don't add anything for j = 0
3636
% grad = grad + YOUR_CODE_HERE (using the temp variable)
3737
%
38-
38+
h = sigmoid(X * theta);
39+
temp = theta;
40+
temp(1) = 0;
41+
positive_J = -y .* log(h);
42+
negative_J = (1 - y) .* log(1 - h);
43+
J = sum((positive_J - negative_J) / m) + lambda * sum(temp.^2) / (2 * m);
44+
45+
grad = (X' * (h - y) + lambda * temp) / m;
3946

4047

4148

machine-learning-ex3/ex3/oneVsAll.m

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,14 @@
4848
% fmincg (@(t)(lrCostFunction(t, X, (y == c), lambda)), ...
4949
% initial_theta, options);
5050
%
51+
initial_theta = zeros(n + 1, 1);
5152

53+
for i = 1:num_labels
54+
options = optimset('GradObj', 'on', 'MaxIter', 50);
55+
[theta] = fmincg(@(t)(lrCostFunction(t, X, (y == i), lambda)), ...
56+
initial_theta, options);
57+
all_theta(i, :) = theta';
58+
end
5259

5360

5461

machine-learning-ex3/ex3/predict.m

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -20,9 +20,15 @@
2020
% information see 'help max'. If your examples are in rows, then, you
2121
% can use max(A, [], 2) to obtain the max for each row.
2222
%
23-
24-
25-
23+
X = [ones(m,1), X];
24+
25+
z1 = Theta1 * X';
26+
a2 = sigmoid(z1);
27+
a2 = [ones(1, m);a2];
28+
z2 = Theta2 * a2;
29+
a3 = sigmoid(z2);
30+
[M, I] = max(a3);
31+
p = I';
2632

2733

2834

machine-learning-ex3/ex3/predictOneVsAll.m

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,9 @@
3030
% for each row.
3131
%
3232

33-
33+
result = all_theta * X';
34+
[M, I] = max(result);
35+
p = I';
3436

3537

3638

0 commit comments

Comments
 (0)