文章目录

  • 前置知识
  • 未正则化的二元逻辑回归
    • 数据载入
    • 数据可视化
    • 逻辑函数
    • 代价-梯度函数
    • 预处理数据集并初始化参数
    • 使用fminunc求解
    • 学习结果可视化
    • 预测
  • 正则化的二元逻辑回归
    • 构造高次项
    • 代价-梯度函数
    • 求解与可视化
    • 正则参数的选择

前置知识

逻辑回归的原理在此
正则化的原理在此

未正则化的二元逻辑回归

在这个问题中,我们要通过两场考试的分数来判断学生能否被录取。

数据载入

% Load Data
% The first two columns contain the exam scores and the third column contains the label.
data = load('ex2data1.txt');
X = data(:, [1, 2]);
y = data(:, 3);

数据可视化

这里我偷了个懒,直接用了吴恩达给的数据绘制函数:

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.
%% Find Indices of Positive and Negative Examplespos = find(y==1); neg = find(y == 0);% Plot Examplesplot(X(pos, 1), X(pos, 2), 'k+','LineWidth', 2, 'MarkerSize', 7);plot(X(neg, 1), X(neg, 2), 'ko', 'MarkerFaceColor', 'y','MarkerSize', 7);% =========================================================================hold off;end

主要步骤是,通过find函数把y==0y==1的数据下标找到,代入X中就能把两类学生用不同的记号绘制出来:

% Plot the data with + indicating (y = 1) examples and o indicating (y = 0) examples.
plotData(X, y);% Labels and Legend
xlabel('Exam 1 score')
ylabel('Exam 2 score')% Specified in plot order
legend('Admitted', 'Not admitted')


可以发现,两部分数据大致可以用一条直线划分开来,所以我们只需要尝试拟合出一条直线就可以了,需要三个参数θ0,θ1,θ2\theta_0,\theta_1,\theta_2θ0​,θ1​,θ2​。

逻辑函数

因为是逻辑回归,所以需要用到逻辑函数,逻辑函数的形式很简单:
g(z)=11+e−zg(z)=\frac{1}{1+e^{-z}} g(z)=1+e−z1​
所以编写也并不复杂,只需要注意运算符号前加点.使函数具有对向量的兼容性:

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

代价-梯度函数

因为这次我们不手写梯度下降,而是用matlab提供的高级算法fminunc直接求解,所以我们要编写一个代价-梯度函数costFunction提供给该算法。该函数需要能返回代价函数的值以及每个参数的梯度。

