第九章 Logistic回归分类模型

逻辑回归(Logistic Regression)原理是一种用于解决二分类(0或1)问题的统计学习方法。虽然名字中包含了“回归”二字,但实际上它是一种分类方法,只是其数学实现上借鉴了回归的思想。以下是逻辑回归的主要原理:

模型假设:
逻辑回归假设因变量(即要预测的目标变量)服从伯努利分布(Bernoulli distribution),即对于给定的输入x,输出y的概率为p,则1-p为y不发生的概率。
线性模型:
首先,逻辑回归构建一个线性模型,用于预测事件发生的概率。线性模型的形式为 z = w0 + w1x1 + w2x2 + … + wn*xn,其中w是权重,x是输入特征,n是特征数量。
逻辑函数(Sigmoid函数):
线性模型的输出z是一个实数,但我们需要将其转换为0到1之间的概率值。为此,我们使用逻辑函数(也称为Sigmoid函数)来转换z。逻辑函数的形式为 p(y=1|x) = 1 / (1 + e^(-z))。这个函数将z映射到0和1之间,当z接近正无穷时,p接近1;当z接近负无穷时,p接近0。
损失函数:
逻辑回归使用最大似然估计来求解模型参数(即权重w)。为了找到使模型预测最准确的参数,我们需要定义一个损失函数(也称为成本函数或误差函数)。逻辑回归通常使用对数似然损失函数,其形式为 -Σy_i * log(p_i) + (1 - y_i) * log(1 - p_i),其中y_i是真实标签,p_i是模型预测的概率。
优化算法:
为了找到使损失函数最小的参数,我们使用优化算法(如梯度下降、随机梯度下降、批量梯度下降等)来迭代更新参数。在每次迭代中,我们计算损失函数关于参数的梯度,并使用这个梯度来更新参数。
模型评估:
在训练模型后,我们需要评估模型的性能。对于二分类问题,常用的评估指标包括准确率、精确率、召回率、F1分数、AUC-ROC曲线等。
正则化:
为了防止过拟合,我们还可以在损失函数中加入正则化项(如L1正则化或L2正则化),以约束参数的大小。正则化项的引入会使模型在拟合训练数据的同时,也考虑到模型的复杂度,从而提高模型的泛化能力。
总的来说,逻辑回归是一种简单而有效的二分类方法,它通过构建一个线性模型并使用逻辑函数将输出转换为概率值来预测目标变量的取值。通过优化算法和正则化技术,我们可以找到使模型性能最优的参数。

# 自定义绘制ks曲线的函数
def plot_ks(y_test, y_score, positive_flag):
    # 对y_test,y_score重新设置索引
    y_test.index = np.arange(len(y_test))
    #y_score.index = np.arange(len(y_score))
    # 构建目标数据集
    target_data = pd.DataFrame({'y_test':y_test, 'y_score':y_score})
    # 按y_score降序排列
    target_data.sort_values(by = 'y_score', ascending = False, inplace = True)
    # 自定义分位点
    cuts = np.arange(0.1,1,0.1)
    # 计算各分位点对应的Score值
    index = len(target_data.y_score)*cuts
    scores = target_data.y_score.iloc[index.astype('int')]
    # 根据不同的Score值,计算Sensitivity和Specificity
    Sensitivity = []
    Specificity = []
    for score in scores:
        # 正例覆盖样本数量与实际正例样本量
        positive_recall = target_data.loc[(target_data.y_test == positive_flag) & (target_data.y_score>score),:].shape[0]
        positive = sum(target_data.y_test == positive_flag)
        # 负例覆盖样本数量与实际负例样本量
        negative_recall = target_data.loc[(target_data.y_test != positive_flag) & (target_data.y_score<=score),:].shape[0]
        negative = sum(target_data.y_test != positive_flag)
        Sensitivity.append(positive_recall/positive)
        Specificity.append(negative_recall/negative)
    # 构建绘图数据
    plot_data = pd.DataFrame({'cuts':cuts,'y1':1-np.array(Specificity),'y2':np.array(Sensitivity), 
                              'ks':np.array(Sensitivity)-(1-np.array(Specificity))})
    # 寻找Sensitivity和1-Specificity之差的最大值索引
    max_ks_index = np.argmax(plot_data.ks)
    plt.plot([0]+cuts.tolist()+[1], [0]+plot_data.y1.tolist()+[1], label = '1-Specificity')
    plt.plot([0]+cuts.tolist()+[1], [0]+plot_data.y2.tolist()+[1], label = 'Sensitivity')
    # 添加参考线
    plt.vlines(plot_data.cuts[max_ks_index], ymin = plot_data.y1[max_ks_index], 
               ymax = plot_data.y2[max_ks_index], linestyles = '--')
    # 添加文本信息
    plt.text(x = plot_data.cuts[max_ks_index]+0.01,
             y = plot_data.y1[max_ks_index]+plot_data.ks[max_ks_index]/2,
             s = 'KS= %.2f' %plot_data.ks[max_ks_index])
    # 显示图例
    plt.legend()
    # 显示图形
    plt.show()
