python实现逻辑回归
首先得明确逻辑回归与线性回归不同,它是一种分类模型。而且是一种二分类模型。
首先我们需要知道sigmoid函数,其公式表达如下:

其函数曲线如下:

sigmoid函数有什么性质呢?
1、关于(0,0.5) 对称
2、值域范围在(0,1)之间
3、单调递增
4、光滑
5、中间较陡,两侧较平缓
6、其导数为g(z)(1-g(z)),即可以用原函数直接计算
于是逻辑回归的函数形式可以用以下公式表示:

其中θ表示权重参数,x表示输入。θTx为决策边界,就是该决策边界将不同类数据区分开来。
为什么使用sigmoid函数呢?
1、sigmoid函数本身的性质
2、推导而来
我们知道伯努利分布:

当x=1时,f(1|p) =p,当x=0时,f(0|p)=1-p
首先要明确伯努利分布也是指数族,指数族的一般表达式为:

由于:

则有:

所以:

因为:
则有:

逻辑回归代价函数:

为什么这么定义呢?
以单个样本为例:

上面式子等价于:

当y=1时,其图像如下:

也就是说当hθ(x)的值越接近1,C(θ) 的值就越小。
同理当y=0时,其图像如下:

也就是说当hθ(x)的值越接近0,C(θ) 的值就越小。
这样就可以将不同类区分开来。
代价函数的倒数如下:

推导过程如下:


上面参考了:
https://blog.csdn.net/sun_wangdong/article/details/80780368
https://zhuanlan.zhihu.com/p/28415991
接下来就是代码实现了,代码来源: https://github.com/eriklindernoren/ML-From-Scratch
from __future__ import print_function, division
import numpy as np
import math
from mlfromscratch.utils import make_diagonal, Plot
from mlfromscratch.deep_learning.activation_functions import Sigmoid class LogisticRegression():
""" Logistic Regression classifier.
Parameters:
-----------
learning_rate: float
The step length that will be taken when following the negative gradient during
training.
gradient_descent: boolean
True or false depending if gradient descent should be used when training. If
false then we use batch optimization by least squares.
"""
def __init__(self, learning_rate=.1, gradient_descent=True):
self.param = None
self.learning_rate = learning_rate
self.gradient_descent = gradient_descent
self.sigmoid = Sigmoid() def _initialize_parameters(self, X):
n_features = np.shape(X)[1]
# Initialize parameters between [-1/sqrt(N), 1/sqrt(N)]
limit = 1 / math.sqrt(n_features)
self.param = np.random.uniform(-limit, limit, (n_features,)) def fit(self, X, y, n_iterations=4000):
self._initialize_parameters(X)
# Tune parameters for n iterations
for i in range(n_iterations):
# Make a new prediction
y_pred = self.sigmoid(X.dot(self.param))
if self.gradient_descent:
# Move against the gradient of the loss function with
# respect to the parameters to minimize the loss
self.param -= self.learning_rate * -(y - y_pred).dot(X)
else:
# Make a diagonal matrix of the sigmoid gradient column vector
diag_gradient = make_diagonal(self.sigmoid.gradient(X.dot(self.param)))
# Batch opt:
self.param = np.linalg.pinv(X.T.dot(diag_gradient).dot(X)).dot(X.T).dot(diag_gradient.dot(X).dot(self.param) + y - y_pred) def predict(self, X):
y_pred = np.round(self.sigmoid(X.dot(self.param))).astype(int)
return y_pred
说明:np.linalg.pinv()用于计算矩阵的pseudo-inverse(伪逆)。第一种方法求解使用随机梯度下降。
其中make_diagonal()函数如下:用于将向量转换为对角矩阵
def make_diagonal(x):
""" Converts a vector into an diagonal matrix """
m = np.zeros((len(x), len(x)))
for i in range(len(m[0])):
m[i, i] = x[i]
return m
其中Sigmoid代码如下:
class Sigmoid():
def __call__(self, x):
return 1 / (1 + np.exp(-x)) def gradient(self, x):
return self.__call__(x) * (1 - self.__call__(x))
最后是主函数运行代码:
from __future__ import print_function
from sklearn import datasets
import numpy as np
import matplotlib.pyplot as plt # Import helper functions
import sys
sys.path.append("/content/drive/My Drive/learn/ML-From-Scratch/")
from mlfromscratch.utils import make_diagonal, normalize, train_test_split, accuracy_score
from mlfromscratch.deep_learning.activation_functions import Sigmoid
from mlfromscratch.utils import Plot
from mlfromscratch.supervised_learning import LogisticRegression def main():
# Load dataset
data = datasets.load_iris()
X = normalize(data.data[data.target != 0])
y = data.target[data.target != 0]
y[y == 1] = 0
y[y == 2] = 1 X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33, seed=1) clf = LogisticRegression(gradient_descent=True)
clf.fit(X_train, y_train)
y_pred = clf.predict(X_test) accuracy = accuracy_score(y_test, y_pred)
print ("Accuracy:", accuracy) # Reduce dimension to two using PCA and plot the results
Plot().plot_in_2d(X_test, y_pred, title="Logistic Regression", accuracy=accuracy) if __name__ == "__main__":
main()
结果:
Accuracy: 0.9393939393939394

