机器学习2 逻辑回归Logistic Regression

机器学习2 逻辑回归Logistic Regression

原文地址:http://blog.csdn.net/hjimce/article/details/45418933
作者:hjimce

逻辑回归

逻辑回归于线性回归的区别:
(1)线性回归的函数拟合,用于数值预测,逻辑回归是二分类算法,用于分类

(2)线性回归模型:enter image description here

逻辑回归模型:enter image description here

也就是说逻辑回归其实是在线性回归的基础上,加了一个激励函数映射。因为逻辑回归是二分类算法,因此对于训练数据,其只有两种取值1、0,代表两个分类,用于预测分类的时候,输入值大于0.5的,则把它归为1类,否者归为0类。因此对于训练数据需要满足一下概率公式:
enter image description here

我们的训练过程,就是要训练参数θ,使得以上的两个概率尽量为1

(3)线性回归常用代价函数定义为:
enter image description here

逻辑回归代价函数为:
enter image description here

其实上式可以分开来写,对于类1,总代价函数为:
enter image description here

对于类0,总代价函数为:
enter image description here

因此:
enter image description here

我们的目的便是要使得代价函数J(θ)的数值最小,使之尽量的趋近于0。

(4)梯度下降法求解。

代价函数简化:
enter image description here

接着就要对其求偏导数:
enter image description here

接着就是直接使用梯度下降法的公式:
enter image description here

close all;  
clear;  
clc;  
%生成测试数据  
mu = [2 3];%测试数据1  
SIGMA = [1 0; 0 2];  
r1 = mvnrnd(mu,SIGMA,100);  
plot(r1(:,1),r1(:,2),'.');  
hold on;  
mu = [10 10];%测试数据2  
SIGMA = [ 1 0; 0 2];  
r2 = mvnrnd(mu,SIGMA,100);  
plot(r2(:,1),r2(:,2),'.');  
data(:,2:3)=[r1;r2];  
data(:,1)=1;  

%训练数据标号  
flag=[ones(100,1);zeros(100,1)];  
[m,n]=size(data);  
w=zeros(n,1);  
%梯度下降法  
sigma=0.05;  
i=1;  
while i<10000  
   for j=1:n  
    %先计算激励函数值  
    pp=data*w;  
    pp=exp(-data*w);  
    gx=1./(1+exp(-data*w));  
    %计算偏导数值  
     r=-1/m*sum((flag-gx).*data(:,j));  
     w(j)=w(j)-sigma*r;  
   end  
   i=i+1;  
end  
%绘制分类结果  
figure(2);  
hold on;  
for i=1:m  
    if gx(i)>0.5  
        plot(data(i,2),data(i,3),'.b');  
    else   
        plot(data(i,2),data(i,3),'.y');  
    end  
end  
%绘制决策边界直线  
w(2)=w(2)/sqrt(w(2)*w(2)+w(3)*w(3));  
w(3)=w(3)/sqrt(w(2)*w(2)+w(3)*w(3));  
line([4,9],[(4*w(2)+w(1))/(-w(3)),(9*w(2)+w(1))/(-w(3))]);  

原图
enter image description here

分类结果
enter image description here

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值