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 修改文件指定行的方法
May 15 Python
python的迭代器与生成器实例详解
Jul 16 Python
详细介绍Python的鸭子类型
Sep 12 Python
Python cookbook(数据结构与算法)同时对数据做转换和换算处理操作示例
Mar 23 Python
python斐波那契数列的计算方法
Sep 27 Python
python实现简易数码时钟
Feb 19 Python
Python Django实现layui风格+django分页功能的例子
Aug 29 Python
win10下安装Anaconda的教程(python环境+jupyter_notebook)
Oct 23 Python
深入了解如何基于Python读写Kafka
Dec 31 Python
浅谈python多线程和多线程变量共享问题介绍
Apr 17 Python
详解Python yaml模块
Sep 23 Python
Python线程池与GIL全局锁实现抽奖小案例
Apr 13 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输出Excel文件类
2010/02/08 PHP
php中switch与ifelse的效率区别及适用情况分析
2015/02/12 PHP
php7 图形用户界面GUI 开发示例
2020/02/22 PHP
jquery ajax提交表单数据的两种实现方法
2010/04/29 Javascript
jQuery validate 中文API 附validate.js中文api手册
2010/07/31 Javascript
jquery.post用法关于type设置问题补充
2014/01/03 Javascript
Jquery获得控件值的三种方法总结
2014/02/13 Javascript
jQuery瀑布流插件Wookmark使用实例
2014/04/02 Javascript
Javascript中的delete操作符详细介绍
2014/06/06 Javascript
jQuery实现的无限级下拉菜单功能示例
2016/09/12 Javascript
老生常谈Javascript中的原型和this指针
2016/10/09 Javascript
微信小程序开发(一) 微信登录流程详解
2017/01/11 Javascript
js仿京东轮播效果 选项卡套选项卡使用
2017/01/12 Javascript
纯JavaScript实现实时反馈系统时间
2017/10/26 Javascript
详解如何提升JSON.stringify()的性能
2019/06/12 Javascript
JavaScript函数重载操作实例浅析
2020/05/02 Javascript
vue 导航菜单刷新状态不消失,显示对应的路由界面操作
2020/08/06 Javascript
[01:05:40]VG vs Newbee 2018国际邀请赛小组赛BO2 第二场 8.17
2018/08/20 DOTA
python调用cmd命令行制作刷博器
2014/01/13 Python
Python和Perl绘制中国北京跑步地图的方法
2016/03/03 Python
python图像常规操作
2017/11/11 Python
通过Python 接口使用OpenCV的方法
2018/04/02 Python
django 外键model的互相读取方法
2018/12/15 Python
python 有效的括号的实现代码示例
2019/11/11 Python
python实现一个点绕另一个点旋转后的坐标
2019/12/04 Python
Python 改变数组类型为uint8的实现
2020/04/09 Python
python爬虫看看虎牙女主播中谁最“顶”步骤详解
2020/12/01 Python
美国专注于健康商品的网站:eVitamins
2017/01/23 全球购物
巴黎卡诗加拿大官网:Kérastase加拿大
2018/11/12 全球购物
长曲棍球装备:Lacrosse Monkey
2020/12/02 全球购物
大家检讨书5000字
2014/02/03 职场文书
村长贪污检举信
2014/04/04 职场文书
批评与自我批评发言稿
2014/10/15 职场文书
小学教师个人总结
2015/02/05 职场文书
婚育证明样本
2015/06/16 职场文书
大学毕业典礼致辞
2015/07/29 职场文书