机器学习深入篇(三)——逻辑回归

机器学习深入篇(三)——逻辑回归

代码实现

1、sigmod函数

function g = sigmoid(z)
g = 1./(1+exp(1).^(-z));
end

2、代价函数

function [J, grad] = costFunctionReg(theta, X, y, lambda)
m = length(y); % number of training examples
n = length(theta);
h = sigmoid(X * theta);
J = 1/m * (-y' * log(h) - (1-y)' * log(1 - h)) + lambda/(2*m) * sum(theta(2:n).^2);
grad = (1/m * (h - y)' * X)' + [0; lambda/m * theta(2:n)];
end

3、决策边界

function plotDecisionBoundary(theta, X, y)
plotData(X(:,2:3), y);
hold on

if size(X, 2) <= 3
    % Only need 2 points to define a line, so choose two endpoints
    plot_x = [min(X(:,2))-2,  max(X(:,2))+2];

    % Calculate the decision boundary line
    plot_y = (-1./theta(3)).*(theta(2).*plot_x + theta(1));

    % Plot, and adjust axes for better viewing
    plot(plot_x, plot_y)
    
    % Legend, specific for the exercise
    legend('Admitted', 'Not admitted', 'Decision Boundary')
    axis([30, 100, 30, 100])
else
    % Here is the grid range
    u = linspace(-1, 1.5, 50);
    v = linspace(-1, 1.5, 50);

    z = zeros(length(u), length(v));
    % Evaluate z = theta*x over the grid
    for i = 1:length(u)
        for j = 1:length(v)
            z(i,j) = mapFeature(u(i), v(j))*theta;
        end
    end
    z = z'; % important to transpose z before calling contour

    % Plot z = 0
    % Notice you need to specify the range [0, 0]
    contour(u, v, z, [0, 0], 'LineWidth', 2)
end
hold off
end

4、数据绘制

function plotData(X, y)
pos=find(y==1);
neg=find(y==0);

% Plot Examples
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

5、特征绘制

function out = mapFeature(X1, X2)
degree = 6;
out = ones(size(X1(:,1)));
for i = 1:degree
    for j = 0:i
        out(:, end+1) = (X1.^(i-j)).*(X2.^j);
    end
end
end

6、预测(分类)

function p = predict(theta, X)
m = size(X, 1); % Number of training examples

% You need to return the following variables correctly
p = zeros(m, 1);
h = sigmoid(X * theta);

pos = h>=0.5;
neg = h<0.5;

p(pos) = 1;
p(neg) = 0;
end

告一段落

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

柚子味的羊

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值