logistc regression练习(三)

% Exercise 4 -- Logistic Regression

clear all; close all; clc

x = load(‘E:\workstation\data\ex4x.dat‘);
y = load(‘E:\workstation\data\ex4y.dat‘);

[m, n] = size(x);

% Add intercept term to x
x = [ones(m, 1), x]; 

% Plot the training data
% Use different markers for positives and negatives   分类分别计算每个的具体是允许还是不允许
figure
pos = find(y); neg = find(y == 0);%find是找到的一个向量,其结果是find函数括号值为真时的值的编号
plot(x(pos, 2), x(pos,3), ‘+‘)
hold on
plot(x(neg, 2), x(neg, 3), ‘o‘)
hold on
xlabel(‘Exam 1 score‘)
ylabel(‘Exam 2 score‘)

% Initialize fitting parameters
theta = zeros(n+1, 1);

% Define the sigmoid function
g = inline(‘1.0 ./ (1.0 + exp(-z))‘); 

% Newton‘s method
MAX_ITR = 7;
J = zeros(MAX_ITR, 1);

for i = 1:MAX_ITR
    % Calculate the hypothesis function
    z = x * theta;
    h = g(z);%转换成logistic函数

    % Calculate gradient and hessian.
    % The formulas below are equivalent to the summation formulas
    % given in the lecture videos.
    grad = (1/m).*x‘ * (h-y);%梯度的矢量表示法
    H = (1/m).*x‘ * diag(h) * diag(1-h) * x;%hessian矩阵的矢量表示法

    % Calculate J (for testing convergence)
    J(i) =(1/m)*sum(-y.*log(h) - (1-y).*log(1-h));%损失函数的矢量表示法

    theta = theta - H\grad;%是这样子的吗?
end
% Display theta

% Calculate the probability that a student with
% Score 20 on exam 1 and score 80 on exam 2
% will not be admitted
prob = 1 - g([1, 20, 80]*theta)

%画出分界面
% Plot Newton‘s method result
% 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的计算公式见博客下面的评论。
plot_y = (-1./theta(3)).*(theta(2).*plot_x +theta(1));
plot(plot_x, plot_y)
legend(‘Admitted‘, ‘Not admitted‘, ‘Decision Boundary‘)
hold off

% Plot J
figure
plot(0:MAX_ITR-1, J, ‘o--‘, ‘MarkerFaceColor‘, ‘r‘, ‘MarkerSize‘, 8)
xlabel(‘Iteration‘); ylabel(‘J‘)
% Display J

结果:

logistic regression练习

这里给出的训练样本的特征为80个学生的两门功课的分数,样本值为对应的同学是否允许被上大学,如果是允许的话则用’1’表示,否则不允许就用’0’表示,这是一个典型的二分类问题。在此问题中,给出的80个样本中正负样本各占40个。而这节采用的是logistic regression来求解,该求解后的结果其实是一个概率值,当然通过与0.5比较就可以变成一个二分类问题了。

实验基础:

  在logistic regression问题中,logistic函数表达式如下:

  

  这样做的好处是可以把输出结果压缩到0~1之间。而在logistic回归问题中的损失函数与线性回归中的损失函数不同,这里定义的为:

  

  如果采用牛顿法来求解回归方程中的参数,则参数的迭代公式为:

  

  其中一阶导函数和hessian矩阵表达式如下:

  

  当然了,在编程的时候为了避免使用for循环,而应该直接使用这些公式的矢量表达式(具体的见程序内容)。

  一些matlab函数:

  find:

  是找到的一个向量,其结果是find函数括号值为真时的值的下标编号。

  inline:

  构造一个内嵌的函数,很类似于我们在草稿纸上写的数学推导公式一样。参数一般用单引号弄起来,里面就是函数的表达式,如果有多个参数,则后面用单引号隔开一一说明。比如:g = inline(‘sin(alpha*x)‘,‘x‘,‘alpha‘),则该二元函数是g(x,alpha) = sin(alpha*x)。

Min max 数组中最大最小元素

具体步骤:

1:加载数据和画图:

x = load(‘E:\workstation\data\ex4x.dat‘);

y = load(‘E:\workstation\data\ex4y.dat‘);

[m, n] = size(x);计算数据行列

% Add intercept term to x

x = [ones(m, 1), x];   将第一列数据变为1

% Plot the training data

% Use different markers for positives andfigure

pos = find(y); neg = find(y ==0)%找到对应允许和不允许的分别画标记;

