%% Load Data
data = load('ex2data1.txt');
X = data(:, [1, 2]); y = data(:, 3);
%%Plotting
plotData(X, y);
function plotData(X, y)
figure;hold on;
pos=find(y==1);neg=find(y==0);
plot(X(pos,1),X(pos,2),'k+','LineWidth',2,...
'MarkerSize',7);
plot(X(neg,1),X(neg,2),'ko','MarkerFaceColor','y',...
'MarkerSize',7);
hold off;
end
hold on;xlabel('Exam 1 score')
ylabel('Exam 2 score')
legend('Admitted', 'Not admitted')
hold off;
%%Compute Cost and Gradient
[m, n] = size(X);
X = [ones(m, 1) X];
initial_theta = zeros(n + 1, 1);
[cost, grad] = costFunction(initial_theta, X, y);
function [J, grad] = costFunction(theta, X, y)
m = length(y);
J = 0;
grad = zeros(size(theta));
sig=sigmoid(X * theta);
J=-(1/m)*sum(y' * log(sig)+ (1-y') * log(1- sig));
grad=(1/m )* (X'* (sig-y));
end
fprintf('Cost at initial theta (zeros): %f\n', cost);fprintf('Gradient at initial theta (zeros): \n');
fprintf(' %f \n', grad);
%%Optimizing using fminunc
options = optimset('GradObj', 'on', 'MaxIter', 400);
[theta, cost] = ...
fminunc(@(t)(costFunction(t, X, y)), initial_theta, options);
fprintf('Cost at theta found by fminunc: %f\n', cost);
fprintf('theta: \n');
fprintf(' %f \n', theta);
plotDecisionBoundary(theta, X, y);
function plotDecisionBoundary(theta, X, y)
plotData(X(:,2:3), y);
hold on
if size(X, 2) <= 3
plot_x = [min(X(:,2))-2, max(X(:,2))+2];
plot_y = (-1./theta(3)).*(theta(2).*plot_x + theta(1));
plot(plot_x, plot_y)
legend('Admitted', 'Not admitted', 'Decision Boundary')
axis([30, 100, 30, 100])
else
u = linspace(-1, 1.5, 50);
v = linspace(-1, 1.5, 50);
z = zeros(length(u), length(v));
for i = 1:length(u)
for j = 1:length(v)
z(i,j) = mapFeature(u(i), v(j))*theta;
end
end
z = z';
contour(u, v, z, [0, 0], 'LineWidth', 2)
end
hold off
end
hold on;
xlabel('Exam 1 score')
ylabel('Exam 2 score')
legend('Admitted', 'Not admitted')
hold off;
%%Predict and Accuracies
prob = sigmoid([1 45 85] * theta);
function g = sigmoid(z)
g = zeros(size(z));
g=1./(1+exp(-z));
end
fprintf(['For a student with scores 45 and 85, we predict an admission ' ...
'probability of %f\n\n'], prob);
p = predict(theta, X);
function p = predict(theta, X)
m = size(X, 1);
p = zeros(m, 1);
sig=sigmoid(X * theta);
for iter=1:m
if sig(iter)>=0.5
p(iter)=1;
else
p(iter)=0;
end;
end;
end
fprintf('Train Accuracy: %f\n', mean(double(p == y)) * 100);fprintf('\nProgram paused. Press enter to continue.\n');
pause;