代价函数定义为
J(θ)=−1m∑i=1m[ylog⁡(hθ(x⃗))+(1−y)log⁡(1−hθ(x⃗))]J(\theta)=-\frac{1}{m}\sum_{i=1}^m\left[y\log(h_\theta(\vec{x}))+(1-y)\log(1-h_\theta(\vec{x}))\right] J(θ)=−m1​i=1∑m​[ylog(hθ​(x))+(1−y)log(1−hθ​(x))]
而我们已有矩阵
X=[x0(1)x1(1)⋯xn(1)x0(2)x1(2)⋯xn(2)⋮⋮⋱⋮x0(m)x1(m)⋯xn(m)],Θ=[θ0θ1⋮θn],Y=[y1y2⋮ym]X= \left[\begin{matrix} x_0^{(1)}&x_1^{(1)}&\cdots&x_n^{(1)}\\ x_0^{(2)}&x_1^{(2)}&\cdots&x_n^{(2)}\\ \vdots & \vdots & \ddots &\vdots\\ x_0^{(m)}&x_1^{(m)}&\cdots&x_n^{(m)}\\ \end{matrix}\right] ,\Theta=\left[\begin{matrix} \theta_0\\ \theta_1\\ \vdots \\ \theta_n\\ \end{matrix}\right], Y=\left[\begin{matrix} y_1\\ y_2\\ \vdots \\ y_m\\ \end{matrix}\right] X=⎣⎢⎢⎢⎢⎡​x0(1)​x0(2)​⋮x0(m)​​x1(1)​x1(2)​⋮x1(m)​​⋯⋯⋱⋯​xn(1)​xn(2)​⋮xn(m)​​⎦⎥⎥⎥⎥⎤​,Θ=⎣⎢⎢⎢⎡​θ0​θ1​⋮θn​​⎦⎥⎥⎥⎤​,Y=⎣⎢⎢⎢⎡​y1​y2​⋮ym​​⎦⎥⎥⎥⎤​
可将代价函数的计算过程向量化为
J(θ)=−1m[YTlog⁡(g(XΘ))+(1−YT)log⁡(1−g(XΘ))]J(\theta)=-\frac{1}{m}[Y^T\log(g(X\Theta))+(1-Y^T)\log(1-g(X\Theta))] J(θ)=−m1​[YTlog(g(XΘ))+(1−YT)log(1−g(XΘ))]
而梯度就是∂J(θ)∂θj\frac{\partial J(\theta)}{\partial \theta_j}∂θj​∂J(θ)​构成的列向量,公式为
∂J(θ)∂θj=1m∑i=1m(hθ(x(i)⃗)−y(i))xj(i)\frac{\partial J(\theta)}{\partial \theta_j}=\frac{1}{m}\sum_{i=1}^m(h_\theta(\vec{x^{(i)}})-y^{(i)})x_j^{(i)} ∂θj​∂J(θ)​=m1​i=1∑m​(hθ​(x(i))−y(i))xj(i)​
同样可以在向量化后利用矩阵快速计算:
∂J(θ)∂θj=1mXT(g(XΘ)−Y)\frac{\partial J(\theta)}{\partial\theta_j}=\frac{1}{m}X^T(g(X\Theta)-Y) ∂θj​∂J(θ)​=m1​XT(g(XΘ)−Y)
代码如下:

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% You need to return the following variables correctly
J = 0;
grad = zeros(size(theta));% ====================== YOUR CODE HERE ======================
% Instructions: Compute the cost of a particular choice of theta.
%               You should set J to the cost.
%               Compute the partial derivatives and set grad to the partial
%               derivatives of the cost w.r.t. each parameter in theta
%
% Note: grad should have the same dimensions as theta
%h=sigmoid(X*theta);
J=y'*log(h)+(1.-y')*log(1.-h);
J=-J/m;
grad=X'*(h-y);
grad=grad./m;% =============================================================end

预处理数据集并初始化参数

预处理:左边加一列1
初始化:全0

%  Setup the data matrix appropriately
[m, n] = size(X);% Add intercept term to X
X = [ones(m, 1) X];% Initialize the fitting parameters
initial_theta = zeros(n + 1, 1);

使用fminunc求解

直接用fminunc求解的好处在于,该算法不需要我们自己实现,同时它比梯度下降收敛的更快,且不需要人为设置学习速率α\alphaα。

调用fminunc的语句如下:

%  Set options for fminunc
options = optimoptions(@fminunc,'Algorithm','Quasi-Newton','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);

首先,我们设定fminunc的选项,GradObj设置为on,表示我们要给它的函数返回的是成本函数值和梯度,让它在求解最小值时使用梯度。此外,设置最大迭代次数MaxIter为400。

之后,定义一个以t为变量的函数@(t)(costFunction(t, X, y)),再传入变量初始值initial_theta和选项optionsfminunc就会帮助我们找到函数的最小值并返回此时的变量值theta与函数值costtheta里就是我们需要的参数矩阵了。

学习结果可视化

为了观察一下我们的参数效果如何,我们可以决策边界与数据集一起可视化,这里我还是借用吴恩达的代码:

function plotDecisionBoundary(theta, X, y)
%PLOTDECISIONBOUNDARY Plots the data points X and y into a new figure with
%the decision boundary defined by theta
%   PLOTDECISIONBOUNDARY(theta, X,y) plots the data points with + for the
%   positive examples and o for the negative examples. X is assumed to be
%   a either
%   1) Mx3 matrix, where the first column is an all-ones column for the
%      intercept.
%   2) MxN, N>3 matrix, where the first column is all-ones% Plot Data
plotData(X(:,2:3), y);
hold onif size(X, 2) <= 3% Only need 2 points to define a line, so choose two endpointsplot_x = [min(X(:,2))-2,  max(X(:,2))+2];% Calculate the decision boundary lineplot_y = (-1./theta(3)).*(theta(2).*plot_x + theta(1));% Plot, and adjust axes for better viewingplot(plot_x, plot_y)% Legend, specific for the exerciselegend('Admitted', 'Not admitted', 'Decision Boundary')axis([30, 100, 30, 100])
else% Here is the grid rangeu = linspace(-1, 1.5, 50);v = linspace(-1, 1.5, 50);z = zeros(length(u), length(v));% Evaluate z = theta*x over the gridfor i = 1:length(u)for j = 1:length(v)z(i,j) = mapFeature(u(i), v(j))*theta;endendz = z'; % important to transpose z before calling contour% Plot z = 0% Notice you need to specify the range [0, 0]contour(u, v, z, [0, 0], 'LineWidth', 2)
end
hold offend
% Plot Boundary
plotDecisionBoundary(theta, X, y);
% Add some labels
hold on;
% Labels and Legend
xlabel('Exam 1 score')
ylabel('Exam 2 score')
% Specified in plot order
legend('Admitted', 'Not admitted')
hold off;