plot(x(pos, 2), x(pos,3), ‘+‘)

hold on

plot(x(neg, 2), x(neg, 3), ‘o‘)

hold on

xlabel(‘Exam 1 score‘)

ylabel(‘Exam 2 score‘)

Newton‘s Method

Recall that in logistic regression, the hypothesis function is

In our example, the hypothesis is interpreted as the probability that a driver will be accident-free, given the values of the features in x.

Matlab/Octave does not have a library function for the sigmoid, so you will have to define it yourself. The easiest way to do this is through an inline expression:

g = inline(‘1.0 ./ (1.0 + exp(-z))‘);

% Usage: To find the value of the sigmoid

% evaluated at 2, call g(2)

The cost function   is defined as

Our goal is to use Newton‘s method to minimize this function. Recall that the update rule for Newton‘s method is

In logistic regression, the gradient and the Hessian are

Note that the formulas presented above are the vectorized versions. Specifically, this means that  , , while   and   are scalars.

Implementation

Now, implement Newton‘s Method in your program, starting with the initial value of  . To determine how many iterations to use, calculate   for each iteration and plot your results as you did in Exercise 2. As mentioned in the lecture videos, Newton‘s method often converges in 5-15 iterations. If you find yourself using far more iterations, you should check for errors in your implementation.

After convergence, use your values of theta to find the decision boundary in the classification problem. The decision boundary is defined as the line where

which corresponds to

% Initialize fitting parameters

theta = zeros(n+1, 1);                  初始化θ值为0。

% Define the sigmoid function

g = inline(‘1.0 ./ (1.0 + exp(-z))‘); 定义归一化函数使g在【0,1】之间inline为内联函数

% Newton‘s method

MAX_ITR = 7;

J = zeros(MAX_ITR, 1);牛顿法具体做法

for i = 1:MAX_ITR

% Calculate the hypothesis function

z = x * theta;     %        有公式定义值    h = g(z);

h = g(z);

grad = (1/m).*x‘ * (h-y);    梯度下降

H = (1/m).*x‘ * diag(h) * diag(1-h) * x;%牛顿环矢量表示

J(i) =(1/m)*sum(-y.*log(h) - (1-y).*log(1-h));随时函数矢量表示

theta = theta - H\grad;                    求出θ这样可以画出直线y=θ0+θ1x曲线从而判断具体可以被允许

end

% Display theta

3:下面找到分界面尽量将一样的放在一方然后之后的可以根据分界面预测是否被允许、

% Calculate the probability that a student with

% Score 20 on exam 1 and score 80 on exam 2

% will not be admitted

prob = 1 - g([1, 20, 80]*theta) %测试一下数据为【1,20,80】这个人

% Plot Newton‘s method result

% Only need 2 points to define a line, so choose two endpoints

plot_x = [min(x(:,2))-2,  max(x(:,2))+2];   第二列即学期最大最小值  +-2是原来的线更加延伸,

直接令logistic回归的值为0.5,则可以得到e的指数为0,即:
theta(1)*1+theta(2)*plot_x+theta(3)*plot_y=0,解出plot_y即可。

plot_y = (-1./theta(3)).*(theta(2).*plot_x +theta(1));

plot(plot_x, plot_y)

legend(‘Admitted‘, ‘Not admitted‘, ‘Decision Boundary‘)

hold off

% Plot J  损失函数值和迭代次数之间的曲线:

figure

plot(0:MAX_ITR-1, J, ‘o--‘, ‘MarkerFaceColor‘, ‘r‘, ‘MarkerSize‘, 8)

xlabel(‘Iteration‘); ylabel(‘J‘)

% Display J

时间: 2024-08-09 15:07:43

logistc regression练习(三)的相关文章

【转】Logistic regression (逻辑回归) 概述

Logistic regression (逻辑回归)是当前业界比较常用的机器学习方法,用于估计某种事物的可能性.比如某用户购买某商品的可能性,某病人患有某种疾病的可能性,以及某广告被用户点击的可能性等.(注意这里是:“可能性”,而非数学上的“概率”,logisitc回归的结果并非数学定义中的概率值,不可以直接当做概率值来用.该结果往往用于和其他特征值加权求和,而非直接相乘) 那么它究竟是什么样的一个东西,又有哪些适用情况和不适用情况呢?   一.官方定义: , Figure 1. The log

【转载】Logistic regression (逻辑回归) 概述

