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 14 Python
利用Python批量压缩png方法实例(支持过滤个别文件与文件夹)
Jul 30 Python
python中验证码连通域分割的方法详解
Jun 04 Python
使用python实现ftp的文件读写方法
Jul 02 Python
python 的 scapy库,实现网卡收发包的例子
Jul 23 Python
Python学习笔记之For循环用法详解
Aug 14 Python
Python3离线安装Requests模块问题
Oct 13 Python
使用keras内置的模型进行图片预测实例
Jun 17 Python
python能自学吗
Jun 18 Python
Keras SGD 随机梯度下降优化器参数设置方式
Jun 19 Python
Visual Studio code 配置Python开发环境
Sep 11 Python
python 下划线的多种应用场景总结
May 12 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
十大催泪虐心动漫电影,有几部你还没看
2020/03/04 日漫
关于手调机和数调机的选择
2021/03/02 无线电
mysql_fetch_assoc和mysql_fetch_row的功能加起来就是mysql_fetch_array
2007/01/15 PHP
基于jQuery试卷自动排版系统
2010/07/18 Javascript
JavaScript格式化数字的函数代码
2010/11/30 Javascript
JavaScript 代码压缩工具小结
2012/02/27 Javascript
jQuery实现带幻灯的tab滑动切换风格菜单代码
2015/08/27 Javascript
Angularjs中的事件广播 —全面解析$broadcast,$emit,$on
2016/05/17 Javascript
Javascript中的arguments对象
2016/06/20 Javascript
性能优化之代码优化页面加载速度
2017/03/01 Javascript
详解webpack + vue + node 打造单页面(入门篇)
2017/09/23 Javascript
JS实现元素上下左右移动效果
2017/10/18 Javascript
使用Vue自定义数字键盘组件(体验度极好)
2017/12/19 Javascript
React学习笔记之高阶组件应用
2018/06/02 Javascript
js实现文件上传功能 后台使用MultipartFile
2018/09/08 Javascript
VUE前后端学习tab写法实例
2019/08/06 Javascript
Vuex中的Mutations的具体使用方法
2020/06/01 Javascript
详解vue v-model
2020/08/31 Javascript
[01:00:04]DOTA2上海特级锦标赛B组小组赛#1 Alliance VS Spirit第二局
2016/02/26 DOTA
python 解析XML python模块xml.dom解析xml实例代码
2014/02/07 Python
python删除指定类型(或非指定)的文件实例详解
2015/07/06 Python
使用Python向DataFrame中指定位置添加一列或多列的方法
2019/01/29 Python
python导入坐标点的具体操作
2019/05/10 Python
python 怎样将dataframe中的字符串日期转化为日期的方法
2019/09/26 Python
TensorFlow 显存使用机制详解
2020/02/03 Python
Python子进程subpocess原理及用法解析
2020/07/16 Python
Python3以GitHub为例来实现模拟登录和爬取的实例讲解
2020/07/30 Python
python制作微博图片爬取工具
2021/01/16 Python
CSS伪类与CSS伪元素的区别及由来具体说明
2012/12/07 HTML / CSS
HTML5学习笔记之History API
2015/02/26 HTML / CSS
护士自我鉴定范文
2013/10/06 职场文书
医德考评自我评价
2014/09/14 职场文书
2014年中学生检讨书大全
2014/10/09 职场文书
2015安全保卫工作总结
2015/04/25 职场文书
react如何快速设置文件路径别名
2021/04/28 Javascript
解决Laravel使用验证时跳转到首页的问题
2021/11/17 PHP