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算法学习之计数排序实例
Dec 18 Python
Python比较两个图片相似度的方法
Mar 13 Python
对Python新手编程过程中如何规避一些常见问题的建议
Apr 01 Python
Python中的字符串查找操作方法总结
Jun 27 Python
python 利用文件锁单例执行脚本的方法
Feb 19 Python
python 实现返回一个列表中出现次数最多的元素方法
Jun 11 Python
pyinstaller打包opencv和numpy程序运行错误解决
Aug 16 Python
Python如何省略括号方法详解
Mar 21 Python
Pyspark读取parquet数据过程解析
Mar 27 Python
解决django FileFIELD的编码问题
Mar 30 Python
Python GUI编程学习笔记之tkinter控件的介绍及基本使用方法详解
Mar 30 Python
python判断all函数输出结果是否为true的方法
Dec 03 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
UCenter中的一个可逆加密函数authcode函数代码
2010/07/20 PHP
php根据地址获取百度地图经纬度的实例方法
2019/09/03 PHP
一个简单的JavaScript数据缓存系统实现代码
2010/10/24 Javascript
multiSteps 基于Jquery的多步骤滑动切换插件
2011/07/22 Javascript
JavaScript中操作Mysql数据库实例
2015/04/02 Javascript
Javascript实现div的toggle效果实例分析
2015/06/09 Javascript
jQuery实现彩带延伸效果的网页加载条loading动画
2015/10/29 Javascript
javascript 中的try catch应用总结
2017/04/01 Javascript
JavaScript设计模式---单例模式详解【四种基本形式】
2020/05/16 Javascript
JavaScript 防抖和节流遇见的奇怪问题及解决
2020/11/20 Javascript
[03:10]2014DOTA2 TI马来劲旅Titan首战告捷目标只是8强
2014/07/10 DOTA
Python实现统计文本文件字数的方法
2017/05/05 Python
Python3.5 处理文本txt,删除不需要的行方法
2018/12/10 Python
利用python开发app实战的方法
2019/07/09 Python
python datetime中strptime用法详解
2019/08/29 Python
python使用yield压平嵌套字典的超简单方法
2019/11/02 Python
Pytorch DataLoader 变长数据处理方式
2020/01/08 Python
Python3 socket即时通讯脚本实现代码实例(threading多线程)
2020/06/01 Python
pycharm全局搜索的具体步骤
2020/07/28 Python
Python爬虫爬取糗事百科段子实例分享
2020/07/31 Python
Python爬虫之Spider类用法简单介绍
2020/08/04 Python
MoviePy简介及Python视频剪辑自动化
2020/12/18 Python
物流专业大学生求职信范文
2013/10/28 职场文书
幼儿园五一活动方案
2014/02/07 职场文书
消防应急演练方案
2014/02/12 职场文书
工程质量月活动方案
2014/02/19 职场文书
总经理秘书岗位职责
2014/03/17 职场文书
奥巴马的演讲稿
2014/05/15 职场文书
我的中国梦演讲稿小学篇
2014/08/19 职场文书
法人委托书范本格式
2014/09/15 职场文书
儿园租房协议书范本
2014/12/02 职场文书
服务明星事迹材料
2014/12/29 职场文书
Java 在生活中的 10 大应用
2021/11/02 Java/Android
世界十大儿童漫画书排名,法国国宝漫画排第五,第二是轰动日本连环
2022/03/18 欧美动漫
SQL SERVER中的流程控制语句
2022/05/25 SQL Server
Windows Server 2012 R2服务器安装与配置的完整步骤
2022/07/15 Servers