梯度下降法解逻辑斯蒂回归

合集下载
  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

梯度下降法解逻辑斯蒂回归
本⽂是Andrew Ng 在Coursera 的机器学习课程的笔记。

Logistic 回归属于分类模型。

回顾,输出的是连续的实数,⽽Logistic 回归输出的是[0,1]区间的概率值,通过概率值来判断因变量应该是1还是0。

因此,虽然名字中带着“回归”(输出范围常为连续实数),但Logistic 回归属于分类模型(输出范围为⼀组离散值构成的集合)。

整体步骤
假如我们的⾃变量是“数学课和英语课的成绩”,x={x1,x2},因变量是“能否被哥⼤录取”,y ∈{0,1}。

我们要通过这两个⾃变量的分布,来预测因变量的值。

Logistic 回归的步骤为:
1. 设定拟合函数(hypothesis function ):h θ(x),其意义是给定参数θ,根据输⼊x ,给出输出h θ(x),当输出值⼤于0.5时预测录取,否则预测被拒。

2. 设定代价函数(cost function ):J(θ),其意义是累加所有样本的 预测结果h θ(x) 与 真实结果y 之间的差距。

3. 利⽤梯度下降法,来调整参数θ,使得代价函数J(θ)的值最⼩。

⽐较线性回归与Logistic 回归,可以看出⼆者⾮常相似,但是Logistic 回归的拟合函数(步骤⼀)和代价函数(步骤⼆)的定义⽅法与线性回归有所不同。

Step 1:拟合函数
线性回归的拟合函数为:h θ(x) = θTx ,输出范围为所有实数,⽽其因变量的取值范围也确实属于所有实
数。

但是Logistic 回归的最终输出要么是0,要么是1,我们不能直接套⽤线性回归的拟合函数。

对于
Logistic 回归,我们需要控制输出在[0,1]之间,因此借助函数g:
g (z )=1
1+e −z 函数g 为S 型函数(Sigmoid function ),也称为Logistic function ,“Logistic 回归”就是得名于此。

最终的拟合函数为:
h θ(x )=g (θT x )=1
1+e −θT x 这个拟合函数的输出范围在[0,1]之间,表⽰分类结果为1的可能性。

例如,我输⼊我的成绩,得到的拟合函数输出值为0.7,就表⽰我有70%的概率被哥⼤录取(30%的概率被拒)。

当输出值超过0.5,我们将其分类为1(这表⽰模型最终预测我会被哥⼤录取)。

值为0.5的线称为“Decision Boundary”(可以是曲线)。

想象⼀个三维坐标系(x1,x2,y),对于任意的地⾯坐标(x1,x2),都有唯⼀的y 值与之对应。

⾸先计算 θTx ,值可正可负且没有边界。

然后将其作为S 型函数g 的输⼊,得到的输出固定在[0,1]之间。

当 θTx≥0时,h≥0.5,预测为1分类,否则为0分类。

拟合函数的意义就在于将值固定在0到1之间。

Step 2:代价函数
如果直接套⽤线性回归的代价函数,那么得到的代价函数将⾮凸(non-convex ),利⽤梯度下降我们可能停留
在局部最⼩值,⽽不是我们想要的全局最⼩值。

因此我们需要重新定义代价函数。

对于⼀个样本,我们新的代价函数定义如下:
公式可以进⼀步化简为:
Cost (h θ(x ),y )=−ylog (h θ(x ))−(1−y )log (1−h θ(x ))
下图是代价函数曲线,横坐标为h 的值,纵坐标为代价。

可以看出,在y=1的前提下,如果预测值越接近1,那么相应代价就越⼩,反之则越⼤。

g (z )=11+e
−z (x )=g (x )=h θθT 11+e −x
θT Cost ((x ),y )=−ylog ((x ))−(1−y )log (1−(x ))h θh θh θ
将所有m个样本的代价累加并平均,我们有最终的代价函数:
这个代价函数满⾜convex的条件,所以有全局最⼩值。

其来源与最⼤似然估计有关,此处略去细节。

Step 3:梯度下降
我们采⽤与中⼀样的梯度下降法来确定θ的值,即设置⼀个合适的学习率α之后,同步更新所有j=1 to n:
重复更新步骤,直到代价函数的值收敛为⽌。

⾼级操作
我们在第三步使⽤的梯度下降法虽然可⾏,但是收敛速度⽐较慢。

有不少⾼级梯度下降算法已经被提出,包括 Conjugate gradient、BFGS、L-BFGS 等等。

这些算法的优点是不需要⼿动挑选学习率,速度也较快,但是缺点就是⽐较复杂,难以⼿动实现。

不过,借助matlab我们就可以利⽤这些算法来计算了。