# 导入第三方包
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# 导入虚拟数据
virtual_data = pd.read_excel(r'virtual_data.xlsx')
# 应用自定义函数绘制k-s曲线
plot_ks(y_test = virtual_data.Class, y_score = virtual_data.Score,positive_flag = 'P')
# 导入第三方模块
import pandas as pd
import numpy as np
from sklearn import linear_model
from sklearn import model_selection

# 读取数据
sports = pd.read_csv(r'Run or Walk.csv')
# 提取出所有自变量名称
predictors = sports.columns[4:]
# 构建自变量矩阵
X = sports.ix[:,predictors]
# 提取y变量值
y = sports.activity
# 将数据集拆分为训练集和测试集
X_train, X_test, y_train, y_test = model_selection.train_test_split(X, y, test_size = 0.25, random_state = 1234)

# 利用训练集建模
sklearn_logistic = linear_model.LogisticRegression()
sklearn_logistic.fit(X_train, y_train)
# 返回模型的各个参数
print(sklearn_logistic.intercept_, sklearn_logistic.coef_)
# 模型预测
sklearn_predict = sklearn_logistic.predict(X_test)
# 预测结果统计
pd.Series(sklearn_predict).value_counts()
# 导入第三方模块
from sklearn import metrics
# 混淆矩阵
cm = metrics.confusion_matrix(y_test, sklearn_predict, labels = [0,1])
cm
Accuracy = metrics.scorer.accuracy_score(y_test, sklearn_predict)
Sensitivity = metrics.scorer.recall_score(y_test, sklearn_predict)
Specificity = metrics.scorer.recall_score(y_test, sklearn_predict, pos_label=0)
print('模型准确率为%.2f%%:' %(Accuracy*100))
print('正例覆盖率为%.2f%%' %(Sensitivity*100))
print('负例覆盖率为%.2f%%' %(Specificity*100))
# 混淆矩阵的可视化
# 导入第三方模块
import seaborn as sns
import matplotlib.pyplot as plt
# 绘制热力图
sns.heatmap(cm, annot = True, fmt = '.2e',cmap = 'GnBu')
# 图形显示
plt.show()
# y得分为模型预测正例的概率
y_score = sklearn_logistic.predict_proba(X_test)[:,1]
# 计算不同阈值下,fpr和tpr的组合值,其中fpr表示1-Specificity,tpr表示Sensitivity
fpr,tpr,threshold = metrics.roc_curve(y_test, y_score)
# 计算AUC的值
roc_auc = metrics.auc(fpr,tpr)

# 绘制面积图
plt.stackplot(fpr, tpr, color='steelblue', alpha = 0.5, edgecolor = 'black')
# 添加边际线
plt.plot(fpr, tpr, color='black', lw = 1)
# 添加对角线
plt.plot([0,1],[0,1], color = 'red', linestyle = '--')
# 添加文本信息
plt.text(0.5,0.3,'ROC curve (area = %0.2f)' % roc_auc)
# 添加x轴与y轴标签
plt.xlabel('1-Specificity')
plt.ylabel('Sensitivity')
# 显示图形
plt.show()
# 调用自定义函数,绘制K-S曲线
plot_ks(y_test = y_test, y_score = y_score, positive_flag = 1)

