• 简介

假设你是某某大学某某系的主任,你想根据每个申请者在两次考试中的成绩来确定他们的入学机会。你有以前申请者的历史数据,可以用作对数几率回归的训练集。对于每个训练示例,你都有申请人在两次考试中的分数和录取结果。

  • 绘制数据

横纵坐标是申请人两次考试的成绩,录取和未录取的示例用两种记号标出。

# 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.
from matplotlib import pyplot as plt
import numpy as npdef plotData(X, y):exam1_0 = []exam2_0 = []exam1_1 = []exam2_1 = []for i in range(len(y)):if y[i] == 0:exam1_0.append(X[i][0])exam2_0.append(X[i][1])elif y[i] == 1:exam1_1.append(X[i][0])exam2_1.append(X[i][1])plt.title("Training data")plt.xlim(30, 100)plt.ylim(30, 100)plt.xticks(np.arange(30, 101, 10))plt.yticks(np.arange(30, 101, 10))plt.xlabel("Exam 1 score")plt.ylabel("Exam 2 score")plt.scatter(exam1_0, exam2_0, s=50, c='y', marker='o')plt.scatter(exam1_1, exam2_1, s=50, c='b', marker='+')plt.legend(scatterpoints=1, labels=['Not admitted', 'Admitted'], loc=1)plt.show()

如图:

  • Sigmoid函数

对数几率回归的假设函数定义为:

其中函数g就是sigmoid函数,定义为:

# SIGMOID Compute sigmoid function
#   g = SIGMOID(z) computes the sigmoid of z.
import numpy as np
import mathdef sigmoid(z):g = np.zeros(shape=z.shape)g = 1/(1+math.e**(-z))return g

迭代训练1000000次,得到梯度下降结果如下,可以看到代价函数在不断减小,并逐渐收敛于期望代价:

Running Gradient Descent ...

After 0 steps, the cost function: [0.69829069]
After 100000 steps, the cost function: [0.38738841]
After 200000 steps, the cost function: [0.31655389]
After 300000 steps, the cost function: [0.28368669]
After 400000 steps, the cost function: [0.2646348]
After 500000 steps, the cost function: [0.25216993]
After 600000 steps, the cost function: [0.24337911]
After 700000 steps, the cost function: [0.23685629]
After 800000 steps, the cost function: [0.23183607]
After 900000 steps, the cost function: [0.22786442]
Cost at theta found by gradient descent: 0.224654

Expected cost (approx): 0.203

  • 代价函数和梯度

对数几率回归的代价函数定义如下:

代价函数的梯度是一个与相同长度的向量,其中第j个元素(j=0,1,...,n)定义如下:

注意,虽然这个梯度看起来与线性回归的梯度相同,但是公式实际上是不同的,因为线性回归和对数几率回归对的定义不同。

# 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.
import numpy as np
import math
from sigmoid import sigmoiddef costFunction(theta, X, y):m = len(y)  # number of training examplesJ = 0grad = np.zeros(shape=(len(theta), 1))for i in range(m):# 以e为底J += -y[i]*math.log(sigmoid(X[i].dot(theta))) - (1-y[i])*math.log((1-sigmoid(X[i].dot(theta))))J = J/mfor i in range(len(theta)):for j in range(m):grad[i] += (sigmoid(X[j].dot(theta))-y[j]) * X[j][i]grad[i] = grad[i]/mreturn J, grad
  • 梯度下降

同时更新所有的

(看起来同线性回归的公式一模一样)

from costFunction import costFunction
import numpy as npdef gradientDescent(X, y, theta, alpha, num_iters):m = len(y)  # number of training examplesJ_history = np.zeros(shape=(num_iters, 1))for i in range(num_iters):_, grad = costFunction(theta, X, y)for j in range(len(theta)):theta[j] -= alpha*grad[j]# Save the cost J in every iterationcost, _ = costFunction(theta, X, y)J_history[i] = costif i % 100000 == 0:print("After %d steps, the cost function:" % i, J_history[i])# print("the gradient:", theta)return theta, J_history[-1]
  • 评价对数几率回归

评估对数几率回归得到的参数的一种方法是查看学习的模型对训练集的预测准确率。predict函数将根据给定的数据集和学习的参数向量生成“1”或“0”预测,并通过计算与示例一致的结果百分比来得到分类器的训练准确率。

# 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)
from sigmoid import sigmoid
import numpy as npdef predict(theta, X):m = len(X)p = np.zeros(shape=(m, 1))for i in range(m):if sigmoid(X[i].dot(theta)) > 0.5:p[i] = 1else:p[i] = 0return p

结果如下,可以看到在经过1000000次迭代训练后,训练的准确率已经与期望准确率相同:

Train Accuracy: 89.000000

Expected accuracy (approx): 89.0

具体代码参考:https://github.com/hanmy1021/MachineLearning

