Logistic回归的牛顿法及DFP、BFGS拟牛顿法求解
牛顿法

# coding:utf-8
import matplotlib.pyplot as plt
import numpy as np def dataN(length):#生成数据
x = np.ones(shape = (length,3))
y = np.zeros(length)
for i in np.arange(0,length/100,0.02):
x[100*i][0]=1
x[100*i][1]=i
x[100*i][2]=i + 1 + np.random.uniform(0,1.2)
y[100*i]=1
x[100*i+1][0]=1
x[100*i+1][1]=i+0.01
x[100*i+1][2]=i+0.01 + np.random.uniform(0,1.2)
y[100*i+1]=0
return x,y def sigmoid(x): #simoid 函数
return 1.0/(1+np.exp(-x)) def DFP(x,y, iter):#DFP拟牛顿法
n = len(x[0])
theta=np.ones((n,1))
y=np.mat(y).T
Gk=np.eye(n,n)
grad_last = np.dot(x.T,sigmoid(np.dot(x,theta))-y)
cost=[]
for it in range(iter):
pk = -1 * Gk.dot(grad_last)
rate=alphA(x,y,theta,pk)
theta = theta + rate * pk
grad= np.dot(x.T,sigmoid(np.dot(x,theta))-y)
delta_k = rate * pk
y_k = (grad - grad_last)
Pk = delta_k.dot(delta_k.T) / (delta_k.T.dot(y_k))
Qk= Gk.dot(y_k).dot(y_k.T).dot(Gk) / (y_k.T.dot(Gk).dot(y_k)) * (-1)
Gk += Pk + Qk
grad_last = grad
cost.append(np.sum(grad_last))
return theta,cost def BFGS(x,y, iter):#BFGS拟牛顿法
n = len(x[0])
theta=np.ones((n,1))
y=np.mat(y).T
Bk=np.eye(n,n)
grad_last = np.dot(x.T,sigmoid(np.dot(x,theta))-y)
cost=[]
for it in range(iter):
pk = -1 * np.linalg.solve(Bk, grad_last)
rate=alphA(x,y,theta,pk)
theta = theta + rate * pk
grad= np.dot(x.T,sigmoid(np.dot(x,theta))-y)
delta_k = rate * pk
y_k = (grad - grad_last)
Pk = y_k.dot(y_k.T) / (y_k.T.dot(delta_k))
Qk= Bk.dot(delta_k).dot(delta_k.T).dot(Bk) / (delta_k.T.dot(Bk).dot(delta_k)) * (-1)
Bk += Pk + Qk
grad_last = grad
cost.append(np.sum(grad_last))
return theta,cost def alphA(x,y,theta,pk): #选取前20次迭代cost最小的alpha
c=float("inf")
t=theta
for k in range(1,200):
a=1.0/k**2
theta = t + a * pk
f= np.sum(np.dot(x.T,sigmoid(np.dot(x,theta))-y))
if abs(f)>c:
break
c=abs(f)
alpha=a
return alpha def newtonMethod(x,y, iter):#牛顿法
m = len(x)
n = len(x[0])
theta = np.zeros(n)
cost=[]
for it in range(iter):
gradientSum = np.zeros(n)
hessianMatSum = np.zeros(shape = (n,n))
for i in range(m):
hypothesis = sigmoid(np.dot(x[i], theta))
loss =hypothesis-y[i]
gradient = loss*x[i]
gradientSum = gradientSum+gradient
hessian=[b*x[i]*(1-hypothesis)*hypothesis for b in x[i]]
hessianMatSum = np.add(hessianMatSum,hessian)
hessianMatInv = np.mat(hessianMatSum).I
for k in range(n):
theta[k] -= np.dot(hessianMatInv[k], gradientSum)
cost.append(np.sum(gradientSum))
return theta,cost def tesT(theta, x, y):#准确率
length=len(x)
count=0
for i in xrange(length):
predict = sigmoid(x[i, :] * np.reshape(theta,(3,1)))[0] > 0.5
if predict == bool(y[i]):
count+= 1
accuracy = float(count)/length
return accuracy def showP(x,y,theta,cost,iter):#作图
plt.figure(1)
plt.plot(range(iter),cost)
plt.figure(2)
color=['or','ob']
for i in xrange(length):
plt.plot(x[i, 1], x[i, 2],color[int(y[i])])
plt.plot([0,length/100],[-theta[0],-theta[0]-theta[1]*length/100]/theta[2])
plt.show()
length=200
iter=5
x,y=dataN(length) theta,cost=BFGS(x,y,iter)
print theta #[[-18.93768161][-16.52178427][ 16.95779981]]
print tesT(theta, np.mat(x), y) #0.935
showP(x,y,theta.getA(),cost,iter) theta,cost=DFP(x,y,iter)
print theta #[[-18.51841028][-16.17880599][ 16.59649161]]
print tesT(theta, np.mat(x), y) #0.935
showP(x,y,theta.getA(),cost,iter) theta,cost=newtonMethod(x,y,iter)
print theta #[-14.49650536 -12.78692552 13.05843361]
print tesT(theta, np.mat(x), y) #0.935
showP(x,y,theta,cost,iter)




