Coursera-ML-AndrewNg-ex2

Programming Exercise 2: Logistic Regression

在本次练习中,你将实现逻辑回归并将其应用于两个不同的数据集。

在整个练习中,您将使用脚本ex2.mex2_reg.m。这些脚本设置了问题的数据集并调用了将要编写的函数


1 Logistic Regression

在本部分的练习中,您将建立一个Logistic回归模型来预测学生是否被大学录取,假设您是大学部门的管理员,并且您想根据每个申请人的入学机会来确定他们的入学机会。两次考试的结果。您拥有以前申请人的历史数据,可以用作逻辑回归的训练集。对于每个培训示例,您都有两次考试的申请人分数和录取决定。您的任务是建立一个分类模型,根据这两次考试的分数估算申请人的录取概率。此大纲和ex2.m中的框架代码将指导您完成本练习。

1.1 Visualizing the data

在开始实施任何学习算法之前,如果可能的话,最好可视化数据。在ex2.m的第一部分中,代码将加载数据并将其通过调用plotData.m函数显示在二维图上。您现在将在plotData.m中完成代码,以使其显示如图1所示的图形。轴是两个考试分数,正例和负例用不同的标记显示。

plotData.m

function plotData(X, y)
%PLOTDATA Plots the data points X and y into a new figure 
%   PLOTDATA(x,y) plots the data points with + for the positive examples
%   and o for the negative examples. X is assumed to be a Mx2 matrix.

% Create New Figure
figure; hold on;

% ====================== YOUR CODE HERE ======================
% Instructions: Plot the positive and negative examples on a
%               2D plot, using the option 'k+' for the positive
%               examples and 'ko' for the negative examples.
%

X1=X(:,1);X2=X(:,2);
pos=find(y);neg=find(~y);

plot(X1(pos),X2(pos),'k+','LineWidth', 2, 'MarkerSize',7);
plot(X1(neg),X2(neg),'ko', 'MarkerFaceColor', 'y','MarkerSize', 7)


% =========================================================================


hold off;

end

在这里插入图片描述

1.2 Implementation

1.2.1 Warmup exercise: sigmoid function

logistic回归假设的定义
h θ ( x ) = g ( θ T x ) h_{\theta}(x)=g(\theta^{T}x) hθ(x)=g(θTx)
其中函数g为s型函数。sigmoid函数定义为:
g ( z ) = 1 1 + e − z g(z)=\frac{1}{1+e^{-z}} g(z)=1+ez1
第一步是在sigmoid.m中实现这个函数,以便它可以被程序的其余部分调用。当您完成时,尝试通过在MATLAB命令行中调用sigmoid(x)来测试一些值。当x的正值较大时,sigmoid应接近于1,当x的负值较大时,sigmoid应接近于0。对sigmoid(0)求值应该正好得到0.5。您的代码还应该使用向量和矩阵。对于一个矩阵,你的函数应该对每个元素执行s型函数。

sgmoid.m

function g = sigmoid(z)
%SIGMOID Compute sigmoid function
%   g = SIGMOID(z) computes the sigmoid of z.

% You need to return the following variables correctly 
g = zeros(size(z));

% ====================== YOUR CODE HERE ======================
% Instructions: Compute the sigmoid of each value of z (z can be a matrix,
%               vector or scalar).

g=1./(1+exp(-z));


% =============================================================

end

现在您将实现logistic回归的成本函数和梯度。在costFunction.m中完成代码。返回代价和梯度。回想一下logistic回归中的成本函数是
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θ(xi))(1y(

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值