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()

效果

更多机器学习代码,请访问 https://github.com/WiseDoge/plume

以上就是python 牛顿法实现逻辑回归(Logistic Regression)的详细内容,更多关于python 逻辑回归的资料请关注我们其它相关文章!

(0)

相关推荐

  • Python利用逻辑回归分类实现模板

    Logistic Regression Classifier逻辑回归主要思想就是用最大似然概率方法构建出方程,为最大化方程,利用牛顿梯度上升求解方程参数. 优点:计算代价不高,易于理解和实现. 缺点:容易欠拟合,分类精度可能不高. 使用数据类型:数值型和标称型数据. 好了,下面开始正文. 算法的思路我就不说了,我就提供一个万能模板,适用于任何纬度数据集. 虽然代码类似于梯度下降,但他是个分类算法 定义sigmoid函数 def sigmoid(x): return 1/(1+np.exp(-x)

  • python代码实现逻辑回归logistic原理

    Logistic Regression Classifier逻辑回归主要思想就是用最大似然概率方法构建出方程,为最大化方程,利用牛顿梯度上升求解方程参数. 优点:计算代价不高,易于理解和实现. 缺点:容易欠拟合,分类精度可能不高. 使用数据类型:数值型和标称型数据. 介绍逻辑回归之前,我们先看一问题,有个黑箱,里面有白球和黑球,如何判断它们的比例. 我们从里面抓3个球,2个黑球,1个白球.这时候,有人就直接得出了黑球67%,白球占比33%.这个时候,其实这个人使用了最大似然概率的思想,通俗来讲,

  • python sklearn库实现简单逻辑回归的实例代码

    Sklearn简介 Scikit-learn(sklearn)是机器学习中常用的第三方模块,对常用的机器学习方法进行了封装,包括回归(Regression).降维(Dimensionality Reduction).分类(Classfication).聚类(Clustering)等方法.当我们面临机器学习问题时,便可根据下图来选择相应的方法. Sklearn具有以下特点: 简单高效的数据挖掘和数据分析工具 让每个人能够在复杂环境中重复使用 建立NumPy.Scipy.MatPlotLib之上 代

  • Python实现的逻辑回归算法示例【附测试csv文件下载】

    本文实例讲述了Python实现的逻辑回归算法.分享给大家供大家参考,具体如下: 使用python实现逻辑回归 Using Python to Implement Logistic Regression Algorithm 菜鸟写的逻辑回归,记录一下学习过程 代码: #encoding:utf-8 """ Author: njulpy Version: 1.0 Data: 2018/04/10 Project: Using Python to Implement Logisti

  • python实现逻辑回归的示例

    代码 import numpy as np import matplotlib.pyplot as plt from sklearn.datasets.samples_generator import make_classification def initialize_params(dims): w = np.zeros((dims, 1)) b = 0 return w, b def sigmoid(x): z = 1 / (1 + np.exp(-x)) return z def logi

  • Python利用逻辑回归模型解决MNIST手写数字识别问题详解

    本文实例讲述了Python利用逻辑回归模型解决MNIST手写数字识别问题.分享给大家供大家参考,具体如下: 1.MNIST手写识别问题 MNIST手写数字识别问题:输入黑白的手写阿拉伯数字,通过机器学习判断输入的是几.可以通过TensorFLow下载MNIST手写数据集,通过import引入MNIST数据集并进行读取,会自动从网上下载所需文件. %matplotlib inline import tensorflow as tf import tensorflow.examples.tutori

  • python编写Logistic逻辑回归

    用一条直线对数据进行拟合的过程称为回归.逻辑回归分类的思想是:根据现有数据对分类边界线建立回归公式. 公式表示为: 一.梯度上升法 每次迭代所有的数据都参与计算. for 循环次数:         训练 代码如下: import numpy as np import matplotlib.pyplot as plt def loadData(): labelVec = [] dataMat = [] with open('testSet.txt') as f: for line in f.re

  • python实现逻辑回归的方法示例

    本文实现的原理很简单,优化方法是用的梯度下降.后面有测试结果. 先来看看实现的示例代码: # coding=utf-8 from math import exp import matplotlib.pyplot as plt import numpy as np from sklearn.datasets.samples_generator import make_blobs def sigmoid(num): ''' :param num: 待计算的x :return: sigmoid之后的数

  • python实现梯度下降和逻辑回归

    本文实例为大家分享了python实现梯度下降和逻辑回归的具体代码,供大家参考,具体内容如下 import numpy as np import pandas as pd import os data = pd.read_csv("iris.csv") # 这里的iris数据已做过处理 m, n = data.shape dataMatIn = np.ones((m, n)) dataMatIn[:, :-1] = data.ix[:, :-1] classLabels = data.i

  • python机器学习理论与实战(四)逻辑回归

    从这节算是开始进入"正规"的机器学习了吧,之所以"正规"因为它开始要建立价值函数(cost function),接着优化价值函数求出权重,然后测试验证.这整套的流程是机器学习必经环节.今天要学习的话题是逻辑回归,逻辑回归也是一种有监督学习方法(supervised machine learning).逻辑回归一般用来做预测,也可以用来做分类,预测是某个类别^.^!线性回归想比大家都不陌生了,y=kx+b,给定一堆数据点,拟合出k和b的值就行了,下次给定X时,就可以计

随机推荐