Logistic回归的牛顿法及DFP、BFGS拟牛顿法求解的更多相关文章
- 机器学习公开课笔记(3):Logistic回归
Logistic 回归 通常是二元分类器(也可以用于多元分类),例如以下的分类问题 Email: spam / not spam Tumor: Malignant / benign 假设 (Hypot ...
- 机器学习 —— 基础整理(五)线性回归;二项Logistic回归;Softmax回归及其梯度推导;广义线性模型
本文简单整理了以下内容: (一)线性回归 (二)二分类:二项Logistic回归 (三)多分类:Softmax回归 (四)广义线性模型 闲话:二项Logistic回归是我去年入门机器学习时学的第一个模 ...
- 机器学习——logistic回归,鸢尾花数据集预测,数据可视化
0.鸢尾花数据集 鸢尾花数据集作为入门经典数据集.Iris数据集是常用的分类实验数据集,由Fisher, 1936收集整理.Iris也称鸢尾花卉数据集,是一类多重变量分析的数据集.数据集包含150个数 ...
- 【机器学习速成宝典】模型篇03逻辑斯谛回归【Logistic回归】(Python版)
目录 一元线性回归.多元线性回归.Logistic回归.广义线性回归.非线性回归的关系 什么是极大似然估计 逻辑斯谛回归(Logistic回归) 多类分类Logistic回归 Python代码(skl ...
- 【导包】使用Sklearn构建Logistic回归分类器
官方英文文档地址:http://scikit-learn.org/dev/modules/generated/sklearn.linear_model.LogisticRegression.html# ...
- 对线性回归,logistic回归和一般回归的认识
原文:http://www.cnblogs.com/jerrylead/archive/2011/03/05/1971867.html#3281650 对线性回归,logistic回归和一般回归的认识 ...
- 线性回归,logistic回归和一般回归
1 摘要 本报告是在学习斯坦福大学机器学习课程前四节加上配套的讲义后的总结与认识.前四节主要讲述了回归问题,回归属于有监督学习中的一种方法.该方法的核心思想是从连续型统计数据中得到数学模型,然后将该数 ...
- 转载 Deep learning:六(regularized logistic回归练习)
前言: 在上一讲Deep learning:五(regularized线性回归练习)中已经介绍了regularization项在线性回归问题中的应用,这节主要是练习regularization项在lo ...
- 机器学习之线性回归---logistic回归---softmax回归
在本节中,我们介绍Softmax回归模型,该模型是logistic回归模型在多分类问题上的推广,在多分类问题中,类标签 可以取两个以上的值. Softmax回归模型对于诸如MNIST手写数字分类等问题 ...
随机推荐
- c++中,bool与int 的区别
菜鸟一枚,为了观察区别,特地运行了下面几个语句 /*阅读程序回答问题, 1.bool类型的false对应数值?true呢? 2.非0整数对应bool型的?0呢? */ #include<iost ...
- [转]dev C++编写windows程序遇到问题
1.工具-编译选项-编译器-在连接器命令行加入以下命令: -mwindows 2.出现错误:undefined reference to `PlaySoundA@12' 解决办法:工具-编译选项-编译 ...
- (spring-第9回【IoC基础篇】)BeanFactoryPostProcessor,实例化Bean之前的第二大利器
继承结构图如上.在加载XML,注册bean definition之后,在实例化bean definition之前,必要的时候要用到BeanFactoryPostProcessor.它负责把XML中有些 ...
- 转载:node.js socket.io
本文转自:http://www.xiaocai.name/post/cf1f9_7b6507 学习node.js socket.io 使用 用node.js(socket.io)实现数据实时推送 在 ...
- ERP反馈信息管理(十九)
前台显示的界面: <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Custo ...
- 在Azure中的Ubuntu中安装Open edX
最近,由于工作原因,在Azure上的Ubuntu虚拟机中安装了Open edX 实例,安装过程遇到了不少问题, 在从网上找答案的过程中,学习到了不同的知识. 注:若Ubuntu虚拟机Setup在Glo ...
- 重学STM32----(二)
前几天买了个蓝牙模块,昨天到来了,就打算来研究研究蓝牙.看了蓝牙模块的资料,知道通讯需要串口,那肯定要先写一个串口程序了.要是用库函数写,10多分钟可能就会搞定,但是这就违背我的初衷了,所以就不知天高 ...
- Runtime 、 Block
1 使用Block方式,对学生对象进行排序. 1.1 问题 在iOS4.0+ 和Mac OS X 10.6+ 中添加了Block概念,以对C语言进行扩展.在Block中可以定义参数列表.返回类型,还可 ...
- selenium执行js报错
selenium执行js报错 Traceback (most recent call last): dr.execute_script(js) File "C:\Python27\l ...
- Pythono 实现 Permutation
不管在R 还是python中,都有现成的函数来轻而易举地进行全排列(Permutation).无序排列等等.今天想要尝试一下使用自己写代码来实现全排列. 首先,我采用的算法如下: 对于一个数列 i.e ...