对数几率回归(Logistic Regression)相关推荐

  1. 对数几率回归 —— Logistic Regression

    机器学习基础算法python代码实现可参考:zlxy9892/ml_code 1 原理 1.1 引入 首先,在引入LR(Logistic Regression)模型之前,非常重要的一个概念是,该模型在 ...

  2. 对数几率回归——Logistics Regression原理

    Logistic Regression 简介 对数几率回归,也称为逻辑回归,虽然名为"回归",但实际上是分类学习方法. 优点 不仅可以预测类别,还可以得到近似概率,对许多需要利用概 ...

  3. 对数几率回归(Logistic Regression)总结

    对数几率回归logistic regression,虽然名字是回归,但是实际上它是处理分类问题的算法.简单的说回归问题和分类问题如下: 回归问题:预测一个连续的输出. 分类问题:离散输出,比如二分类问 ...

  4. 对数几率回归原理和代码实现--机器学习

    对数几率回归Logistic Regression 原理 代码实现 原理 对数几率回归,有的也叫逻辑回归,虽然带有回归二字,但本质是做分类任务的,也是线性模型的一种. 之前介绍过线性回归,就是用最简单 ...

  5. 对数几率回归(Logistic Regression)分析与实践

    目录 1 对数几率回归原理分析 1.1 引入 1.2 损失函数 1.3  求最优解 2 对数几率回归实践 Logistic回归的一般过程 Logistic回归的优缺点 Logistic回归算法描述(改 ...

  6. 逻辑回归(logistic regression)的本质——极大似然估计

    文章目录 1 前言 2 什么是逻辑回归 3 逻辑回归的代价函数 4 利用梯度下降法求参数 5 结束语 6 参考文献 1 前言 逻辑回归是分类当中极为常用的手段,因此,掌握其内在原理是非常必要的.我会争 ...

  7. python 逻辑回归 复杂抽样_逻辑回归(Logistic Regression) ----转载

    概要: 1. 介绍Logistic Regression的数学模型,推导并详细解释求解最优回归系数的过程: 2. Python实现Logistic Regression的基本版: 3. 介绍sklea ...

  8. 机器学习(二)线性模型——线性回归、对数几率回归、线性判别分析

    一.线性回归 线性回归(linear regression:试图学得一个线性模型以尽可能准确地预测实值输出标记. 1.最简单的形式:输入属性的数且只有一个, 最小二乘法:基于均方差误差最小化来进行模型 ...

  9. 个人总结:从 线性回归 到 逻辑回归 为什么逻辑回归又叫对数几率回归?

    逻辑回归不是回归算法,是分类算法,可以处理二元分类以及多元分类. 线性回归 线性回归的模型是求出特征向量Y和输入样本矩阵X之间的线性关系系数θ,满足Y = Xθ.此时Y是连续的,所以是回归模型. 对应 ...

  10. 札记_ML——《统计学习方法》逻辑回归logistic regression)

    统计学习方法:五. 逻辑回归logistic regression 逻辑回归logistic regression Logistic的起源 1).概念logistic回归又称logistic回归分析, ...

最新文章

  1. 连接的管道(最小生成树)
  2. Python爬虫基础面试题为2020年初大学生就业做准备(文末附教程)
  3. PHP中环境变量的设置
  4. 类模板特化之经典(一)
  5. python 数据分析-读写数据csv、xlsx文件
  6. mysql的cpu飙升到500_[MySQLCPU]线上飙升800%,load达到12的解决过程
  7. html xsl xml文件,用XSL显示XML文件看起来像HTML
  8. 第四届CocoaChina开发者大会官网上线
  9. wincc上位机与1200组态步骤_组态上位机WINCC与PLC通讯连接
  10. 采集工具有哪些-免费的采集工具下载
  11. 用混淆矩阵计算kappa系数
  12. 跨平台移动开发平台Flutter环境搭建
  13. H5调用Android原生Api
  14. 阿里P8整理出SQL笔记:收获不止SOL优化抓住SQL的本质
  15. 使用uni-app开发一个取流播放器(网络电视)app简陋版
  16. 【解决问题】‘cl‘ 不是内部或外部命令,也不是可运行的程序或批处理文件。
  17. 解决CSDN上传图片失败的问题
  18. 十七项网页恶意代码,别去害人啊!
  19. WinCE下GPRS自动拨号软件(GPRS AutoDial)
  20. 三菱5u 上位机mc协议_上位机读写三菱plc fx5u的内存数据示例

热门文章

  1. Oracle递归查询所有树结构,并确定其中的一条分支
  2. Mysql:日志管理:二进制事务日志
  3. 讨论String与string的区别.
  4. 《剑指offer》面试题20——顺时针打印矩阵(C++)
  5. 在Ubuntu中安装以theano作为backend的keras
  6. 阿里云服务器部署GeoServer以及跨域处理
  7. matlab经验正交分解函数EOF的实现—基于Climate Data Toolbox操作
  8. android实现Materia Design风格APP(二):部分Materia Design风格的控件介绍一
  9. android自定义软键盘
  10. ScrollView如何判断滑动到底部以及getHeight()方法与getMeasuredHeight()方法的一些理解