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 获取新浪微博的最新公共微博实例分享
Jul 03 Python
python关闭windows进程的方法
Apr 18 Python
详解Python中expandtabs()方法的使用
May 18 Python
解决python3 urllib中urlopen报错的问题
Mar 25 Python
Python基础知识_浅谈用户交互
May 31 Python
django rest framework 数据的查找、过滤、排序的示例
Jun 25 Python
python调用百度语音识别实现大音频文件语音识别功能
Aug 30 Python
Python实现字符串匹配的KMP算法
Apr 04 Python
pyqt5 tablewidget 利用线程动态刷新数据的方法
Jun 17 Python
python调用接口的4种方式代码实例
Nov 19 Python
利用python实现后端写网页(flask框架)
Feb 28 Python
Python selenium的这三种等待方式一定要会!
Jun 10 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 判断访客是否为搜索引擎蜘蛛的函数代码
2011/07/29 PHP
php 获取页面中指定内容的实现类
2014/01/23 PHP
用Laravel Sms实现laravel短信验证码的发送的实现
2018/11/29 PHP
PHP+Redis链表解决高并发下商品超卖问题(实现原理及步骤)
2020/08/03 PHP
关于Blog顶部的滚动导航条代码
2006/09/25 Javascript
JS解析json数据并将json字符串转化为数组的实现方法
2012/12/25 Javascript
用Javascript来生成ftp脚本的小例子
2013/07/03 Javascript
js实现网页自动刷新可制作节日倒计时效果
2014/05/27 Javascript
基于JSON格式数据的简单jQuery幻灯片插件(jquery-slider)
2016/08/10 Javascript
nodejs6下使用koa2框架实例
2017/05/18 NodeJs
js禁止浏览器页面后退功能的实例(推荐)
2017/09/01 Javascript
JS正则表达式完美实现身份证校验功能
2017/10/18 Javascript
基于node.js实现微信支付退款功能
2017/12/19 Javascript
js数组去重的N种方法(小结)
2018/06/07 Javascript
js 计算月/周的第一天和最后一天代码
2020/02/01 Javascript
jQuery单页面文字搜索插件jquery.fullsearch.js的使用方法
2020/02/04 jQuery
JS Thunk 函数的含义和用法实例总结
2020/04/08 Javascript
[00:56]跨越时空加入战场 全新祈求者身心“失落奇艺侍祭”展示
2019/07/20 DOTA
matplotlib绘制动画代码示例
2018/01/02 Python
Django中日期处理注意事项与自定义时间格式转换详解
2018/08/06 Python
python2.7实现邮件发送功能
2018/12/12 Python
Python面向对象之类和实例用法分析
2019/06/08 Python
python GUI库图形界面开发之PyQt5复选框控件QCheckBox详细使用方法与实例
2020/02/28 Python
Python如何将函数值赋给变量
2020/04/28 Python
日本著名化妆品零售网站:Cosme Land
2019/03/01 全球购物
银行实习人员自我鉴定
2013/09/22 职场文书
2013年保送生自荐信格式
2013/11/20 职场文书
预备党员转正思想汇报
2014/01/12 职场文书
寄语十八大感言
2014/02/07 职场文书
触电现场处置方案
2014/05/14 职场文书
幸福家庭事迹材料
2014/12/20 职场文书
幼儿教师师德师风自我评价
2015/03/05 职场文书
大学生求职意向书
2015/05/11 职场文书
浅谈Redis主从复制以及主从复制原理
2021/05/29 Redis
Python探索生命起源 matplotlib细胞自动机动画演示
2022/04/21 Python
python标准库ElementTree处理xml
2022/05/20 Python