机器学习:Experiment 4: Logistic Regression and Newton’s Method

实验目的

在本次实验中,使用牛顿法实现逻辑回归的分类任务。

实验步骤与内容:

1. 数据加载

下载数据 exe4Data.zip 并解压。对于这个练习,假设一所高中有这样一个数据集,包括 40 名被大学录取的学生和 40 名未被录取的学生。每个(x(i),y(i))训练示例都包含一个学 生在两项标准化考试中的分数,以及该学生是否被录取的标签。 你的任务是建立一个二元 分类模型,根据一个学生在两次考试中的分数来估计大学入学机会。 在你的训练数据中,

a. x 数组的第一列表示所有 test1 的分数,第二列表示所有 test2 的分数。
b. y 向量使用“1”来标记被录取的学生,使用“0”来标记未被录取的学生。

2. 绘制数据

将训练示例的数据加载到程序中,并将 x0=1 偏置项(截距项)添加到 x 矩阵中。 在开始牛顿法之前,我们将首先用不同的符号绘制数据来表示这两个类。在 Matlab/Octave 中,可以使用 find 命令将正类和负类分开:

x=load('ex4x.dat');
y=load('ex4y.dat');
[m,n]=size(x);
x=[ones(m,1),x];%add one column
%find returns the indices of the rows 
%meeting the specified condition
figure
pos=find(y==1);
neg=find(y==0);
%Assume the features are in the 2nd and 3rd
%columns of x
plot(x(pos,2),x(pos,3),'+');
hold on
plot(x(neg,2),x(neg,3),'o');
legend({'Admitted','Not Admitted'});
xlabel('Exam1 score');
ylabel('Exam2 score');
title('Training data');
hold off

得到的结果图应为:
figure

3.牛顿法

回想一下,在logistic回归中,假设函数是:
h θ ( x ) = g ( θ T x ) = 1 1 + e − θ T x = P ( y = 1 ∣ x ; θ ) h_\theta(x)=g(\theta_Tx)=\frac{1}{1+e^{-\theta^Tx}}=P(y=1|x;\theta) hθ(x)=g(θTx)=1+eθTx1=P(y=1x;θ)
在这个例子中,假设概率都是准确的,并给定X的特征值。
Matlab/Octave没有Sigmoid的库函数,所以你必须自己定义它。 最简单的方法是通过内联表达式:(但是由于MATLAB改版,最新版将删除内联函数,所以使用匿名函数)

%define the sigmoid function
%g = inline('1.0 ./ (1.0+ exp(-z))');
g=@(z)1.0 ./ (1.0+exp(-z));
% Usage: To find the value of the sigmoid 
% evaluated at 2, call g(2)

损失函数J(θ)被定义为
J ( θ ) = 1 m ∑ i = 1 m [ − y ( i ) l o g ( h θ ( x ( i ) ) − ( 1 − y ( i ) ) l o g ( 1 − h θ ( x ( i ) ) ) ] J(\theta)=\frac{1}{m}\sum_{i=1}^m[-y^{(i)}log(h_\theta(x^{(i)})-(1-y^{(i)})log(1-h_\theta(x^{(i)}))] J(θ)=m1i=1m[y(i)log(hθ(x(i))(1y(i))log(1hθ(x(i)))]
我们的目标是要使用牛顿法最小化误差函数,回想牛顿法更新规则
θ ( t + 1 ) = θ ( t ) − H − 1 ∇ θ J \theta^{(t+1)}=\theta^{(t)}-H^{-1}\nabla_\theta{J} θ(t+1)=θ(t)H1θJ

在逻辑回归中,梯度下降和海森Hessian公式为
∇ θ J = 1 m ∑ i = 1 m ( h θ ( x ( i ) ) − y ( i ) ) x ( i ) \nabla_\theta{J}=\frac{1}{m}\sum_{i=1}^m(h_\theta(x^{(i)})-y^{(i)})x^{(i)} θJ=m1i=1m(hθ(x(i))y(i))x(i)

现在,在你的程序中实现牛顿法,并初始化 θ = 0 ⃗ θ=\vec{0} θ=0 ,为了决定迭代次数,计算每一次迭代后的J(θ)并将它画在你的结果中。
记录的J(θ):
figure
牛顿法通常在5-15次迭代后收敛。如果你发下需要更多的迭代次数时,那么你应该检查实现过程中出现的错误。
收敛后,使用θ的值在分类问题中找到决策边界。 判定边界定义为所在线
P ( y = 1 ∣ x ; θ ) = g ( θ T x ) = 0.5 P(y=1|x;\theta)=g(\theta^Tx)=0.5 P(y=1x;θ)=g(θTx)=0.5
它对应于 θ T x = 0 \theta^Tx=0 θTx=0
绘制决策边界相当于绘制 θ T x = 0 \theta^Tx=0 θTx=0线。 当你完成时,你的图形如下:
figure
最后,记录你对这些问题的答案。

结论分析

问题1

1.θ的价值是多少? 收敛需要多少次迭代?
θ = − 16.3787 0.1483 0.1589 \theta=\\-16.3787\\0.1483\\0.1589 θ=16.37870.14830.1589
由下图可知,大概5次的时候就已经收敛了。
figure

问题2

2.如果一个学生在第一次考试中得了20分,在第二次考试中得了80不会被录取的概率是多少?

该学生第一次20,第二次80,那么不被录取的概率
P=1-g([1, 20, 80]*theta);
figure

Code

x=load('ex4x.dat');
y=load('ex4y.dat');
[m,n]=size(x);
x=[ones(m,1),x];%add one column
%find returns the indices of the rows 
%meeting the specified condition
figure
pos=find(y==1);
neg=find(y==0);
%Assume the features are in the 2nd and 3rd
%columns of x
plot(x(pos,2),x(pos,3),'+');
hold on
plot(x(neg,2),x(neg,3),'o');
legend({'Admitted','Not Admitted'});
xlabel('Exam1 score');
ylabel('Exam2 score');
title('Training data');
hold off
%Newton's method
figure
theta=zeros(n+1,1);
%define the sigmoid function
%g = inline('1.0 ./ (1.0+ exp(-z))');
g=@(z)1.0 ./ (1.0+exp(-z));
% Usage: To find the value of the sigmoid 
% evaluated at 2, call g(2)
ITR=9;%5-15 iterations
J=zeros(ITR,1);
for i=1:ITR
    %calculate the hypothesis function
    z=x*theta;
    h=g(z);%logistic function
    J(i) =(1/m)*sum(-y.*log(h) - (1-y).*log(1-h));%Vector representation of a loss function
    grad=(1/m).*x'*(h-y);%gradients
    H=(1/m).*x'*diag(h)*diag(1-h)*x;%vector of matrix
    theta=theta-H\grad;
end
%display theta
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(x(pos,2),x(pos,3),'+');
hold on
plot(x(neg,2),x(neg,3),'o');
legend({'Admitted','Not Admitted'});
xlabel('Exam1 score');
ylabel('Exam2 score');
title('Newton`s method');
% 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:ITR-1, J, 'o--', 'MarkerFaceColor', 'r', 'MarkerSize', 5)
xlabel('Iteration');
ylabel('J');
title('Iteration and Jcost');
% Display J
hold off
J
  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值