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中的函数用法入门教程
Sep 02 Python
让python在hadoop上跑起来
Jan 27 Python
带你了解python装饰器
Jun 15 Python
Python 循环语句之 while,for语句详解
Apr 23 Python
flask入门之文件上传与邮件发送示例
Jul 18 Python
Python反射和内置方法重写操作详解
Aug 27 Python
python使用正则筛选信用卡
Jan 27 Python
对Python 检查文件名是否规范的实例详解
Jun 10 Python
Python 中如何实现参数化测试的方法示例
Dec 10 Python
jupyter 实现notebook中显示完整的行和列
Apr 09 Python
PyQt5爬取12306车票信息程序的实现
May 14 Python
python自动化测试通过日志3分钟定位bug
Nov 20 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
解决文件名解压后乱码的问题 将文件名进行转码的代码
2012/01/10 PHP
MacOS下PHP7.1升级到PHP7.4.15的方法
2021/02/22 PHP
用javascript实现读取txt文档的脚本
2007/07/20 Javascript
JavaScript Sort 表格排序
2009/10/31 Javascript
3种不同方式的焦点图轮播特效分享
2013/10/30 Javascript
jQuery学习笔记之 Ajax操作篇(一) - 数据加载
2014/06/23 Javascript
javascript实现控制文字大中小显示
2015/04/28 Javascript
jQuery实现仿腾讯微博滑出效果报告每日天气的方法
2015/05/11 Javascript
jQuery zclip插件实现跨浏览器复制功能
2015/11/02 Javascript
Javascript如何判断数据类型和数组类型
2016/06/22 Javascript
js实现增加数字显示的环形进度条效果
2017/02/05 Javascript
Vue.directive自定义指令的使用详解
2017/03/10 Javascript
在vue中安装使用vux的教程详解
2018/09/16 Javascript
Vue中的$set的使用实例代码
2018/10/08 Javascript
如何手动实现es5中的bind方法详解
2018/12/07 Javascript
通过实例学习React中事件节流防抖
2019/06/17 Javascript
Vue.js如何使用Socket.IO的示例代码
2019/09/05 Javascript
Javascript Dom元素获取和添加详解
2019/09/24 Javascript
[03:37]2016完美“圣”典 风云人物:Mikasa专访
2016/12/07 DOTA
python实现RSA加密(解密)算法
2016/02/17 Python
树莓派安装OpenCV3完整过程的实现
2019/10/10 Python
pandas数据拼接的实现示例
2020/04/16 Python
PyPDF2读取PDF文件内容保存到本地TXT实例
2020/05/12 Python
使用pyecharts1.7进行简单的可视化大全
2020/05/17 Python
html5的画布canvas——画出简单的矩形、三角形实例代码
2013/06/09 HTML / CSS
基于HTML5新特性Mutation Observer实现编辑器的撤销和回退操作
2016/01/11 HTML / CSS
html5 canvas的绘制文本自动换行的示例代码
2018/09/17 HTML / CSS
印尼极简主义和实惠的在线家具店:Fabelio
2019/03/27 全球购物
中文师范生自荐信
2014/01/30 职场文书
小学教师师德感言
2014/02/10 职场文书
《千年梦圆在今朝》教学反思
2014/02/24 职场文书
六一亲子活动总结
2014/07/01 职场文书
园艺专业毕业生求职信
2014/09/02 职场文书
大学生英文求职信范文
2015/03/19 职场文书
初中团支书竞选稿
2015/11/21 职场文书
如何理解Vue简单状态管理之store模式
2021/05/15 Vue.js