本文采用的训练方法是牛顿法(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)的详细内容,更多关于python 逻辑回归的资料请关注脚本之家其它相关文章!

python pandas库实现逻辑回归拟牛顿法求参数_python 牛顿法实现逻辑回归(Logistic Regression)...相关推荐

  1. python pandas库读取excel/csv中指定行或列数据详解

    通过阅读表格,可以发现Pandas中提供了非常丰富的数据读写方法,下面这篇文章主要给大家介绍了关于python利用pandas库读取excel/csv中指定行或列数据的相关资料,需要的朋友可以参考下 ...

  2. python pandas库——pivot使用心得

    python pandas库--pivot使用心得 2017年12月14日 17:07:06 阅读数:364 最近在做基于python的数据分析工作,引用第三方数据分析库--pandas(versio ...

  3. Python pandas库|任凭弱水三千,我只取一瓢饮(5)

    上一篇链接: Python pandas库|任凭弱水三千,我只取一瓢饮(4)_Hann Yang的博客-CSDN博客 S~W:  Function46~56 Types['Function'][45: ...

  4. Python pandas库|任凭弱水三千,我只取一瓢饮(4)

    上一篇链接: Python pandas库|任凭弱水三千,我只取一瓢饮(3)_Hann Yang的博客-CSDN博客  R(read_系列2):  Function36~45 Types['Funct ...

  5. Python pandas库|任凭弱水三千,我只取一瓢饮(7)

    上一篇链接: Python pandas库|任凭弱水三千,我只取一瓢饮(6)_Hann Yang的博客-CSDN博客 to_系列函数:22个 (12~22) Function12 to_numpy(s ...

  6. Python pandas库|任凭弱水三千,我只取一瓢饮(6)

    上一篇链接: Python pandas库|任凭弱水三千,我只取一瓢饮(5)_Hann Yang的博客-CSDN博客 DataFrame 类方法(211个,其中包含18个子类.2个子模块) >& ...

  7. Python pandas库|任凭弱水三千,我只取一瓢饮(1)

    对Python的 pandas 库所有的内置元类.函数.子模块等全部浏览一遍,然后挑选一些重点学习一下.我安装的库版本号为1.3.5,如下: >>> import pandas as ...

  8. Python pandas库|任凭弱水三千,我只取一瓢饮(3)

    上一篇链接: Python pandas库|任凭弱水三千,我只取一瓢饮(2)_Hann Yang的博客-CSDN博客 R(read_系列1):  Function26~35 Types['Functi ...

  9. Python pandas库|任凭弱水三千,我只取一瓢饮(2)

    上一篇链接: Python pandas库|任凭弱水三千,我只取一瓢饮(2)_Hann Yang的博客-CSDN博客 I~Q:  Function10~25 Types['Function'][9:2 ...

最新文章

  1. Android 数字签名学习笔记
  2. Swift: 可变参数
  3. 第一个WindowService服务
  4. tomcat 虚拟路径 与 虚拟主机配置
  5. 再见,Spark!Flink已成气候!
  6. python樱花树代码_【推荐】手把手教你如何用Python画一棵漂亮樱花树含源码
  7. ThreadLocal可以解决并发问题吗?
  8. 【CUDA学习】计时方法
  9. Unity3D 怎样在安卓手机上播放视频
  10. vue-cli2.0webpack的理解
  11. 三维点云数据处理软件供技术原理说明_十大点云数据处理技术梳理
  12. 网络安全渗透测试自学
  13. 卷积码编码器matlab,卷积码的编解码matlab仿真.doc
  14. SPSS独立样本t检验结果分析
  15. Python爬取百度文库的内容输出
  16. 5G/NR/LTE: CQI MCS SNR UE NB 之间的关系梳理
  17. Buoyant的Conduit服务网格正式成为Linkerd 2
  18. OSPF -LSA的类型及特点
  19. 使用GDI/GDI+绘制到D3D9缓冲区的方法
  20. 在线预览 Word、Excel、PowerPoint 文档——Office Online插件使用

热门文章

  1. 如何测量代码执行时间
  2. 机器学习导论(张志华):渐近性质
  3. liblbfgs简介
  4. CUDA性能优化----线程配置
  5. C/C++常见库函数实现(memcpy、memset、 strcpy)
  6. 【云炬大学生创业基础笔记】第1章第1节 测试
  7. 专栏 | 基于 Jupyter 的特征工程手册:特征选择(二)
  8. 解决jquery的多次绑定事件
  9. OpenGL从入门到精通--着色器的使用
  10. Java中this的简单应用