机器学习/逻辑回归(logistic regression)/--附python代码
个人分类: 机器学习
本文为吴恩达《机器学习》课程的读书笔记,并用python实现。
前一篇讲了线性回归,这一篇讲逻辑回归,有了上一篇的基础,这一篇的内容会显得比较简单。
逻辑回归(logistic regression)虽然叫回归,但他做的事实际上是分类。这里我们讨论二元分类,即只分两类,y属于{0,1}。
选择如下的假设函数:
这里写图片描述
其中:
这里写图片描述
上式称为逻辑函数或S型函数,图像如下图:
这里写图片描述
可以看到,当z趋向正无穷,g(z)趋向1,当z趋向负无穷g(z)趋向0,即g(z)取值[0,1]。
同样,令 这里写图片描述 ,
现在我们要根据训练集,获取上面模型的最好参数 值。同样,可以通过最大似然函数的方法来求解。
假设:
这里写图片描述
合并上面两个式子:
这里写图片描述
假设m个训练样本是独立的,则似然函数:
这里写图片描述
同样,我们求其对数值以方便求解:
这里写图片描述
我们的目的是最大似然函数,即max l ,可以用梯度上升法:
这里写图片描述
下面我们先对g(z)进行函数求导(后面会用到):
这里写图片描述
则可以求得一个样本时的导数(第二步用到 ):
这里写图片描述
则增量梯度法(上一篇线性回归有介绍)有:
这里写图片描述
m个样本的批处理梯度法有:
这里写图片描述
python 代码:
##author:lijiayan
##data:2016/10/27
from numpy import *
import matplotlib.pyplot as plt
def loadData(filename):
data = loadtxt(filename)
x = data[:,0:2]
y = data[:,2:3]
return x,y
#the sigmoid function
def sigmoid(x):
return 1.0 / (1 + exp(-x))
#the cost function
def costfunction(y,h):
y = array(y)
h = array(h)
J = sum(y*log(h))+sum((1-y)*log(1-h))
return J
# the batch gradient descent algrithm
def gradescent(x,y):
m,n = shape(x) #m: number of training example; n: number of features
x = c_[ones(m),x] #add x0
x = mat(x) # to matrix
y = mat(y)
a = 0.002 # learning rate
maxcycle = 2000
theta = ones((n+1,1)) #initial theta
J = []
for i in range(maxcycle):
h = sigmoid(x*theta)
theta = theta + a * x.transpose()*(y-h)
cost = costfunction(y,h)
J.append(cost)
plt.plot(J)
plt.show()
return theta,cost
#the stochastic gradient descent (m should be large,if you want the result is good)
def stocGraddescent(x,y):
m,n = shape(x) #m: number of training example; n: number of features
x = c_[ones(m),x] #add x0
x = mat(x) # to matrix
y = mat(y)
a = 0.01 # learning rate
theta = ones((n+1,1)) #initial theta
J = []
for i in range(m):
h = sigmoid(x[i]*theta)
theta = theta + a * x[i].transpose()*(y[i]-h)
cost = costfunction(y,h)
J.append(cost)
plt.plot(J)
plt.show()
return theta,cost
#plot the decision boundary
def plotbestfit(x,y,theta):
plt.plot(x[:,0:1][where(y==1)],x[:,1:2][where(y==1)],'ro')
plt.plot(x[:,0:1][where(y!=1)],x[:,1:2][where(y!=1)],'bx')
x1= arange(-4,4,0.1)
x2 =(-float(theta[0])-float(theta[1])*x1) /float(theta[2])
plt.plot(x1,x2)
plt.xlabel('x1')
plt.ylabel(('x2'))
plt.show()
def classifyVector(inX,theta):
prob = sigmoid(sum(inX*theta))
print 'the probobility is:',prob
if prob > 0.5:
return 1.0
else:
return 0.0
if __name__=='__main__':
x,y = loadData("testSet.txt")
theta,cost = gradescent(x,y)
print 'theta:\n',theta
print 'J:',cost
X = [1,2,9]
print 'the new input:',X
h = classifyVector(X,theta)
print 'the predict y:',h
plotbestfit(x,y,theta)
这个是logL(似然函数对数值)的曲线图,有点cost function的意思,只不过cost function取最小值,这个是取最大值,平稳了不震荡、不发散,就说明算法正常运行:
这里写图片描述
这个是两个类的分类示意图:
这里写图片描述
这是最后的运算结果,给出了theta值,logL的最终值(最大值),以及新来一个输入X,模型给出的预测值。注意,输入是两个特征x1,x2,这边X=[1,2,9]是三个特征,其中有一个是x0=1。
这里写图片描述
机器学习/逻辑回归(logistic regression)/--附python代码的更多相关文章
- 机器学习(四)--------逻辑回归(Logistic Regression)
逻辑回归(Logistic Regression) 线性回归用来预测,逻辑回归用来分类. 线性回归是拟合函数,逻辑回归是预测函数 逻辑回归就是分类. 分类问题用线性方程是不行的 线性方程拟合的是连 ...
- Coursera公开课笔记: 斯坦福大学机器学习第六课“逻辑回归(Logistic Regression)” 清晰讲解logistic-good!!!!!!
原文:http://52opencourse.com/125/coursera%E5%85%AC%E5%BC%80%E8%AF%BE%E7%AC%94%E8%AE%B0-%E6%96%AF%E5%9D ...
- 机器学习 (三) 逻辑回归 Logistic Regression
文章内容均来自斯坦福大学的Andrew Ng教授讲解的Machine Learning课程,本文是针对该课程的个人学习笔记,如有疏漏,请以原课程所讲述内容为准.感谢博主Rachel Zhang 的个人 ...
- 逻辑回归(Logistic Regression)详解,公式推导及代码实现
逻辑回归(Logistic Regression) 什么是逻辑回归: 逻辑回归(Logistic Regression)是一种基于概率的模式识别算法,虽然名字中带"回归",但实际上 ...
- 机器学习总结之逻辑回归Logistic Regression
机器学习总结之逻辑回归Logistic Regression 逻辑回归logistic regression,虽然名字是回归,但是实际上它是处理分类问题的算法.简单的说回归问题和分类问题如下: 回归问 ...
- 机器学习入门11 - 逻辑回归 (Logistic Regression)
原文链接:https://developers.google.com/machine-learning/crash-course/logistic-regression/ 逻辑回归会生成一个介于 0 ...
- 机器学习方法(五):逻辑回归Logistic Regression,Softmax Regression
欢迎转载,转载请注明:本文出自Bin的专栏blog.csdn.net/xbinworld. 技术交流QQ群:433250724,欢迎对算法.技术.应用感兴趣的同学加入. 前面介绍过线性回归的基本知识, ...
- ML 逻辑回归 Logistic Regression
逻辑回归 Logistic Regression 1 分类 Classification 首先我们来看看使用线性回归来解决分类会出现的问题.下图中,我们加入了一个训练集,产生的新的假设函数使得我们进行 ...
- 【机器学习】Octave 实现逻辑回归 Logistic Regression
ex2data1.txt ex2data2.txt 本次算法的背景是,假如你是一个大学的管理者,你需要根据学生之前的成绩(两门科目)来预测该学生是否能进入该大学. 根据题意,我们不难分辨出这是一种二分 ...
- [笔记]机器学习(Machine Learning) - 02.逻辑回归(Logistic Regression)
逻辑回归算法是分类算法,虽然这个算法的名字中出现了"回归",但逻辑回归算法实际上是一种分类算法,我们将它作为分类算法使用.. 分类问题:对于每个样本,判断它属于N个类中的那个类或哪 ...
随机推荐
- 【luogu P1307 数字反转】 题解
题目链接:https://www.luogu.org/problemnew/show/P1307 刚入门的一道字符串模拟,分四种情况讨论来做比较好. #include<iostream> ...
- centos修改hostname
1.临时修改 hostname localhost 2.永久修改 vim /etc/sysconfig/network 修改hostname的值后保存
- File zilla远程连接服务器报错:服务器发回了不可路由的地址,使用服务器地址代替
百度的答案都是:更改Filezilla设置,编辑-设置-连接-FTP-被动模式,将“使用服务器的外部ip地址来代替”改为“回到主动模式”即可.但问题没有解决!!! 由于使用的是阿里云的服务器.安全组里 ...
- Centos6.9 安装Oracle11gR2
最近在学习怎么安装Centos,在Centos6.9版本安装Oracle数据库.参考了网络上很多文章,终于可以不报错的完成安装了,在这里记录一下 一.需要用到的安装文件 Centos6.9 ps: ...
- vue入门: 实现选中并显示修改功能
1.实现功能 2.工具 vue 3.代码 <!DOCTYPE html> <html lang="en"> <head> <meta ch ...
- react.js中实现tab吸顶效果问题
在react项目开发中有一个需求是,页面滚动到tab所在位置时,tab要固定在顶部. 实现的思路其实很简单,就是判断当滚动距离scrollTop大于tab距离页面顶部距离offsetTop时,将tab ...
- NPM 常见错误
找不到兼容版本 你有一个过时的npm.请更新到最新稳定的npm. 权限错误 npm ERR! code EPERM npm ERR! code EACCES 修复缓存的权限sudo chown -R ...
- chromium之tracked_objects
// For each thread, we have a ThreadData that stores all tracking info generated // on this thread. ...
- Asp.net 自定义CustomerSession 存放到Redis中
首先,引用 Redis 操作驱动组件:StackExchange.Redis.dll. 继承SessionStateStoreProviderBase 类, 实现方法: using System; u ...
- Docker(三):部署软件
Docker的镜像文件可以在镜像仓库中进行搜索. 部署软件目录导航: 常用命令 部署 Tomcat 部署 MySQL 部署 Oracle 常用命令 docker的常用命令如下: docker -v , ...