machine-learning-ex2_1

%% 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;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值