牛顿法

  # 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拟牛顿法求解的更多相关文章

  1. 机器学习公开课笔记(3):Logistic回归

    Logistic 回归 通常是二元分类器(也可以用于多元分类),例如以下的分类问题 Email: spam / not spam Tumor: Malignant / benign 假设 (Hypot ...

  2. 机器学习 —— 基础整理(五)线性回归;二项Logistic回归;Softmax回归及其梯度推导;广义线性模型

    本文简单整理了以下内容: (一)线性回归 (二)二分类:二项Logistic回归 (三)多分类:Softmax回归 (四)广义线性模型 闲话:二项Logistic回归是我去年入门机器学习时学的第一个模 ...

  3. 机器学习——logistic回归,鸢尾花数据集预测,数据可视化

    0.鸢尾花数据集 鸢尾花数据集作为入门经典数据集.Iris数据集是常用的分类实验数据集,由Fisher, 1936收集整理.Iris也称鸢尾花卉数据集,是一类多重变量分析的数据集.数据集包含150个数 ...

  4. 【机器学习速成宝典】模型篇03逻辑斯谛回归【Logistic回归】(Python版)

    目录 一元线性回归.多元线性回归.Logistic回归.广义线性回归.非线性回归的关系 什么是极大似然估计 逻辑斯谛回归(Logistic回归) 多类分类Logistic回归 Python代码(skl ...

  5. 【导包】使用Sklearn构建Logistic回归分类器

    官方英文文档地址:http://scikit-learn.org/dev/modules/generated/sklearn.linear_model.LogisticRegression.html# ...

  6. 对线性回归,logistic回归和一般回归的认识

    原文:http://www.cnblogs.com/jerrylead/archive/2011/03/05/1971867.html#3281650 对线性回归,logistic回归和一般回归的认识 ...

  7. 线性回归,logistic回归和一般回归

    1 摘要 本报告是在学习斯坦福大学机器学习课程前四节加上配套的讲义后的总结与认识.前四节主要讲述了回归问题,回归属于有监督学习中的一种方法.该方法的核心思想是从连续型统计数据中得到数学模型,然后将该数 ...

  8. 转载 Deep learning:六(regularized logistic回归练习)

    前言: 在上一讲Deep learning:五(regularized线性回归练习)中已经介绍了regularization项在线性回归问题中的应用,这节主要是练习regularization项在lo ...

  9. 机器学习之线性回归---logistic回归---softmax回归

    在本节中,我们介绍Softmax回归模型,该模型是logistic回归模型在多分类问题上的推广,在多分类问题中,类标签 可以取两个以上的值. Softmax回归模型对于诸如MNIST手写数字分类等问题 ...

随机推荐

  1. JS中阻止默认事件与事件冒泡

    JQuery 提供了两种方式来阻止事件冒泡. 方式一:event.stopPropagation(); $("#div1").mousedown(function(event){ ...

  2. 检测INT3 软断点

    “INT3”断点指令的机器码是 “0xcch” 检测思路,取函数地址,判断第一个字节是不是 “CCh” BYTE bFirst = ; ProcAddres = GetProcAddress(Load ...

  3. hdu 2054

    Ps:WA了无数次,,简直成了心病..今天终于AC了..先取整数部分,去零,判断位数相等否,再比较.如果相等,再取小数部分,去零,比较,输出....好烦... 代码; #include "s ...

  4. Chapter 1: A Simple Web Server

    这算是一篇读书笔记,留着以后复习看看. Web Server又称为Http Server,因为它使用HTTP协议和客户端(一般是各种各样的浏览器)进行通信. 什么是HTTP协议呢? HTTP协议是基于 ...

  5. OpenSesame:一个能够攻击fixed-pin设备的工具

    OpenSesame是一种设备,这种设备可以通过无线技术来打开任何一个设有固定密码的车库门,我从中发现了一个攻击无线固定pin码设备的新方法. 演示视频以及详细信息: opensesame源代码:ht ...

  6. Objective-C determine data network type of the iOS device

    Im on an application that receive data from server, the problem is when user connect to cellular dat ...

  7. HDU 4160

    http://acm.hdu.edu.cn/showproblem.php?pid=4160 大娃娃可以套在小娃娃外面(各边严格小),问最后最少得到几个娃娃 题目中的娃娃可以看做点,嵌套关系可以看做有 ...

  8. 简单的IOS6和IOS7通过图片名适配

    在美工提供图片图片的前提下,只需要下面给UIImage做一个分类,就可以简单的实现在6和7上的图片名字适配. 比如美工在6上面提供的图片叫common_button_big_red_highlight ...

  9. I.MX6 mfgtool2-android-mx6q-sabresd-emmc.vbs hacking

    /******************************************************************** * I.MX6 mfgtool2-android-mx6q- ...

  10. HTML-day-1-HTML基础知识

    HTML基础知识 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://ww ...