python 牛顿法实现逻辑回归(Logistic Regression)


Posted in Python onOctober 15, 2020

本文采用的训练方法是牛顿法(Newton Method)。

代码

import numpy as np

class LogisticRegression(object):
 """
 Logistic Regression Classifier training by Newton Method
 """

 def __init__(self, error: float = 0.7, max_epoch: int = 100):
  """
  :param error: float, if the distance between new weight and 
      old weight is less than error, the process 
      of traing will break.
  :param max_epoch: if training epoch >= max_epoch the process 
       of traing will break.
  """
  self.error = error
  self.max_epoch = max_epoch
  self.weight = None
  self.sign = np.vectorize(lambda x: 1 if x >= 0.5 else 0)

 def p_func(self, X_):
  """Get P(y=1 | x)
  :param X_: shape = (n_samples + 1, n_features)
  :return: shape = (n_samples)
  """
  tmp = np.exp(self.weight @ X_.T)
  return tmp / (1 + tmp)

 def diff(self, X_, y, p):
  """Get derivative
  :param X_: shape = (n_samples, n_features + 1) 
  :param y: shape = (n_samples)
  :param p: shape = (n_samples) P(y=1 | x)
  :return: shape = (n_features + 1) first derivative
  """
  return -(y - p) @ X_

 def hess_mat(self, X_, p):
  """Get Hessian Matrix
  :param p: shape = (n_samples) P(y=1 | x)
  :return: shape = (n_features + 1, n_features + 1) second derivative
  """
  hess = np.zeros((X_.shape[1], X_.shape[1]))
  for i in range(X_.shape[0]):
   hess += self.X_XT[i] * p[i] * (1 - p[i])
  return hess

 def newton_method(self, X_, y):
  """Newton Method to calculate weight
  :param X_: shape = (n_samples + 1, n_features)
  :param y: shape = (n_samples)
  :return: None
  """
  self.weight = np.ones(X_.shape[1])
  self.X_XT = []
  for i in range(X_.shape[0]):
   t = X_[i, :].reshape((-1, 1))
   self.X_XT.append(t @ t.T)

  for _ in range(self.max_epoch):
   p = self.p_func(X_)
   diff = self.diff(X_, y, p)
   hess = self.hess_mat(X_, p)
   new_weight = self.weight - (np.linalg.inv(hess) @ diff.reshape((-1, 1))).flatten()

   if np.linalg.norm(new_weight - self.weight) <= self.error:
    break
   self.weight = new_weight

 def fit(self, X, y):
  """
  :param X_: shape = (n_samples, n_features)
  :param y: shape = (n_samples)
  :return: self
  """
  X_ = np.c_[np.ones(X.shape[0]), X]
  self.newton_method(X_, y)
  return self

 def predict(self, X) -> np.array:
  """
  :param X: shape = (n_samples, n_features] 
  :return: shape = (n_samples]
  """
  X_ = np.c_[np.ones(X.shape[0]), X]
  return self.sign(self.p_func(X_))

测试代码

import matplotlib.pyplot as plt
import sklearn.datasets

def plot_decision_boundary(pred_func, X, y, title=None):
 """分类器画图函数,可画出样本点和决策边界
 :param pred_func: predict函数
 :param X: 训练集X
 :param y: 训练集Y
 :return: None
 """

 # Set min and max values and give it some padding
 x_min, x_max = X[:, 0].min() - .5, X[:, 0].max() + .5
 y_min, y_max = X[:, 1].min() - .5, X[:, 1].max() + .5
 h = 0.01
 # Generate a grid of points with distance h between them
 xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h))
 # Predict the function value for the whole gid
 Z = pred_func(np.c_[xx.ravel(), yy.ravel()])
 Z = Z.reshape(xx.shape)
 # Plot the contour and training examples
 plt.contourf(xx, yy, Z, cmap=plt.cm.Spectral)
 plt.scatter(X[:, 0], X[:, 1], s=40, c=y, cmap=plt.cm.Spectral)
 if title:
  plt.title(title)
 plt.show()

效果

python 牛顿法实现逻辑回归(Logistic Regression)

更多机器学习代码,请访问 https://github.com/WiseDoge/plume

以上就是python 牛顿法实现逻辑回归(Logistic Regression)的详细内容,更多关于python 逻辑回归的资料请关注三水点靠木其它相关文章!

