二分类逻辑回归原理与复现


前言

复现二分类LogisticRegression(逻辑回归),加深模型的理解与复现能力。
文中会给出伪代码和相关的具体计算案例帮助理解。


一、LogisticRegression

1.1 什么是逻辑回归?

逻辑回归(Logistic Regression)是一种用于解决分类问题的统计学习方法。与线性回归不同,逻辑回归的因变量是离散的而非连续的。它通过建立一个逻辑回归模型来预测观测值所属的类别,模型输出的值范围在0和1之间,表示观测值属于某个类别的概率。

逻辑回归模型基于线性回归模型,使用了一个称为“逻辑函数”或“sigmoid函数”的特殊函数,将线性函数的输出转化为介于0和1之间的概率。常用的逻辑函数是sigmoid函数,也称为逻辑斯蒂函数(Logistic function)。 sigmoid函数的数学表达式为:
f ( z ) = 1 1 + e − z f(z) = \frac{1}{1+e^{-z}} f(z)=1+ez1
其中,z代表预测变量的线性组合。

逻辑回归模型的训练过程通常使用最大似然估计或梯度下降等优化算法来确定模型的参数。经过训练后,模型可以用于预测新的观测值所属的类别,通常是根据预测的概率值进行判断,例如,当概率大于0.5时归为一类,否则归为另一类。

1.2 伪代码

Input: 训练数据集 D = {(x1, y1), (x2, y2), ..., (xn, yn)},其中 xi 表示第 i 个样本的特征向量,yi 表示其对应的类别标签
       学习率 learning_rate

Output: 逻辑回归模型的权重参数 w

Step 1: 初始化权重参数 w:
        w = [w1, w2, ..., wd],其中 d 为特征的维度,并且初始化 w 中的元素为 0 或者一个较小的随机值

Step 2: 定义 sigmoid 函数:
        def sigmoid(z):
       		return 1 / (1 + exp(-z))

Step 3: 进行迭代更新权重参数 w 直至收敛:
    for each epoch:
        for each training sample (x, y) in D:
            z = dot_product(w, x)  # 计算样本 x 的线性组合
            a = sigmoid(z)  # 通过 sigmoid 函数将结果转换为概率值
            gradient = x * (y - a)  # 根据梯度下降法计算梯度
            w = w + learning_rate * gradient  # 更新权重参数 w

Step 4: 返回训练得到的权重参数 w

1.3 具体计算案例

假设我们有一个二分类问题,要根据学生的学习时间和考试成绩两个特征来预测其是否通过考试。

训练数据集 D 包含以下样本:
D = { (x1=(5, 60), y=0), (x2=(3, 80), y=0), (x3=(8, 70), y=1), (x4=(4, 75), y=1) }

其中,x 表示特征向量,y 表示类别标签(0 表示未通过考试,1 表示通过考试)。

我们设置学习率 learning_rate=0.01。

通过迭代更新权重参数 w,进行逻辑回归模型的训练:

  • 初始化权重参数 w 为 [0, 0]
  • 第一次迭代:
    • 对于样本 (x1=(5, 60), y=0):
      • 计算线性组合 z = 0 * 5 + 0 * 60 = 0
      • 计算概率值 a = sigmoid(0) = 0.5
      • 计算梯度 gradient = [5, 60] * (0 - 0.5) = [-2.5, -30]
      • 更新权重参数 w = [0, 0] + 0.01 * [-2.5, -30] = [0.025, 0.3]
    • 对于样本 (x2=(3, 80), y=0):
      • 计算线性组合 z = 0.025 * 3 + 0.3 * 80 = 24.5
      • 计算概率值 a = sigmoid(24.5) ≈ 1
      • 计算梯度 gradient = [3, 80] * (0 - 1) = [-3, -80]
      • 更新权重参数 w = [0.025, 0.3] + 0.01 * [-3, -80] = [0.055, 1.1]
    • 对于样本 (x3=(8, 70), y=1):
      • 计算线性组合 z = 0.055 * 8 + 1.1 * 70 = 81.06
      • 计算概率值 a = sigmoid(81.06) ≈ 1
      • 计算梯度 gradient = [8, 70] * (1 - 1) = [0, 0]
      • 更新权重参数 w = [0.055, 1.1] # 权重参数无变化,梯度为 0
    • 对于样本 (x4=(4, 75), y=1):
      • 计算线性组合 z = 0.055 * 4 + 1.1 * 75 = 83.5
      • 计算概率值 a = sigmoid(83.5) ≈ 1
      • 计算梯度 gradient = [4, 75] * (1 - 1) = [0, 0]
      • 更新权重参数 w = [0.055, 1.1] # 权重参数无变化,梯度为 0

经过多次迭代后,权重参数 w 收敛于一个稳定的值。

最终训练得到的逻辑回归模型的权重参数 w 为 [0.055, 1.1]。

对于测试样本 x=(6, 65),我们将它带入逻辑回归模型进行预测。

  • 计算线性组合 z = 0.055 * 6 + 1.1 * 65 ≈ 71.775
  • 计算概率值 a = sigmoid(71.775) ≈ 1
  • 最终预测结果为通过考试。

二、复现LogisticRegression

