牛顿法python代码_python 牛顿法实现逻辑回归(Logistic Regression)
本文采用的训练方法是牛顿法(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代码_python 牛顿法实现逻辑回归(Logistic Regression)相关推荐
- OpenCV逻辑回归Logistic Regression的实例(附完整代码)
OpenCV逻辑回归Logistic Regression的实例 OpenCV逻辑回归Logistic Regression的实例 OpenCV逻辑回归Logistic Regression的实例 # ...
- 逻辑回归(Logistic Regression)简介及C++实现
逻辑回归(Logistic Regression):该模型用于分类而非回归,可以使用logistic sigmoid函数( 可参考:http://blog.csdn.net/fengbingchun/ ...
- CS229学习笔记(3)逻辑回归(Logistic Regression)
1.分类问题 你要预测的变量yyy是离散的值,我们将学习一种叫做逻辑回归 (Logistic Regression) 的算法,这是目前最流行使用最广泛的一种学习算法. 从二元的分类问题开始讨论. 我们 ...
- 逻辑回归(Logistic Regression
6.1 分类问题 参考文档: 6 - 1 - Classification (8 min).mkv 在这个以及接下来的几个视频中,开始介绍分类问题. 在分类问题中,你要预测的变量 y y y 是离散的 ...
- 吴恩达机器学习 8.6 逻辑回归(Logistic Regression)
6.1 分类问题 参考文档: 6 - 1 - Classification (8 min).mkv 在这个以及接下来的几个视频中,开始介绍分类问题. 在分类问题中,你要预测的变量 $y$ 是离散的值, ...
- OpenCV3.3中逻辑回归(Logistic Regression)使用举例
OpenCV3.3中给出了逻辑回归(logistic regression)的实现,即cv::ml::LogisticRegression类,类的声明在include/opencv2/ml.hpp文件 ...
- Coursera公开课笔记: 斯坦福大学机器学习第六课“逻辑回归(Logistic Regression)”
Coursera公开课笔记: 斯坦福大学机器学习第六课"逻辑回归(Logistic Regression)" 斯坦福大学机器学习第六课"逻辑回归"学习笔记,本次 ...
- 斯坦福大学机器学习第四课“逻辑回归(Logistic Regression)”
斯坦福大学机器学习第四课"逻辑回归(Logistic Regression)" 本次课程主要包括7部分: 1) Classification(分类) 2) Hypothesis R ...
- 逻辑回归(logistic regression)的本质——极大似然估计
文章目录 1 前言 2 什么是逻辑回归 3 逻辑回归的代价函数 4 利用梯度下降法求参数 5 结束语 6 参考文献 1 前言 逻辑回归是分类当中极为常用的手段,因此,掌握其内在原理是非常必要的.我会争 ...
最新文章
- Django源码分析4:staticfiles静态文件处理中间件分析
- vue 打包上线后字体图标不显示
- 中国速度之二神山建设(3):有力的技术保障,基建世界里的云原生缩影 | IDCF DevOps案例研究...
- 线段树-Count on a Treap-神题
- 前端学习(86):标签嵌套规范
- Graphviz下载 使用
- HTML期末学生大作业-乒乓球网页作业html+css+javascript
- Linux下 RPM 包和Deb包的安装(代码指令+案列)
- mysql数据库sql语法参考_MySQL数据库SQL语法参考
- JavaScript 常用数组函数方法专题
- TG电报telegram群发软件,批量采集群成员、发消息、拉人,全自动营销工具,免费用
- SQL Server 不允许保存更改的解决方法
- 小说平台系统开发(PHP)
- 无线网络的几种认证与加密方式
- 捷普服务器群组防护系统,捷普入侵防御系统
- 戴尔微型计算机进bois,dell进bios按什么键 戴尔进bios的方法
- 万兆以太网选择6类线还是6A类线?
- airpak模拟案例,Airpak模拟教程-体育馆通风模拟案例-CFD数值模拟教程airpak.pdf
- git切换分支、push或pull指定分支
- php的注册头像上传,用Ajax实现注册与头像上传功能
热门文章
- 02ODBC基本概念
- 原创]Windows Gdi入门初级应用(VC SDK)
- 我真out了,高端人士都这样玩儿?
- 知道答案吗?知道为什么是这个答案吗?
- html表单php连接mysql数据库_使用HTML表单和PHP更新MySQL
- mysql my.cnf 配置_MySQL——my.cnf参数设置说明
- code换取微信openid_JSamp;微信_微信授权
- 推荐我们在B站免费的转录组课程
- Ps胶片颗粒效果插件:Imagenomic Realgrain for Mac
- 1.5 编程基础之循环控制 29 数字反转