[原创]Logistic regression (逻辑回归) 概述 Logistic regression (逻辑回归)是当前业界比较常用的机器学习方法,用于估计某种事物的可能性.比如某用户购买某商品的可能性,某病人患有某种疾病的可能性,以及某广告被用户点击的可能性等.(注意这里是:“可能性”,而非数学上的“概率”,logisitc回归的结果并非数学定义中的概率值,不可以直接当做概率值来用.该结果往往用于和其他特征值加权求和,而非直接相乘) 那么它究竟是什么样的一个东西,又有哪些适用情况和不适用

ogistic regression (逻辑回归) 概述

:http://hi.baidu.com/hehehehello/blog/item/0b59cd803bf15ece9023d96e.html#send http://en.wikipedia.org/wiki/Logistic_regression Logistic regression (逻辑回归)是当前业界比较常用的机器学习方法,用于估计某种事物的可能性.比如某用户购买某商品的可能性,某病人患有某种疾病的可能性,以及某广告被用户点击的可能性等.(注意这里是:“可能性”,而非数学上的“概率

Neural Networks Learning----- Stanford Machine Learning(by Andrew NG)Course Notes

本栏目内容来自Andrew NG老师的公开课:https://class.coursera.org/ml/class/index 一般而言, 人工神经网络与经典计算方法相比并非优越, 只有当常规方法解决不了或效果不佳时人工神经网络方法才能显示出其优越性.尤其对问题的机理不甚了解或不能用数学模型表示的系统,如故障诊断.特征提取和预测等问题,人工神经网络往往是最有利的工具.另一方面, 人工神经网络对处理大量原始数据而不能用规则或公式描述的问题, 表现出极大的灵活性和自适应性. 神经网络模型解决问题的

初识分类算法(4)-----logistic回归

参考:http://blog.csdn.net/dongtingzhizi/article/details/15962797 1.简述 在线性回归中,h函数的输出值为连续值,当需要进行归类时,输出的应该是离散值,如何将连续值转换成离散值? 如果分类结果只有两个,用1,0表示.我们希望有:函数1/(1+e^(-z)),这样就可以将函数结果限定在0~1之间. Logistic Regression 有三个主要组成部分:回归.线性回归.Logsitic方程. 1)回归其实就是对已知公式的未知参数进行估

机器学习(五)-决策树和随机森林

这节课终于不是那么迷糊了,如果100分满分的话,听懂程度有70分了,初学者就是这么容易满足. :| 老师说这是这20次课里最简单的一次...oh...no. 不废话了,接着记笔记吧. CART:classsification and regression tree 三种决策树:ID3,C4.5,CART 树是最重要的数据结构. 决策树示意图: 决策树最重要的知识点: 决策树学习采用的是自顶向下的递归方法,其基本思想是以信息熵为度量构造一棵熵值下降最快的树,到叶子节点处的熵值为零.此时每个叶节点中

神经网络的6个基本问题

转自I love Matlab论坛 视频制作好以后,自己再回头看看,感觉讲的有点磨叽, 适合初学者看!下个视频,争取简化一点. 大家看了以后,有什么意见的,尽管提啊! 这一节主要讲了以下几个问题: •第一个问题:什么时候可以用神经网络? •第二个问题:分类还是回归?(classification or regression) •第三个问题:Deterministic 还是Stochastic •第四个问题:Supervised 还是 Unsupervised •第五个问题:On-line 还是

机器学习 (三) 逻辑回归 Logistic Regression

文章内容均来自斯坦福大学的Andrew Ng教授讲解的Machine Learning课程,本文是针对该课程的个人学习笔记,如有疏漏,请以原课程所讲述内容为准.感谢博主Rachel Zhang 的个人笔记,为我做个人学习笔记提供了很好的参考和榜样. § 3.  逻辑回归 Logistic Regression 1 分类Classification 首先引入了分类问题的概念——在分类(Classification)问题中,所需要预测的$y$是离散值.例如判断一封邮件是否属于垃圾邮件.判断一个在线交

机器学习方法:回归(三):最小角回归Least Angle Regression(LARS),forward stagewise selection

希望与志同道合的朋友一起交流,我刚刚设立了了一个技术交流QQ群:433250724,欢迎对算法.技术.应用感兴趣的同学加入. 前面两篇回归(一)(二)复习了线性回归,以及L1与L2正则--lasso和ridge regression.特别描述了lasso的稀疏性是如何产生的.在本篇中介绍一下和lasso可以产生差不多效果的两种feature selection的方法,forward stagewise selection和最小角回归least angle regression(LARS).尤其是