逻辑回归算法原理及python实现

article/2025/9/16 18:40:33

文章目录

  • 引言
  • 逻辑回归算法原理
    • 逻辑回归损失函数
  • python实现逻辑回归
  • 决策边界
  • python实现多项式逻辑回归
  • sklearn中的逻辑回归
    • 逻辑回归中的正则化
    • sklearn实现逻辑回归

引言

逻辑回归(Logistic Regression)是一种分类学习算法,其本质是将样本的特征和样本发生的概率联系起来,由于发生的概率是一个数值,因此称为回归算法。主要解决2分类问题,例如:一个垃圾邮件过滤系统,x是邮件的特征,预测的y值就是邮件的类别(是垃圾邮件还是正常邮件)。

逻辑回归算法原理

逻辑回归算法步骤如下

  1. 计算样本发生的概率值,即 p ^ = f ( x ) \hat p=f(x) p^=f(x)
  2. 根据样本发生的概率分类 y ^ = { 1 , p ^ ≥ 0.5 0 , p ^ ≤ 0.5 \hat y= \begin{cases} 1 \ , \ \hat p\geq 0.5\\ 0 \ , \ \hat p\leq 0.5\\ \end{cases} y^={1  p^0.50  p^0.5

逻辑回归算法既可以看作回归算法,也可以看作分类算法,只执行第一步时就是回归算法,但是逻辑回归算法通常作为回归算法用,主要解决2分类问题。在线性回归算法中,样本预测值
y ^ = f ( x ) = θ T ⋅ x b \hat y=f(x)= \theta ^{T} \cdot x_b y^=f(x)=θTxb
其值域为( − ∞ , + ∞ -\infty , + \infty ,+),而概率的值域为[0,1],因此需要对 f ( x ) f(x) f(x)函数进行处理,使之值域处于[0,1]
p ^ = σ ( θ T ⋅ x b ) \hat p=\sigma( \theta ^{T} \cdot x_b ) p^=σ(θTxb),一般
σ ( t ) = 1 1 + e − t \sigma(t) = \frac{1}{1+e^{-t}} σ(t)=1+et1

σ ( t ) \sigma(t) σ(t)值域为(0,1),当t>0时,p>0.5;当t<0时,p<0.5

在这里插入图片描述

逻辑回归损失函数

模型预测值 y ^ \hat y y^ 如下
y ^ = { 1 , p ^ ≥ 0.5 0 , p ^ ≤ 0.5 \hat y= \begin{cases} 1 \ , \ \hat p\geq 0.5\\ 0 \ , \ \hat p\leq 0.5\\ \end{cases} y^={1  p^0.50  p^0.5
由此可以看出当实际值y=1时,p越小,损失越大;当y=0时,p越大,损失越大,即
c o s t = { y = 1 时 , p 越 小 , 损 失 越 大 y = 0 时 , p 越 大 , 损 失 越 大 cost= \begin{cases} y=1时,p越小,损失越大 \\ y=0时,p越大,损失越大\end{cases} cost={y=1py=0p

下面函数刚好满足条件

c o s t = { − l o g ( p ^ ) , i f y = 1 − l o g ( 1 − p ^ ) , i f y = 0 cost= \begin{cases} -log(\hat p) \ ,\ \ \ \ \ \ \ if \ \ y=1\\ -log(1-\hat p) \ ,if \ \ y=0\\ \end{cases} cost={log(p^)        if  y=1log(1p^) if  y=0
画出cost函数图像可以看出,当样本实际值为1时,预测概率值x为0, − log ⁡ ( x ) -\log(x) log(x)趋于正无穷,即损失趋于正无穷,当x=1即符合实际值,损失为0;当样本实际值为0时,预测值概率值x为1, − log ⁡ ( 1 − x ) -\log(1-x) log(1x)趋于正无穷,即损失趋于正无穷,当x=0即符合实际值,损失为0。
在这里插入图片描述
损失函数可以合为1个,即
在这里插入图片描述
最终得到损失函数
J ( θ ) = − 1 m ∑ i = 1 m y ( i ) + log ⁡ ( p ^ ( i ) ) + ( 1 − y ( i ) ) log ⁡ ( 1 − p ^ ( i ) ) J(\theta)=-\frac {1}{m} \sum_{i=1}^{m}{y^{(i)}+\log(\hat p^{(i)})+(1-y^{(i)})\log(1-\hat p^{(i)})} J(θ)=m1i=1my(i)+log(p^(i))+(1y(i))log(1p^(i))

p ^ ( i ) = σ ( X b ( i ) θ ) = 1 1 + e − X b ( i ) θ \hat p^{(i)}=\sigma(X_b^{(i)}\theta)=\frac{1}{1+e^{-X_b^{(i)}\theta}} p^(i)=σ(Xb(i)θ)=1+eXb(i)θ1

在这里插入图片描述
最后可以通过梯度下降法,求出使损失函数最小的 θ \theta θ,求得的损失函数梯度如下
在这里插入图片描述

python实现逻辑回归

import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_splitclass LogisticRegression:def __init__(self):self.coef_ = Noneself.intercept_ = Noneself._theta = Nonedef _sigmoid(self, t):return 1 / (1 + np.exp(-t))def fit(self, x_train, y_trian, n):def J(theta, x_b, y):y_hat = self._sigmoid(x_b.dot(theta))return -np.sum(y * np.log(y_hat) + (1 - y) * np.log(1 - y_hat)) / len(y)def dJ(theta, x_b, y):return x_b.T.dot(self._sigmoid(x_b.dot(theta)) - y) / len(y)def gradient_descent(x_b, y, initial_theta, alpha=0.01, n_iters=1e4, epsilon=1e-8):theta = initial_thetaiter = 0while iter < n_iters:gradient = dJ(theta, x_b, y)last_theta = thetatheta = theta - alpha * gradientif abs(J(last_theta, x_b, y) - J(theta, x_b, y)) < epsilon:breakiter += 1return last_thetax_b = np.hstack([np.ones((len(x_train), 1)), x_train])initail_theta = np.zeros(x_b.shape[1])self._theta = gradient_descent(x_b, y_trian, initail_theta, n_iters=n)self.intercept_ = self._theta[0]self.coef_ = self._theta[1:]def predict_prob(self, x_test):x_b = np.hstack([np.ones((len(x_test), 1)), x_test])return self._sigmoid(x_b.dot(self._theta))def predict(self, x_test):prob = self.predict_prob(x_test)return np.array(prob >= 0.5,dtype='int')def score(self, x_test, y_test):return np.sum(y_test == self.predict(x_test)) / len(y_test)# 鸢尾花数据集测试手写逻辑回归算法
iris = load_iris()
x = iris.data
y = iris.target# 由于逻辑回归只能处理2分类问题,截取分类为0,1,保留x2个特征方便可视化
X = x[y < 2, :2]
Y = y[y < 2]plt.scatter(X[Y == 0, 0], X[Y == 0, 1])
plt.scatter(X[Y == 1, 0], X[Y == 1, 1], color='r')
plt.show()x_train, x_test, y_train, y_test = train_test_split(X, Y)logistic = LogisticRegression()
logistic.fit(x_train, y_train, n=1e6)
y_predict = logistic.predict(x_test)
score = logistic.score(x_test, y_test)
print(score)
print(y_predict)
print(y_test)

输出
1.0
[0 1 1 1 0 0 0 0 0 1 1 0 1 1 1 0 0 1 1 0 1 0 1 1 1]
[0 1 1 1 0 0 0 0 0 1 1 0 1 1 1 0 0 1 1 0 1 0 1 1 1]在这里插入图片描述

决策边界

决策边界就是能够把样本正确分类的一条边界
p ^ = σ ( X b ⋅ θ ) = 1 1 + e − X b ⋅ θ \hat p=\sigma(X_b \cdot \theta)=\frac{1}{1+e^{-X_b \cdot \theta}} p^=σ(Xbθ)=1+eXbθ1
y ^ = { 1 , p ^ ≥ 0.5 0 , p ^ ≤ 0.5 \hat y= \begin{cases} 1 \ , \ \hat p\geq 0.5\\ 0 \ , \ \hat p\leq 0.5\\ \end{cases} y^={1  p^0.50  p^0.5
p ^ = 0.5 \hat p=0.5 p^=0.5时,=> X b ⋅ θ = 0 X_b \cdot \theta=0 Xbθ=0, 即为决策边界

(1) 当样本空间只有2个特征情况,即

θ 0 + x 1 θ 1 + x 2 θ 2 = 0 \theta_0+x_1 \theta_1+x_2 \theta_2=0 θ0+x1θ1+x2θ2=0

x 2 = − θ 0 − x 1 θ 1 θ 2 x_2=\frac{-\theta_0-x_1 \theta_1}{\theta_2} x2=θ2θ0x1θ1
绘制 x 1 , x 2 x_1,x_2 x1,x2关系直线图

x_1 = np.linspace(4, 7, 100)
x_2 = (-logistic.intercept_ - x_1 * logistic.coef_[0]) / logistic.coef_[1]
plt.plot(x_1, x_2)
plt.show()

在这里插入图片描述
(2)不规则决策边界绘制
把整个区域看成无数个点,用得出的模型去预测这些点,不同分类用不同颜色区分

def plot_decision_boundary(model, axis):# x/y轴矩阵,如x:0-2,y:0-1,得到x=[[0, 1, 2],[0, 1, 2]],y=[[0, 0, 0],[1, 1, 1]]x, y = np.meshgrid(np.linspace(axis[0], axis[1], int((axis[1] - axis[0]) * 100)).reshape(-1, 1),np.linspace(axis[2], axis[3], int((axis[3] - axis[2]) * 100)).reshape(-1, 1))# 矩阵拼接,如x:0-2,y:0-1,得到[[0. 0.], [1. 0.], [2. 0.], [0. 1.], [1. 1.], [2. 1.]]x_new = np.c_[x.reshape(-1), y.reshape(-1)]y_predict = model.predict(x_new)zz = y_predict.reshape(x.shape)custom_cmap = ListedColormap(['#EF9A9A', '#EFF59D', '#90CAF9'])plt.contourf(x, y, zz, linewidth=5, cmap=custom_cmap)

python实现多项式逻辑回归

import numpy as np
import matplotlib.pyplot as plt
from sklearn.pipeline import Pipeline
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import PolynomialFeatures
from sklearn.preprocessing import StandardScalerclass LogisticRegression:def __init__(self):self.coef_ = Noneself.intercept_ = Noneself._theta = Nonedef _sigmoid(self, t):return 1 / (1 + np.exp(-t))def fit(self, x_train, y_trian, n=1e4):def J(theta, x_b, y):y_hat = self._sigmoid(x_b.dot(theta))return -np.sum(y * np.log(y_hat) + (1. - y) * np.log(1. - y_hat)) / len(y)def dJ(theta, x_b, y):return x_b.T.dot(self._sigmoid(x_b.dot(theta)) - y) / len(x_b)def gradient_descent(x_b, y, initial_theta, alpha=0.01, n_iters=1e4, epsilon=1e-8):theta = initial_thetaiter = 0while iter < n_iters:gradient = dJ(theta, x_b, y)last_theta = thetatheta = theta - alpha * gradientif abs(J(last_theta, x_b, y) - J(theta, x_b, y)) < epsilon:breakiter += 1return last_thetax_b = np.hstack([np.ones((len(x_train), 1)), x_train])initail_theta = np.zeros(x_b.shape[1])self._theta = gradient_descent(x_b, y_trian, initail_theta, n_iters=n)self.intercept_ = self._theta[0]self.coef_ = self._theta[1:]def predict_prob(self, x_test):x_b = np.hstack([np.ones((len(x_test), 1)), x_test])return self._sigmoid(x_b.dot(self._theta))def predict(self, x_test):prob = self.predict_prob(x_test)return np.array(prob >= 0.5, dtype='int')def score(self, x_test, y_test):return np.sum(y_test == self.predict(x_test)) / len(y_test)def plot_decision_boundary(model, axis):# x/y轴矩阵,如x:0-2,y:0-1,得到x=[[0, 1, 2],[0, 1, 2]],y=[[0, 0, 0],[1, 1, 1]]x, y = np.meshgrid(np.linspace(axis[0], axis[1], int((axis[1] - axis[0]) * 100)).reshape(-1, 1),np.linspace(axis[2], axis[3], int((axis[3] - axis[2]) * 100)).reshape(-1, 1))# 矩阵拼接,如x:0-2,y:0-1,得到[[0. 0.], [1. 0.], [2. 0.], [0. 1.], [1. 1.], [2. 1.]]x_new = np.c_[x.reshape(-1), y.reshape(-1)]y_predict = model.predict(x_new)zz = y_predict.reshape(x.shape)custom_cmap = ListedColormap(['#EF9A9A', '#EFF59D', '#90CAF9'])plt.contourf(x, y, zz, linewidth=5, cmap=custom_cmap)# 测试数据集
x = np.random.normal(0, 1, size=(200, 2))
y = np.array(x[:, 0] ** 2 + x[:, 1] ** 2 < 1.5, dtype='int')
x_train, x_test, y_train, y_test = train_test_split(x, y)pip = Pipeline([('poly', PolynomialFeatures(degree=10)),('std', StandardScaler()),('logistic', LogisticRegression())
])
pip.fit(x_train, y_train)
score = pip.score(x_test, y_test)
print(score)plt.scatter(x[y == 0, 0], x[y == 0, 1])
plt.scatter(x[y == 1, 0], x[y == 1, 1])
plt.show()

在这里插入图片描述

sklearn中的逻辑回归

逻辑回归中的正则化

在多项式回归当中添加正则化模型后的损失函数为 J ( θ ) + α L J(\theta)+\alpha L J(θ)+αL,而在逻辑回归当中,模型正则化通常为 C ⋅ J ( θ ) + L 1 C\cdot J(\theta)+L_1 CJ(θ)+L1或者 C ⋅ J ( θ ) + L 2 C\cdot J(\theta)+L_2 CJ(θ)+L2,L1、L2对应2种正则项,如果C越大,优化损失函数时越应该集中火力,将损失函数减小到最小;C非常小时,此时L1和L2的正则项就显得更加重要。

sklearn实现逻辑回归

from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
import numpy as np
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import PolynomialFeatures
from sklearn.preprocessing import StandardScaler
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormapdef plot_decision_boundary(model, axis):# x/y轴矩阵,如x:0-2,y:0-1,得到x=[[0, 1, 2],[0, 1, 2]],y=[[0, 0, 0],[1, 1, 1]]x, y = np.meshgrid(np.linspace(axis[0], axis[1], int((axis[1] - axis[0]) * 100)).reshape(-1, 1),np.linspace(axis[2], axis[3], int((axis[3] - axis[2]) * 100)).reshape(-1, 1))# 矩阵拼接,如x:0-2,y:0-1,得到[[0. 0.], [1. 0.], [2. 0.], [0. 1.], [1. 1.], [2. 1.]]x_new = np.c_[x.reshape(-1), y.reshape(-1)]y_predict = model.predict(x_new)zz = y_predict.reshape(x.shape)custom_cmap = ListedColormap(['#EF9A9A', '#EFF59D', '#90CAF9'])plt.contourf(x, y, zz, linewidth=5, cmap=custom_cmap)# 测试数据集
x = np.random.normal(0, 1, size=(200, 2))
y = np.array(x[:, 0] ** 2 + x[:, 1] ** 2 < 1.5, dtype='int')
x_train, x_test, y_train, y_test = train_test_split(x, y)pip = Pipeline([('poly', PolynomialFeatures(degree=10)),('std', StandardScaler()),('logistic', LogisticRegression(C=1., penalty='l2'))
])pip.fit(x_train, y_train)
score = pip.score(x_test, y_test)
print(score)plot_decision_boundary(pip, axis=[-4, 4, -4, 4])
plt.scatter(x[y == 0, 0], x[y == 0, 1])
plt.scatter(x[y == 1, 0], x[y == 1, 1])
plt.show()

在这里插入图片描述


http://chatgpt.dhexx.cn/article/98CLSxpE.shtml

相关文章

基于逻辑回归算法模型搭建思路

在真实工作场景中&#xff0c;有多种算法依据借贷数据集建立模型&#xff0c;主要使用的算法有逻辑回归、神经网络、决策树、贝叶斯信念网、GBDT算法等&#xff0c;本系列文章旨在为刚入门和对模型感兴趣的同学介绍传统风控模型算法之一——逻辑回归。 前方高能&#xff01;准…

【机器学习】Logistic Regression 逻辑回归算法详解 + Java代码实现

文章目录 一、逻辑回归简介1.1 什么是逻辑回归1.2 Sigmoid函数1.3 预测函数 二、逻辑回归实战 - Java代码实现 一、逻辑回归简介 1.1 什么是逻辑回归 逻辑回归&#xff08;Logistic Regression&#xff09;是一种用于解决二分类&#xff08;0 or 1&#xff09;问题的机器学习…

机器学习之逻辑回归算法

文章目录 逻辑回归原理推导逻辑回归求解 逻辑回归&#xff08;Logistic Regression&#xff09;是机器学习中的一种分类模型&#xff0c;它是一种分类算法&#xff0c;虽然名字中带有回归&#xff0c;但是它与回归之间有一定的联系。 看到回归二字&#xff0c;很多人可能会认为…

机器学习算法 之 逻辑回归算法

1 逻辑回归之第一次学习 本文内容主要转自两处&#xff1a; [1] 逻辑回归从入门到深入&#xff08;logistic regression) 本文内容从Python 逻辑回归实际使用的角度出发&#xff0c;较为通俗易懂&#xff0c;感谢其作者的分享。 [2] 《百面机器学习》之逻辑回归 注意&#xf…

逻辑回归算法简介

逻辑回归算法&#xff1a;虽然名字中带有回归两个字&#xff0c;但它却不是回归算法&#xff0c;它是一个经典的二分类算法。 回归与分类的区别&#xff1a; 回归&#xff1a;可以得到一个准确值或一个区间值&#xff0c;比如房屋价格预测&#xff0c;NBA比赛得分等。 分类&am…

逻辑回归算法原理

回归与分类的不同在于其目标变量是否是连续的。分类是预测出一个标签&#xff0c;找到一条线或超平面去区分数据&#xff0c;输出是离散的、有限的。回归是预测出一个量&#xff0c;找到一条线去尽可能的拟合逼近这些数据&#xff0c;输出是连续的、无限的。 逻辑回归本质上是线…

机器学习算法--逻辑回归原理介绍

一、逻辑回归基本概念 1. 什么是逻辑回归 逻辑回归就是这样的一个过程&#xff1a;面对一个回归或者分类问题&#xff0c;建立代价函数&#xff0c;然后通过优化方法迭代求解出最优的模型参数&#xff0c;然后测试验证我们这个求解的模型的好坏。 Logistic回归虽然名字里带“…

逻辑回归算法

逻辑回归算法-龙珠计划 一、逻辑回归算法原理 逻辑回归&#xff08;Logistic Regression&#xff09; 属于机器学习 — 监督学习 — 分类。 逻辑回归&#xff08;Logistic Regression&#xff09;主要解决二分类问题&#xff0c;用来表示某件事情发生的可能性。 逻辑回归本…

【机器学习】逻辑回归算法

逻辑回归算法 学习目标1. 逻辑回归的介绍1.1 逻辑回归的应用场景1.2 逻辑回归的原理1.2.1 输入1.2.2 激活函数 1.3 损失以及优化1.3.1 损失1.3.2 优化 1.4 小结 2. 逻辑回归api介绍3. 案例&#xff1a;癌症分类预测-良&#xff0f;恶性乳腺癌肿瘤预测3.1 背景介绍3.2 案例分析3…

java中字符流和字节流的区别_java中字节流和字符流有哪些区别

java中字节流和字符流的区别有&#xff1a;1、定义不同&#xff1b;2、结尾不同&#xff1b;3、处理方式不同&#xff1b;4、缓冲区不同&#xff1b;5、编码方式不同。字节流默认不使用缓冲区&#xff0c;而字符流使用缓冲区。字节流采用ASCII编码&#xff0c;字符流采用unicod…

JAVA--字节流和字符流区别

&#xff08;一&#xff09;功能区别 1、FileInputSteam和FileOutputStream可以完成所有格式文件的复制&#xff1b; 2、FileReader和FileWriter只能完成文本格式的复制&#xff0c;无法完成视频、音频等文件的复制&#xff1b; &#xff08;二&#xff09;区别原理 1、字节…

Java进阶(四十五)java 字节流与字符流的区别

字节流与和字符流的使用非常相似&#xff0c;两者除了操作代码上的不同之外&#xff0c;是否还有其他的不同呢&#xff1f; 实际上字节流在操作时本身不会用到缓冲区&#xff08;内存&#xff09;&#xff0c;是文件本身直接操作的&#xff0c;而字符流在操作时使用了缓冲区&a…

字节流与字符流的区别用字节流好还是用字符流好?

字节流&#xff1a; (A)FileOutputStream(File name) 创建一个文件输出流&#xff0c;向指定的 File 对象输出数据。 (B)FileOutputStream(FileDescriptor) 创建一个文件输出流&#xff0c;向指定的文件描述器输出数据。 (C)FileOutputStream(String name) 创建一个文件输出流&…

Java基础面试题 | 字节流和字符流有什么区别?

字节流按 8 位传输&#xff0c;以字节为单位输入输出数据&#xff0c;字符流按 16 位传输&#xff0c;以字符为单位输入输出数据。 但是不管文件读写还是网络发送接收&#xff0c;信息的最小存储单元都是字节。 java 字节流与字符流的区别_afa的专栏-CSDN博客_java中字节流和…

JAVA字节流和字符流的区别

之前在复习IO的时候&#xff0c;为了方便记忆&#xff0c;提到了以Stream结尾的为字节流&#xff0c;以Writer或者Reader结尾的为字符流。 除了在使用上的不一样&#xff0c;那究竟两者有什么区别呢。直接给出结论&#xff1a;字节流在操作时本身不会用到缓冲区&#xff08;内…

字节流与字符流的区别及相互转换

转载&#xff1a;http://www.cnblogs.com/sjjsh/p/5269781.html 先来看一下流的概念&#xff1a; 在程序中所有的数据都是以流的方式进行传输或保存的&#xff0c;程序需要数据的时候要使用输入流读取数据&#xff0c;而当程序需要将一些数据保存起来的时候&#xff0c;就要使用…

字节流与字符流

字节流、字符流 主要内容 IO 流 字节流 字符流 异常处理 Properties 教学目标 能够说出IO流的分类和功能 能够使用字节输出流写出数据到文件能够使用字节输入流读取数据到程序 能够理解读取数据read(byte[])方法的原理能够使用字节流完成文件的复制 能够使用FileWirter…

Java字节流和字符流的区别?

字符流&#xff1a;就是在字节流的基础上&#xff0c;加上编码&#xff0c;形成的数据流 字符流出现的意义&#xff1a;因为字节流在操作字符时&#xff0c;可能会有中文导致的乱码&#xff0c;所以由字节流引申出了字符流。 程序中所有的数据都是以流的方式进行传输或保存的…

字节流和字符流的区别

目录 1.区别 2.字节流 2.1没执行代码前&#xff1a; 2.2效果&#xff1a; 3.字符流 3.1代码 3.2效果前&#xff1a; 3.3执行后 没效果&#xff1a;&#xff08;因为数据还在临时内存&#xff09; 3.4需要:多上面多个关闭资源 3.5 效果图&#xff1a;&#xff08;可以关…