# -----------------------第一步 建模 ----------------------- #
# 导入第三方模块
import statsmodels.api as sm
# 将数据集拆分为训练集和测试集
X_train, X_test, y_train, y_test = model_selection.train_test_split(X, y, test_size = 0.25, random_state = 1234)
# 为训练集和测试集的X矩阵添加常数列1
X_train2 = sm.add_constant(X_train)
X_test2 = sm.add_constant(X_test)
# 拟合Logistic模型
sm_logistic = sm.formula.Logit(y_train, X_train2).fit()
# 返回模型的参数
sm_logistic.params
# -----------------------第二步 预测构建混淆矩阵 ----------------------- #
# 模型在测试集上的预测
sm_y_probability = sm_logistic.predict(X_test2)
# 根据概率值,将观测进行分类,以0.5作为阈值
sm_pred_y = np.where(sm_y_probability >= 0.5, 1, 0)
# 混淆矩阵
cm = metrics.confusion_matrix(y_test, sm_pred_y, labels = [0,1])
cm
# -----------------------第三步 绘制ROC曲线 ----------------------- #
# 计算真正率和假正率 
fpr,tpr,threshold = metrics.roc_curve(y_test, sm_y_probability)
# 计算auc的值  
roc_auc = metrics.auc(fpr,tpr)
# 绘制面积图
plt.stackplot(fpr, tpr, color='steelblue', alpha = 0.5, edgecolor = 'black')
# 添加边际线
plt.plot(fpr, tpr, color='black', lw = 1)
# 添加对角线
plt.plot([0,1],[0,1], color = 'red', linestyle = '--')
# 添加文本信息
plt.text(0.5,0.3,'ROC curve (area = %0.2f)' % roc_auc)
# 添加x轴与y轴标签
plt.xlabel('1-Specificity')
plt.ylabel('Sensitivity')
# 显示图形
plt.show()
# -----------------------第四步 绘制K-S曲线 ----------------------- #
# 调用自定义函数,绘制K-S曲线
sm_y_probability.index = np.arange(len(sm_y_probability))
plot_ks(y_test = y_test, y_score = sm_y_probability, positive_flag = 1)

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 4
    评论
1. 读取数据,显示前10行数据后后10行数据 ```python import pandas as pd # 读取数据 data = pd.read_csv('breast_cancer.csv') # 显示前10行数据 print(data.head(10)) # 显示后10行数据 print(data.tail(10)) ``` 2. 按照8:2的比例分割数据集为训练集和测试集,显示测试集和数据集的维度 ```python from sklearn.model_selection import train_test_split # 分割数据集为训练集和测试集 train_data, test_data, train_label, test_label = train_test_split(data.iloc[:, :-1], data.iloc[:, -1], test_size=0.2, random_state=0) # 显示训练集和测试集的维度 print("训练集维度:", train_data.shape) print("测试集维度:", test_data.shape) ``` 3. 使用全变量创建逻辑Logistic回归模型,显示模型表达式 ```python from sklearn.linear_model import LogisticRegression # 创建逻辑回归模型 model = LogisticRegression() # 训练模型 model.fit(train_data, train_label) # 显示模型表达式 print("模型表达式:") print("y = ", end="") for i in range(len(model.coef_[0])): print("{:.4f} * x{} + ".format(model.coef_[0][i], i), end="") print("{:.4f}".format(model.intercept_[0])) ``` 4. 使用逐步回归法选择合适的变量创建Logistics回归模型,选出最好的模型,显示模型表达式 ```python from mlxtend.feature_selection import SequentialFeatureSelector from sklearn.linear_model import LogisticRegression # 创建逐步回归选择器 selector = SequentialFeatureSelector(LogisticRegression(), scoring='accuracy', verbose=2, k_features=5, forward=True, n_jobs=-1) # 训练选择器 selector.fit(train_data, train_label) # 显示选择的特征 print("选择的特征:", selector.k_feature_idx_) # 创建逻辑回归模型 model = LogisticRegression() # 训练模型 model.fit(train_data.iloc[:, selector.k_feature_idx_], train_label) # 显示模型表达式 print("模型表达式:") print("y = ", end="") for i in range(len(model.coef_[0])): print("{:.4f} * x{} + ".format(model.coef_[0][i], selector.k_feature_idx_[i]), end="") print("{:.4f}".format(model.intercept_[0])) ``` 5. 计算并显示Logistic回归模型在训练集和验证集上的准确率 ```python from sklearn.metrics import accuracy_score # 在训练集上计算准确率 train_predict = model.predict(train_data.iloc[:, selector.k_feature_idx_]) train_accuracy = accuracy_score(train_label, train_predict) print("训练集准确率:", train_accuracy) # 在验证集上计算准确率 test_predict = model.predict(test_data.iloc[:, selector.k_feature_idx_]) test_accuracy = accuracy_score(test_label, test_predict) print("测试集准确率:", test_accuracy) ``` 6. 分析Logistic回归模型分类结果。 通过对训练集和测试集的准确率进行比较,我们可以看出模型在训练集上的准确率为1.0,而在测试集上的准确率为0.9649,说明模型具有一定的泛化能力,能够较好地对新数据进行分类。同时,我们还可以通过混淆矩阵等工具对模型进行更深入的分析。
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

灯下夜无眠

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值