Python 相关文章推荐
Python中使用glob和rmtree删除目录子目录及所有文件的例子
Nov 21 Python
python实现实时监控文件的方法
Aug 26 Python
python利用sklearn包编写决策树源代码
Dec 21 Python
利用Python如何实现数据驱动的接口自动化测试
May 11 Python
Python格式化输出字符串方法小结【%与format】
Oct 29 Python
Django中Middleware中的函数详解
Jul 18 Python
Python time库基本使用方法分析
Dec 13 Python
pycharm双击无响应(打不开问题解决办法)
Jan 10 Python
python中使用paramiko模块并实现远程连接服务器执行上传下载功能
Feb 29 Python
Python中如何添加自定义模块
Jun 09 Python
Python为何不支持switch语句原理详解
Oct 21 Python
解决virtualenv -p python3 venv报错的问题
Feb 05 Python
PyCharm 2020.2.2 x64 下载并安装的详细教程
Oct 15 #Python
Python 实现3种回归模型(Linear Regression,Lasso,Ridge)的示例
Oct 15 #Python
Python在centos7.6上安装python3.9的详细教程(默认python版本为2.7.5)
Oct 15 #Python
Pycharm编辑器功能之代码折叠效果的实现代码
Oct 15 #Python
如何用Python 实现全连接神经网络(Multi-layer Perceptron)
Oct 15 #Python
python 实现非极大值抑制算法(Non-maximum suppression, NMS)
Oct 15 #Python
解决pip安装的第三方包在PyCharm无法导入的问题
Oct 15 #Python
You might like
PHP图片验证码制作实现分享(全)
2012/05/10 PHP
基于wordpress主题制作的具体实现步骤
2013/05/10 PHP
WordPress自定义时间显示格式
2015/03/27 PHP
PHP共享内存用法实例分析
2016/02/12 PHP
php数值转换时间及时间转换数值用法示例
2017/05/18 PHP
如何在MVC应用程序中使用Jquery
2014/11/17 Javascript
JavaScript常用验证函数实例汇总
2014/11/25 Javascript
JavaScript中诡异的delete操作符
2015/03/12 Javascript
配置Grunt的Task时通配符支持和动态生成文件名问题
2015/09/06 Javascript
封装好的javascript前端分页插件pagination
2016/01/04 Javascript
JavaScript基础教程——入门必看篇
2016/05/20 Javascript
jQuery数据检索中根据关键字快速定位GridView指定行的实现方法
2016/06/08 Javascript
从零开始学习搭建React脚手架项目
2018/08/23 Javascript
vue路由--网站导航功能详解
2019/03/29 Javascript
基于layPage插件实现两种分页方式浅析
2019/07/27 Javascript
Vue.js中的高级面试题及答案
2020/01/13 Javascript
解决Vue-cli3没有vue.config.js文件夹及配置vue项目域名的问题
2020/12/04 Vue.js
[50:45]2018DOTA2亚洲邀请赛 4.6 淘汰赛 VP vs TNC 第一场
2018/04/10 DOTA
[49:28]VP vs Optic 2018国际邀请赛小组赛BO2 第二场 8.16
2018/08/17 DOTA
Python 制作糗事百科爬虫实例
2016/09/22 Python
python实现八大排序算法(1)
2017/09/14 Python
Python中list查询及所需时间计算操作示例
2018/06/21 Python
对Xpath 获取子标签下所有文本的方法详解
2019/01/02 Python
详解python中的time和datetime的常用方法
2019/07/08 Python
详解解决Python memory error的问题(四种解决方案)
2019/08/08 Python
Python基于requests库爬取网站信息
2020/03/02 Python
Django 再谈一谈json序列化
2020/03/16 Python
Python 中如何写注释
2020/08/28 Python
YOOX台湾:意大利奢侈品电商
2018/10/13 全球购物
建筑设计师岗位职责
2013/11/18 职场文书
简历中个人求职的自我评价模板
2013/11/29 职场文书
事业单位辞职信范文
2014/01/19 职场文书
重阳节登山活动方案
2014/02/03 职场文书
教师自我剖析材料(群众路线)
2014/09/29 职场文书
2015年中秋节活动总结
2015/03/23 职场文书
golang 如何通过反射创建新对象
2021/04/28 Golang