2.1 封装为类

并给出详细的注释

class MYlogistic_regression:
    def __init__(self, learning_rate=0.01, num_epochs=100, w_mode="zeros"):
        self.learning_rate = learning_rate  # 学习率
        self.num_epochs = num_epochs        # 迭代次数
        self.w_mode = w_mode                # 初始权重参数的模式

    def sigmoid(self, z):
        # return 1 / (1 + np.exp(-z))         # Sigmoid 激活函数,将输入值 z 映射到 [0, 1] 区间
        return scipy.special.expit(z)              # 确保不会溢出

    def get_w(self):
        if self.w_mode == "zeros":
            self.w = np.zeros(self.num_features)          # 初始化权重参数为0
        elif self.w_mode == "random":
            self.w = np.random.random(self.num_features)  # 初始化权重参数为[0,1]之间的随机值

    def Stochastic_Gradient_Descent(self):
        # 随机梯度下降法(Stochastic Gradient Descent):在每个迭代步骤中,仅使用一个样本计算梯度并更新权重参数。
        # 这意味着每个样本都会对参数进行更新,而不是使用整个训练集的平均梯度。
        # 由于每次只计算一个样本的梯度,随机梯度下降法通常具有更快的训练速度,但收敛性可能会不够稳定。
        for epoch in range(self.num_epochs):     # 迭代次数为num_epochs
            for i in range(self.x_train.shape[0]):
                xi = self.x_train[i]             # 当前样本的特征向量
                yi = self.y_train[i]             # 当前样本对应的标签值
                z = np.dot(self.w, xi)           # 计算线性回归模型的预测值 z
                a = self.sigmoid(z)              # 将预测值 z 经过 sigmoid 函数得到概率 a
                gradient = xi * (yi - a)         # 计算梯度
                self.w = self.w + self.learning_rate * gradient  # 根据学习率更新权重参数

    def update_w(self, updateW_mode):
        if updateW_mode == "SGD":
            self.Stochastic_Gradient_Descent()     # 使用随机梯度下降法更新模型参数

    def fit(self, x_train, y_train, updateW_mode="SGD"):
        self.x_train, self.y_train = x_train, y_train
        # X, Y 均为 numpy 格式,涉及到的操作都是 numpy 类型
        if type(self.x_train) != np.ndarray:
            self.x_train = np.array(self.x_train)
        if type(self.y_train) != np.ndarray:
            self.y_train = np.array(self.y_train)

        self.num_features = self.x_train.shape[1]  # 特征个数
        self.get_w()                               # 初始化权重参数
        self.update_w(updateW_mode)                # 默认使用随机梯度下降法更新模型参数

    def predict(self, x_test):
        self.x_test = x_test
        # 涉及到的操作都是 numpy 类型
        if type(self.x_test) != np.ndarray:
            self.x_test = np.array(self.x_test)

        z = np.dot(self.x_test, self.w)            # 计算线性回归模型的预测值 z
        predict_prob = self.sigmoid(z)             # 将预测值 z 经过 sigmoid 函数得到概率 a
        predict = (predict_prob > 0.5).astype(int) # 根据阈值 0.5 进行预测判断
        return predict

2.2 读入数据

import pandas as pd 
data = pd.read_csv(r"heart.csv")
for column in data.columns: 
    data[column].replace("N",np.nan,inplace=True)  # 将错误的值换成缺失值格式np.Nan
print(data.shape)
data = data.dropna() # 删除nan值
print(data.shape)
data["sex"].replace("male",0,inplace=True) 
data["sex"].replace("female",1,inplace=True) 
data["thal"].replace("fixed defect",0,inplace=True) 
data["thal"].replace("reversable defect",1,inplace=True)  
data["thal"].replace("normal",2,inplace=True)
Y = data['target'] 
X = data.drop("target",axis=1) 
# 切分数据集,设置测试集占比为30%
x_train, x_test, y_train, y_test = train_test_split(X,Y,test_size=0.2, random_state=3220822)

2.3 sklearn封装LogisticRegression类

# 创建逻辑回归模型并进行训练
model = LogisticRegression(max_iter=1000)
model.fit(x_train, y_train)
# 进行预测
y_pred = model.predict(x_test)
# 计算准确率
accuracy = accuracy_score(y_test, y_pred)
print("准确率:", accuracy)

在这里插入图片描述

2.4 调用复现的LogisticRegression类

learning_rate = 0.1
num_epochs = 1000
mymodel = MYlogistic_regression(learning_rate=learning_rate,num_epochs=num_epochs)
mymodel.fit(x_train, y_train)
# 进行预测
y_predict = mymodel.predict(x_test)
# 计算准确率
accuracy = accuracy_score(y_test, y_predict)
print("准确率:", accuracy)

总结

通过数据验证,可以发现两者达到相同的效果,且在本文中复现的算法,可以更加多的进行补充。例如

  • 补充批量梯度下降法(Batch Gradient Descent)或小批量梯度下降法(Mini-Batch Gradient Descent)
  • 考虑添加正则化项、特征缩放等来提高模型的性能和稳定性。
  • 文中复现的仅是二分类的逻辑回归,可后续进行补充,使其适用于多分类数据集。
  • 9
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值