python实现逻辑回归的更多相关文章
- 机器学习_线性回归和逻辑回归_案例实战:Python实现逻辑回归与梯度下降策略_项目实战:使用逻辑回归判断信用卡欺诈检测
线性回归: 注:为偏置项,这一项的x的值假设为[1,1,1,1,1....] 注:为使似然函数越大,则需要最小二乘法函数越小越好 线性回归中为什么选用平方和作为误差函数?假设模型结果与测量值 误差满足 ...
- 机器学习之使用Python完成逻辑回归
一.任务基础 我们将建立一个逻辑回归模型来预测一个学生是否被大学录取.假设你是一个大学系的管理员,你想根据两次考试的结果来决定每个申请人的录取机会.你有以前的申请人的历史数据,你可以用它作为逻辑回归的 ...
- 吴裕雄 python 机器学习——逻辑回归
import numpy as np import matplotlib.pyplot as plt from matplotlib import cm from mpl_toolkits.mplot ...
- Python之逻辑回归模型来预测
建立一个逻辑回归模型来预测一个学生是否被录取. import numpy as np import pandas as pd import matplotlib.pyplot as plt impor ...
- python机器学习-逻辑回归
1.逻辑函数 假设数据集有n个独立的特征,x1到xn为样本的n个特征.常规的回归算法的目标是拟合出一个多项式函数,使得预测值与真实值的误差最小: 而我们希望这样的f(x)能够具有很好的逻辑判断性质,最 ...
- python机器学习——逻辑回归
我们知道感知器算法对于不能完全线性分割的数据是无能为力的,在这一篇将会介绍另一种非常有效的二分类模型--逻辑回归.在分类任务中,它被广泛使用 逻辑回归是一个分类模型,在实现之前我们先介绍几个概念: 几 ...
- Python使用逻辑回归估算OR值
第一种是统计学方法,需要用到 statsmodels包 statsmodels是统计和计量经济学的package,包含了用于参数评估和统计测试的实用工具 第二种是机器学习,需要使用sklearn中的L ...
- 用python实现逻辑回归
机器学习课程的一个实验,整理出来共享. 原理很简单,优化方法是用的梯度下降.后面有测试结果. # coding=utf-8 from math import exp import matplotlib ...
- Python之逻辑回归
代码: import numpy as np from sklearn import datasets from sklearn.linear_model import LogisticRegress ...
随机推荐
- Java并发基础07. ThreadLocal类以及应用技巧
在前面的文章(6. 线程范围内共享数据)总结了一下,线程范围内的数据共享问题,即定义一个 Map,将当前线程名称和线程中的数据以键值对的形式存到 Map 中,然后在当前线程中使用数据的时候就可以根据当 ...
- Qt实现学生学籍管理系统(文件存储)
记录 19:53 2019-07-30 在小学期学c++做完课设后萌生了把写完的课设放在博客上的想法,于是,我第一篇博客诞生了. 22:32:19 2019-07-30 下棋 16:04:56 201 ...
- Spring Web Flow 笔记
在Spring 中配置 Web Flow <?xml version="1.0" encoding="UTF-8"?> <beans xmln ...
- Linux系统安装java jdk
1)下载地址: https://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html 我这里下载的是 ...
- php--php设计模式留存
装饰者模式 <?php interface Decorator { public function display(); } class XiaoFang implements Decorato ...
- C语言学生管理系统(C语言课程设计/精简版)
#include<stdio.h>#include<stdlib.h>#include<windows.h>#include<conio.h>typed ...
- 31 Exception 异常处理
/* * Exception in thread "main" java.lang.ArithmeticException: / by zero at com.itheima_01 ...
- 从谷歌面试翻车到offer收割的心路历程
首先声明,这只是我的播客随感,其中无法避免有一些个人色彩的见解,请不要在意,我尊敬任何的互联网公司,尊敬研究生期间的老师同学,我只希望给在求学路上的CS同学一些启发. 先介绍一下背景,我是ACM铜牌退 ...
- 表字段或表名出现Mysql关键字或保留字导致问题 Cause: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have
MySQL 5.7使用的关键字和保留字 https://dev.mysql.com/doc/refman/5.7/en/keywords.html 当我们建表的时候如果使用了关键字或者保留字,则在执行 ...
- 关于《Python自动化测试实战》
作者有话说 笔者写这本书的初心是想通过自身经验分享一些在自动化测试领域中的实用技术,能够帮助那些正在从事自动化测试相关工作或者准备转型自动化测试的测试人员.任何一门技术涵盖的知识点都是非常广泛的,可能 ...