我们可以利⽤matlab中的 (Find minimum of unconstrained multivariable function) 来实现⾼级操作。

1 2 3options = optimset(‘GradObj’, ‘on’, ‘MaxIter’, ‘100’);
initialTheta = zeros(2,1);
[optTheta, functionVal, exitFlag] = fminunc(@costFunction, initialTheta, options);
的:
第⼀个参数是⼀个指向代价函数的指针,此代价函数需要返回代价值与各个参数的偏导数;
第⼆个参数是θ的初始值;
第三个参数是⼀些开关选项。

matlab代码
输⼊是ex2data1.txt⽂件,前两列是⾃变量,最后⼀列是因变量,⽤逗号分隔,格式类似于:
34.62365962451697,78.0246928153624,0
30.28671076822607,43.89499752400101,0
……
这个代码⽤两种⽅法来进⾏梯度下降,⼀种是常规⽅法,⼀种是⾼级⽅法。

实验中发现常规⽅法经过了很长时间(⼤约好⼏分钟)还是没有收敛,且需要考虑学习率的⼤⼩;⽽⾼级⽅法只需要⼏秒钟就能收敛,并且不需要考虑学习率。

1
2
3
4
5 6 7function logisticRegressionDemo( )
%A demo of logistic regression
% Logistic regression using traditional gradient descent and advanced methods
9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75%% Load Data
data = load('ex2data1.txt');
X = data(:, [1, 2]); y = data(:, 3);
%% ============ Part 1: Compute Cost and Gradient ============
% Setup the data matrix appropriately, and add ones for the intercept term
[m, n] = size(X);
% Add intercept term to x and X_test
X = [ones(m, 1) X];
% Initialize fitting parameters
initial_theta = zeros(n + 1, 1);
% Compute and display initial cost and gradient
[cost, grad] = costFunction(initial_theta, X, y);
theta = initial_theta;
iterNum = 50000;
costList = zeros(iterNum,1);
% this method fails because it doesn't converge even I set iteration number to 50000, which takes quite a long time for i=1:iterNum
theta = theta - 0.001 * grad;
[cost, grad] = costFunction(theta, X, y);
costList(i,1)= cost;
end;
plot(costList);
% ======================= Predict ============================
prob = sigmoid([1 45 85] * theta);
fprintf(['For a student with scores 45 and 85, we predict an admission '...
'probability of %f\n\n'], prob);
%% ============= Part 2: Optimizing using fminunc =============
% Set options for fminunc
options = optimset('GradObj', 'on', 'MaxIter', 400);
% Run fminunc to obtain the optimal theta
% This function will return theta and the cost
[theta, cost] = fminunc(@(t)(costFunction(t, X, y)), initial_theta, options);
% ======================= Predict ============================
prob = sigmoid([1 45 85] * theta);
fprintf(['For a student with scores 45 and 85, we predict an admission '...
'probability of %f\n\n'], prob);
end
function g = sigmoid(z)
%SIGMOID Compute sigmoid functoon
% J = SIGMOID(z) computes the sigmoid of z.
g = 1 ./ (1 + exp(-z));
end
function [J, grad] = costFunction(theta, X, y)
%COSTFUNCTION Compute cost and gradient for logistic regression
% J = COSTFUNCTION(theta, X, y) computes the cost of using theta as the
% parameter for logistic regression and the gradient of the cost
% w.r.t. to the parameters.
% Initialize some useful values
m = length(y); % number of training examples
J = 0;
grad = zeros(size(theta));
for i = 1:m
J = J + (-y(i)) * log(sigmoid(theta' * X(i,:)')) - (1-y(i)) * log(1-sigmoid(theta' * X(i,:)'));
grad = grad + (sigmoid(theta' * X(i,:)') - y(i)) * X(i,:)';
end
J = J / m;
grad = grad ./ m;
7778
79
80
81
end
正则化:防⽌过拟合
我们采⽤正则化(Regularization )的⽅法,通过修改代价函数来防⽌过拟合。

过拟合问题⼀般归咎于过多的特征类型。

有两种⽅法来减少过拟合:
1. 丢掉⼀些特征,不过这样也丢失了⼀些信息;
2. 正则化,修改代价函数,来限制参数值的⼤⼩
正则化除了能防⽌过拟合之外,还有⼀个好处就是可以避免利⽤normal equation ⼀步到位地求得参数值中需要考虑的矩阵可逆问题,因为加⼊正则参数之后的矩阵总是可逆的。

修改之后的代价函数和梯度⽅程见下,出于习惯我们不对j=0
的参数做正则化,但是即使做了影响也不⼤:
有关正则化的详细讨论可以见。

相关文档
最新文档