看起来还不错。

预测

有了参数,我们就可以进行预测了,将待预测数据与参数矩阵相乘,代入逻辑函数并四舍五入之后就可以得到预测结果:

function p = predict(theta, X)
%PREDICT Predict whether the label is 0 or 1 using learned logistic
%regression parameters theta
%   p = PREDICT(theta, X) computes the predictions for X using a
%   threshold at 0.5 (i.e., if sigmoid(theta'*x) >= 0.5, predict 1)m = size(X, 1); % Number of training examples% You need to return the following variables correctly
p = zeros(m, 1);% ====================== YOUR CODE HERE ======================
% Instructions: Complete the following code to make predictions using
%               your learned logistic regression parameters.
%               You should set p to a vector of 0's and 1's
%p=round(sigmoid(X*theta));% =========================================================================end

在原数据集上的准确率可用下面的代码计算:

% Compute accuracy on our training set
p = predict(theta, X);
fprintf('Train Accuracy: %f\n', mean(double(p == y)) * 100);

正则化的二元逻辑回归

在上面的问题中,一根直线就能满足我们的需求,所以我们只用到三个参数,不需要正则化。但在下面的问题中,可视化后数据集长成这样:

%  The first two columns contains the X values and the third column
%  contains the label (y).
data = load('ex2data2.txt');
X = data(:, [1, 2]); y = data(:, 3);plotData(X, y);
% Put some labels
hold on;
% Labels and Legend
xlabel('Microchip Test 1')
ylabel('Microchip Test 2')
% Specified in plot order
legend('y = 1', 'y = 0')
hold off;


显然,这个问题并不能用一根直线解决,我们需要考虑更高次项,但由x1,x2x_1,x_2x1​,x2​可以组成无数多高次项,我们很难人工判断该用什么高次项。

构造高次项

索性我们直接把0次到6次项全部囊括进来,使用吴恩达写的mapFeature函数,将28个项即28个特征值都扔进矩阵中。

function out = mapFeature(X1, X2)
% MAPFEATURE Feature mapping function to polynomial features
%
%   MAPFEATURE(X1, X2) maps the two input features
%   to quadratic features used in the regularization exercise.
%
%   Returns a new feature array with more features, comprising of
%   X1, X2, X1.^2, X2.^2, X1*X2, X1*X2.^2, etc..
%
%   Inputs X1, X2 must be the same size
%degree = 6;
out = ones(size(X1(:,1)));
for i = 1:degreefor j = 0:iout(:, end+1) = (X1.^(i-j)).*(X2.^j);end
endend
% Add Polynomial Features
% Note that mapFeature also adds a column of ones for us, so the intercept term is handled
X = mapFeature(X(:,1), X(:,2));

代价-梯度函数

正则化以后,代价函数和梯度都加上了正则项,代价函数变为
J(θ)=−1m∑i=1m[ylog⁡(hθ(x⃗))+(1−y)log⁡(1−hθ(x⃗))]+λ2m∑j=1nθj2J(\theta)=-\frac{1}{m}\sum_{i=1}^m\left[y\log(h_\theta(\vec{x}))+(1-y)\log(1-h_\theta(\vec{x}))\right] +\frac{\lambda}{2m}\sum_{j=1}^n\theta_j^2 J(θ)=−m1​i=1∑m​[ylog(hθ​(x))+(1−y)log(1−hθ​(x))]+2mλ​j=1∑n​θj2​
梯度变为
∂J(θ)∂θj=1m∑i=1m(hθ(x(i))−y(i))xj(i)+λmθj\frac{\partial J(\theta)}{\partial \theta_j}=\frac{1}{m}\sum_{i=1}^m(h_\theta(x^{(i)})-y^{(i)})x_j^{(i)}+\frac{\lambda}{m}\theta_j ∂θj​∂J(θ)​=m1​i=1∑m​(hθ​(x(i))−y(i))xj(i)​+mλ​θj​
所以在未正则化的函数基础上稍微改一下就可以了,参数加上λ\lambdaλ,结果加上正则项,要注意θ0\theta_0θ0​不正则化。

function [J, grad] = costFunctionReg(theta, X, y, lambda)
%COSTFUNCTIONREG Compute cost and gradient for logistic regression with regularization
%   J = COSTFUNCTIONREG(theta, X, y, lambda) computes the cost of using
%   theta as the parameter for regularized 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% You need to return the following variables correctly
J = 0;
grad = zeros(size(theta));% ====================== YOUR CODE HERE ======================
% Instructions: Compute the cost of a particular choice of theta.
%               You should set J to the cost.
%               Compute the partial derivatives and set grad to the partial
%               derivatives of the cost w.r.t. each parameter in thetah=sigmoid(X*theta);
J=y'*log(h)+(1.-y')*log(1.-h);
J=-J/m;
J=J+(lambda/(2*m)).*(theta'*theta-theta(1)^2);grad=X'*(h-y);
grad=grad./m;
tmp=grad(1);
grad=grad+(lambda/m).*theta;
grad(1)=tmp;% =============================================================end

求解与可视化

求解没有太大差异,设置一下参数λ\lambdaλ就好了:

% Initialize fitting parameters
initial_theta = zeros(size(X, 2), 1);lambda = 1;
% Set Options
options = optimoptions(@fminunc,'Algorithm','Quasi-Newton','GradObj', 'on', 'MaxIter', 1000);% Optimize
[theta, J, exit_flag] = fminunc(@(t)(costFunctionReg(t, X, y, lambda)), initial_theta, options);

效果还是很不错的:

正则参数的选择

正则参数是平衡对训练集的拟合程度与参数大小的关键,当该参数选取不合理的时候,同样会造成过拟合或欠拟合。

当λ=0\lambda=0λ=0时,出现过拟合:

当λ=100\lambda=100λ=100时,出现欠拟合:

机器学习:使用matlab的fminunc+正则化实现二元逻辑回归相关推荐

  1. 基于Octave/Matlab的二元逻辑回归(logistic regression)算法

    基于Octave/Matlab的二元逻辑回归(logistic regression)算法 本博文基于吴恩达老师的机器学习网课,是对作业代码进行简化和补充完整后的实现. 逻辑回归算法的基本思想 sig ...

  2. 《人工智能》机器学习 - 第5章 逻辑回归(二 二元逻辑回归实战)

    5.2二元逻辑回归实战 5.2.1二元逻辑回归简单实例 首先看看数据吧. 随机的一些数据,这是一个二分问题的数据.先导入数据.Python代码如下. """ 函数说明:读 ...

  3. 机器学习 -- 二元逻辑回归实例

    二元逻辑回归可用于向量的概率预测,是一种分类算法.迭代方式可选择最小二乘法或梯度下降. 迭代之后会得到每个特征的系数. 公式(对于有N个特征的向量,其中w[i]为权): f(x) = 1/(1+ e^ ...

  4. 机器学习:二元逻辑回归的损失函数

    损失函数的概念 在学习决策树时,曾经提到过两种模型表现:在训练集上的表现,和在测试集上的表现.建模,是追求模型在测试集上的表现最优,因此模型的评估指标往往是用来衡量模型在测试集上的表现的.然而,逻辑回 ...

  5. 二元逻辑回归 · 数学推导过程及代码实现完全解析

    文章目录 概述 两个重要函数 预测的基本思想 二元逻辑回归 线性模型的简单回顾 从线性回归到二元逻辑回归 参数怎么估计 梯度下降 牛顿迭代 最近修改:2021/6/17 原文<从二元逻辑回归到多 ...

  6. Interview:算法岗位面试—10.24下午—上海某软件公司(机器学习,上市)电话面试—考察SVM、逻辑回归、降低过拟合、卷积网络基础等

    Interview:算法岗位面试-10.24下午-上海某软件公司(机器学习,上市)电话面试-考察SVM.逻辑回归.降低过拟合.卷积网络基础等 导读:当时电话来的非常快,我刚做完一家公司的笔试,接着来了 ...

  7. 练习:二元逻辑回归实现

    一.什么是逻辑回归模型 逻辑回归模型是线性的二分类模型. 逻辑回归的表达式: f(x)就是大名鼎鼎的Sigmoid函数,也称为Logistic函数.这个函数的曲线如下: sigmoid函数的作用就是将 ...

  8. 二元逻辑回归损失函数的数学解释与公式推导

    我们基于极大似然法来推导二元逻辑回归的损失函数,这个推导过程能够帮助我们了解损失函数怎么 得来的,以及为什么J(θ)J(\theta)J(θ)的最小化能够实现模型在训练集上的拟合最好. 我们的目标是: ...

  9. Python梯度下降法实现二元逻辑回归

    Python梯度下降法实现二元逻辑回归 二元逻辑回归假设函数 定义当函数值大于等于0.5时,结果为1,当函数值小于0.5时,结果为0.函数的值域是(0, 1). 二元逻辑回归的损失函数 上图为二元逻辑 ...

  10. 机器学习算法——以癌症分类为例子介绍 逻辑回归(sklearn实现)

    目录 1.逻辑回归介绍 1.1.逻辑回归的应用场景 1.2.逻辑回归的原理 1.2.1 输入: 1.2.2 激活函数 1.3.损失以及优化 1.3.1 损失 1.3.2 优化 总结: 2.逻辑回归ap ...

最新文章

  1. 后氧传感器正常数据_氧传感器正常数据流
  2. php如何保存服务器会话,如何用PHP在服务器上创建会话?
  3. 开源项目PullToRefresh详解(一)——PullToRefreshListView
  4. python数据存储与读取_【Python爬虫】数据保存与读取
  5. 文巾解题3. 无重复字符的最长子串
  6. Qtcreator 之中文目录
  7. 管理mysql表知识点_数据库复习提纲(必考知识点整理)
  8. 傲腾服务器系统,英特尔傲腾加速 释放数据价值
  9. python-基础-面向对象2-异常-模块工厂模式
  10. 疯狂程序员网址。。。
  11. VMware安装苹果虚拟机-亲测有效
  12. 公网IP、私网IP、动态IP、静态IP
  13. 【观察】戴尔:为核心数据“保驾护航”,为数字化转型“拨云见日”
  14. AD19导出bom表的方法(按照元件不同数值分类,重点信息突出)
  15. WebDriver Sierra 10.12.3 N卡驱动
  16. 计算机网络(三)—— 数据链路层(1):数据链路层概述
  17. C语言——经典200道实例【基础例题100道——进阶例题100道】
  18. Python 3 爬虫之批量下载字帖图片
  19. 个人深度学习工作站配置
  20. 因果分析与关联分析的联系

热门文章

  1. 使用BoobSnail生成任意Excel 4.0 XLM宏文件
  2. 政府机构网络安全实战
  3. 让面试官赞扬的IO读取方法:大文件进行词频统计(单线程与多线程分别解决)利用Buffer流简单又快捷
  4. 计算机应用基础专科在线考试,电子科技大学在线考试2019年春计算机应用基础专科(18页)-原创力文档...
  5. win10 开机启动_win10 -- 取消不需要的开机启动项和服务项加快win10系统开机速度...
  6. Intellij IDEA创建maven项目无java文件问题
  7. 2017.6.4 入门组 NO.4——猜数
  8. 使用Java实现面向对象编程(6)
  9. Java直接插入排序
  10. iOS 不规则的ImageView