ML算法——逻辑回归随笔【机器学习】

news2024/10/6 17:16:31

文章目录

  • 3、逻辑回归
    • 3.1、理论部分
    • 3.2、sklearn 实现
    • 3.3、案例

3、逻辑回归


3.1、理论部分

Logic Regression (LR),逻辑回归的因变量是二分类的,而不是连续的。它的输出是一个概率值,表示输入数据属于某个类别的概率。如果该值为0.8,则表示输入数据有80%的可能性属于某个类别。

解决二元(0/1)分类问题,优先考虑。

逻辑函数是一个sigmoid函数,其公式为:

f ( x ) = 1 1 + e − x f(x) = \frac{1}{1 + e^{-x}} f(x)=1+ex1

其中,x是由输入特征和权重组成的向量,f(x)表示输入特征属于某个类别的概率。

类别1的概率 P = 1 1 + e − ( θ T x ) P =\frac{1}{1+e^{-(θ^Tx)}} P=1+e(θTx)1
类别0的概率 1 − P = 1 1 + e θ T x 1-P = \frac{1}{1+e^{θ^Tx}} 1P=1+eθTx1
类别1与0概率比值 P 1 − P = e θ T x \frac{P}{1-P} =e^{θ^Tx} 1PP=eθTx
类别1与0概率比值的自然对数 l n P 1 − P = θ T x ln\frac{P}{1-P} = θ^Tx ln1PP=θTx

以买房预测理解这个逻辑函数

在这里插入图片描述

如何判断θ是三个?θTx的转置公式是怎样的?

参照线性回归中的θ,这里的θ也是个向量,涵盖所有提到过的θ分量,θ=< θ 0 , θ 1 , θ 2 θ_0,θ_1,θ_2 θ0,θ1,θ2>。转置可能是与x这个向量进行矩阵乘法,个人猜测是这样的, θ T = < θ 0 , θ 1 , θ 2 > , x = < x 0 , x 1 , x 2 > T θ^T=<θ_0,θ_1,θ_2> ,x =<x0,x1,x2>^T θT=<θ0,θ1,θ2>,x=<x0,x1,x2>T,(1,3)(3,1)得到一个1×1结果。

逻辑回归的损失函数

在这里插入图片描述

梯度方向:→|向右/正向 ←|向左|反方向

应用场景:

  • 垃圾邮件分类
  • 广告点击预测
  • 医疗效果预测

3.2、sklearn 实现

#训练模型
from sklearn.linear_model import LogisticRegression
model = LogisticRegression().fit(X_train,y_train)
res =model.score(X_train,y_train)
print(f"训练数据上的准确率为:{res}")
res= model.score(X_test,y_test)
print(f"测试数据上的准确率为:{res}")

这里使用的默认参数,LogisticRegression() ,具体场景下,应该调参

3.3、案例

预测银行客户是否开设定存账户 <观察样本><样本不平衡问题>

import pandas as pd
import numpy as np
from sklearn import preprocessing
import matplotlib.pyplot as plt 
plt.rc("font", size=14)
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
import seaborn as sns
sns.set(style="white")
sns.set(style="whitegrid", color_codes=True)
data = pd.read_csv('banking.csv', header=0)
data = data.dropna()
print(data.shape)
print(list(data.columns))
(41188, 21)
['age', 'job', 'marital', 'education', 'default', 'housing', 'loan', 'contact', 'month', 'day_of_week', 'duration', 'campaign', 'pdays', 'previous', 'poutcome', 'emp_var_rate', 'cons_price_idx', 'cons_conf_idx', 'euribor3m', 'nr_employed', 'y']

输入特征的意义:

bank client data:

  • 1 - age (numeric)
  • 2 - job : type of job (categorical: ‘admin.’,‘blue-collar’,‘entrepreneur’,‘housemaid’,‘management’,‘retired’,‘self-employed’,‘services’,‘student’,‘technician’,‘unemployed’,‘unknown’)
  • 3 - marital : marital status (categorical: ‘divorced’,‘married’,‘single’,‘unknown’; note: ‘divorced’ means divorced or widowed)
  • 4 - education (categorical: ‘basic.4y’,‘basic.6y’,‘basic.9y’,‘high.school’,‘illiterate’,‘professional.course’,‘university.degree’,‘unknown’)
  • 5 - default: has credit in default? (categorical: ‘no’,‘yes’,‘unknown’)
  • 6 - housing: has housing loan? (categorical: ‘no’,‘yes’,‘unknown’)
  • 7 - loan: has personal loan? (categorical: ‘no’,‘yes’,‘unknown’)

related with the last contact of the current campaign:

  • 8 - contact: contact communication type (categorical: ‘cellular’,‘telephone’)
  • 9 - month: last contact month of year (categorical: ‘jan’, ‘feb’, ‘mar’, …, ‘nov’, ‘dec’)
  • 10 - day_of_week: last contact day of the week (categorical: ‘mon’,‘tue’,‘wed’,‘thu’,‘fri’)
  • 11 - duration: last contact duration, in seconds (numeric). Important note: this attribute highly affects the output target (e.g., if duration=0 then y=‘no’). Yet, the duration is not known before a call is performed. Also, after the end of the call y is obviously known. Thus, this input should only be included for benchmark purposes and should be discarded if the intention is to have a realistic predictive model.

other attributes:

  • 12 - campaign: number of contacts performed during this campaign and for this client (numeric, includes last contact)
  • 13 - pdays: number of days that passed by after the client was last contacted from a previous campaign (numeric; * 999 means client was not previously contacted)
  • 14 - previous: number of contacts performed before this campaign and for this client (numeric)
  • 15 - poutcome: outcome of the previous marketing campaign (categorical: ‘failure’,‘nonexistent’,‘success’)

social and economic context attributes

  • 16 - emp.var.rate: employment variation rate - quarterly indicator (numeric)
  • 17 - cons.price.idx: consumer price index - monthly indicator (numeric)
  • 18 - cons.conf.idx: consumer confidence index - monthly indicator (numeric)
  • 19 - euribor3m: euribor 3 month rate - daily indicator (numeric)
  • 20 - nr.employed: number of employees - quarterly indicator (numeric)

Output variable (desired target):

  • 21 - y - has the client subscribed a term deposit? (binary: ‘yes’,‘no’)

获取'education'列的所有唯一值

data['education'].unique()

简化处理,basic.9ybasic.4ybasic.6y统一为Basic

data['education']=np.where(data['education'] =='basic.9y', 'Basic', data['education'])
data['education']=np.where(data['education'] =='basic.6y', 'Basic', data['education'])
data['education']=np.where(data['education'] =='basic.4y', 'Basic', data['education'])
data['education'].unique()

这次结果中只有 array([‘Basic’, ‘unknown’, ‘university.degree’, ‘high.school’, ‘professional.course’, ‘illiterate’], dtype=object)

统计开户情况,明显的样本数据不平衡(下文将详述)

data['y'].value_counts()

0 36548

1 4640

Name: y, dtype: int64

以图的形式呈现统计结果

sns.countplot(x='y', data = data, palette='hls')
plt.show()
plt.savefig('count_plot')

以百分比形式呈现统计结果

count_no_sub = len(data[data['y']==0])
count_sub = len(data[data['y']==1])
pct_of_no_sub = count_no_sub/(count_no_sub+count_sub)
print('未开户的百分比:  %.2f%%' % (pct_of_no_sub*100))
pct_of_sub = count_sub/(count_no_sub+count_sub)
print('开户的百分比:  %.2f%%' % (pct_of_sub*100))

未开户的百分比: 88.73% 开户的百分比: 11.27%

依据是否开户分组,取平均观察

data.groupby('y').mean()

在这里插入图片描述

按照其他特征分组观察

data.groupby('job').mean()

在这里插入图片描述

data.groupby('marital').mean()
data.groupby('education').mean()

购买定期存款的客户的平均年龄高于未购买定期存款的客户的平均年龄。

购买定期存款的客户的 pdays(自上次联系客户以来的日子)较低。 pdays越低,最后一次通话的记忆越好,因此销售的机会就越大。

购买定期存款的客户的销售通话次数较低。

我们可以计算其他特征值(如教育和婚姻状况)的分布,以更详细地了解我们的数据。

%matplotlib inline
table=pd.crosstab(data.job,data.y)
table.div(table.sum(1).astype(float), axis=0).plot(kind='bar', stacked=True)
plt.title('Stacked Bar Chart of Job title vs Purchase')
plt.xlabel('Job')
plt.ylabel('Proportion of Purchase')
plt.savefig('purchase_vs_job')

在这里插入图片描述

具有不同职位的人购买存款的频率不一样。 因此,职称可以是良好的预测因素。

table=pd.crosstab(data.marital,data.y)
table.div(table.sum(1).astype(float), axis=0).plot(kind='bar', stacked=True)
plt.title('Stacked Bar Chart of Marital Status vs Purchase')
plt.xlabel('Marital Status')
plt.ylabel('Proportion of Customers')
plt.savefig('mariral_vs_pur_stack')

在这里插入图片描述
相比较,婚姻不是好的预测因素,差距不大。

table=pd.crosstab(data.education,data.y)
table.div(table.sum(1).astype(float), axis=0).plot(kind='bar', stacked=True)
plt.title('Stacked Bar Chart of Education vs Purchase')
plt.xlabel('Education')
plt.ylabel('Proportion of Customers')
plt.savefig('edu_vs_pur_stack')

在这里插入图片描述

有变化,教育似乎是结果变量的良好预测指标。

table=pd.crosstab(data.day_of_week,data.y)#.plot(kind='bar')
table.div(table.sum(1).astype(float), axis=0).plot(kind='bar', stacked=True)
plt.title('Stacked Bar Chart of Day of Week vs Purchase')
plt.xlabel('Day of Week')
plt.ylabel('Proportion of Purchase')
plt.savefig('dow_vs_purchase')

在这里插入图片描述

明显地,一周工作时间同婚姻情况,并不是良好的预测因素。

若存在样本数据不平衡有必要干预吗?

样本数据不平衡性致使模型“耍小聪明”,故意偏向预测样本中概率大的可能性,需要解决。

如何解决

1)减少样本偏多方的样本数量。

2)使用SMOTE过采样,生成模拟数据,增补样本偏少方样本数量。

SMOTE过采样

使用SMOTE算法(合成少数过采样技术)对已经开户的用户进行上采样。 在高层次上,SMOTE:

通过从次要类(已经开户的用户)创建合成样本而不是创建副本来工作。

随机选择一个k-最近邻居并使用它来创建一个类似但随机调整的新观察结果。

cat_vars=['job','marital','education','default','housing','loan','contact','month','day_of_week','poutcome']
for var in cat_vars:
    cat_list = pd.get_dummies(data[var], prefix=var)
    data=data.join(cat_list)
data_final=data.drop(cat_vars, axis=1)

使用如下命令安装:

conda install -c conda-forge imbalanced-learn

X = data_final.loc[:, data_final.columns != 'y']
y = data_final.loc[:, data_final.columns == 'y'].values.ravel()

from imblearn.over_sampling import SMOTE
os = SMOTE(random_state=0)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=0)
columns = X_train.columns
os_data_X,os_data_y=os.fit_sample(X_train, y_train)
os_data_X = pd.DataFrame(data=os_data_X,columns=columns )
os_data_y= pd.DataFrame(data=os_data_y,columns=['y'])
# we can Check the numbers of our data
print("过采样以后的数据量: ",len(os_data_X))
print("未开户的用户数量: ",len(os_data_y[os_data_y['y']==0]))
print("开户的用户数量: ",len(os_data_y[os_data_y['y']==1]))
print("未开户的用户数量的百分比: ",len(os_data_y[os_data_y['y']==0])/len(os_data_X))
print("开户的用户数量的百分比: ",len(os_data_y[os_data_y['y']==1])/len(os_data_X))

过采样以后的数据量: 51134

未开户的用户数量: 25567

开户的用户数量: 25567

未开户的用户数量的百分比: 0.5

开户的用户数量的百分比: 0.5

仅干预训练数据,不可干预 test_X,test_y 。

from sklearn.linear_model import LogisticRegression
from sklearn import metrics
#X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=0)
logreg = LogisticRegression()
logreg.fit(os_data_X, os_data_y.values.reshape(-1))

拟合完,预测

y_pred = logreg.predict(X_test)
print('在测试数据集上面的预测准确率: {:.2f}'.format(logreg.score(X_test, y_test)))

在测试数据集上面的预测准确率: 0.89

模型评估指标

from sklearn.metrics import classification_report
print(classification_report(y_test, y_pred))

在这里插入图片描述

  1. Precision:准确率,即预测为正样本的样本中,真正为正样本的比例。
  2. Recall:查全率,即所有实际为正样本的样本中,被预测为正样本的比例。
  3. F1-Score:F1分数,是Precision和Recall的调和平均数,是一个综合的评价指标。
  4. support:各分类样本的数量或测试集样本的总数量

分类问题中的假阳率问题

假阳率(False Positive Rate)是指在预测结果为正例的情况下,实际上是负例的比例。在机器学习中,假阳率通常与真阳性率(True Positive Rate)一起用于评估二分类模型的性能。 计算假阳率的方法是,将预测为正例的样本数量除以所有的负例样本数量。 在实际应用中,假阳率高的模型可能会导致过多的误判,因此需要尽可能降低模型的假阳率。

假阳率主要出现在分类问题中。在二分类问题中,假阳率是指将负例预测为正例的比例。在多分类问题中,假阳率是指将其他类别预测为某个特定类别的比例。在评估分类模型的性能时,假阳率是一个重要的指标,特别是在模型应用于关键决策时。例如,在医疗诊断中,高假阳率可能会导致对病人进行不必要的治疗或手术,因此需要尽可能降低模型的假阳率。

图像分析假阳率

from sklearn.metrics import roc_auc_score
from sklearn.metrics import roc_curve
logit_roc_auc = roc_auc_score(y_test, logreg.predict(X_test))
fpr, tpr, thresholds = roc_curve(y_test, logreg.predict_proba(X_test)[:,1])
plt.figure()
plt.plot(fpr, tpr, label='Logistic Regression (area = %0.2f)' % logit_roc_auc)
plt.plot([0, 1], [0, 1],'r--')
plt.xlim([0.0, 1.0])
plt.ylim([0.0, 1.05])
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.title('Receiver operating characteristic')
plt.legend(loc="lower right")
plt.savefig('Log_ROC')
plt.show()

在这里插入图片描述

观察图像,曲线越趋近(0,1)坐标,表示假阳率越低,模型效果越好。无限趋近(0,1)坐标就几乎是无假阳率。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/635787.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

Building a Cloud Based Data Warehouse on Google Big Query Using Qlik Compose

Learn how to build a cloud based data warehouse using Qlik Compose on Google Big Query How to Build Data Integration Pipelines with Qlik and Databricks - YouTube Google BigQuery是一个具有成本效益、高度可扩展的无服务器数据仓库&#xff0c;专为业务敏捷性而设…

概率图简介

引言 本文介绍概率图模型的部分基础知识&#xff0c;希望学习完本文之后能更好地理解HMM和CRF模型。 概率论基础 本节简单回顾一下相关的概率论知识&#xff0c;概率论有两条重要的基本规则。 分别为乘法规则(product rule)和加和规则(sum rule)&#xff0c;假设有两个随机…

chatgpt赋能python:Python3.9.7安装指南

Python 3.9.7安装指南 Python是一种高级编程语言&#xff0c;得到了越来越多的使用&#xff0c;并且在机器学习、数据科学和网络开发中变得越来越重要。本篇文章将向大家介绍如何安装Python 3.9.7版本。 下载Python 3.9.7 首先&#xff0c;我们需要下载Python 3.9.7。你可以…

chatgpt赋能python:Python怎么安装Flask

Python怎么安装Flask Python是一种高级编程语言&#xff0c;常用于 Web 开发、人工智能、机器学习等领域。同时&#xff0c;Flask也是一个十分著名的Python Web框架&#xff0c;具有灵活、轻量级、易于扩展等特点。那么&#xff0c;如何在Python环境中安装Flask呢&#xff1f;…

chatgpt赋能python:Python安装PySpark:从入门到精通

Python安装PySpark&#xff1a;从入门到精通 PySpark是使用Python编写的Apache Spark API。它提供了一个Python接口来与Spark的分布式计算引擎进行交互。本文将介绍如何在Python中安装PySpark。 环境准备 在安装PySpark之前&#xff0c;您需要先安装以下依赖项&#xff1a; …

chatgpt赋能python:如何安装Python3.4

如何安装Python 3.4 简介 Python是一种流行的编程语言。它易于学习&#xff0c;具有可读性&#xff0c;且适用于多种用例。Python的版本非常多&#xff0c;但是Python 3.4是最新的稳定版本之一。 在本文中&#xff0c;我们将介绍如何更轻松地安装Python 3.4。 步骤 安装Py…

NLP学习笔记七-多层RNN和双向RNN

NLP学习笔记七-多层RNN和双向RNN 接着之前写的博客内容&#xff0c;多层RNN&#xff0c;其实就是在&#xff0c;simple RNN的基础上&#xff0c;再套一层或多层RNN单元。 看如下网络结构图&#xff1a; 上图中A就是表示一个RNN网络&#xff0c;这里&#xff0c;其实有一个疑…

chatgpt赋能python:Python与前端连接:使用Python的Web框架构建后端API

Python与前端连接&#xff1a;使用Python的Web框架构建后端API Python是一种强大的编程语言&#xff0c;越来越受到开发者的欢迎。但是&#xff0c;对于Web开发&#xff0c;Python并不是一种前端语言。那么&#xff0c;如何将Python的后端与前端连接起来&#xff1f;本文将介绍…

Java ~ Reference ~ Cleaner【总结】

前言 文章 相关系列&#xff1a;《Java ~ Reference【目录】》&#xff08;持续更新&#xff09;相关系列&#xff1a;《Java ~ Reference ~ Cleaner【源码】》&#xff08;学习过程/多有漏误/仅作参考/不再更新&#xff09;相关系列&#xff1a;《Java ~ Reference ~ Cleaner…

[java]关于Session关于Token关于JWT

目录 关于Session 关于Token 关于JWT 关于Session HTTP协议是一种无状态协议&#xff0c;即&#xff1a;当某个客户端向服务器发起请求&#xff0c;服务器端进行处理&#xff0c;后续&#xff0c;此客户端再次发起请求&#xff0c;服务器端并不能直接知道它就是此前来访过的…

chatgpt赋能python:Python怎么多行输入?教你高效开发!

Python怎么多行输入&#xff1f;教你高效开发&#xff01; 1. 介绍 Python是一种可读性高、可编程性强、拥有丰富的第三方模块和库的高级编程语言。作为典型的解释型语言&#xff0c;它可在多个平台上进行开发和运行&#xff0c;凭借其优雅、简洁、高效的语法风格和强大的功能…

Linux下C/C++ 多线程SSH扫描与暴力攻击

Secure Shell&#xff08;安全外壳协议&#xff0c;简称SSH&#xff09;是一种加密的网络传输协议&#xff0c;可在不安全的网络中为网络服务提供安全的传输环境。SSH通过在网络中建立安全隧道来实现SSH客户端与服务器之间的连接。 为什么需要SSH 如果没有SSH&#xff0c;绝大…

chatgpt赋能python:Python怎么安装skimage?

Python怎么安装skimage&#xff1f; 如果你之前使用Python编程&#xff0c;你可能会遇到需要安装第三方库的情况。对于图像处理任务&#xff0c;你可能需要用到scikit-image&#xff08;也称为skimage&#xff09;这个库。本文将提供一个详细的指南来安装skimage。 1. 确保你…

【JVM篇】类加载过程详解

目录 1、类加载过程概述 2、加载 3、连接 3.1 验证 3.1.1 文件格式验证 3.1.2 元数据验证 3.1.3 字节码验证 3.1.4 符号引用验证 3.2 准备 3.3 解析 4、初始化 1、类加载过程概述 想必大家一般在网上看类加载过程的资料时&#xff0c;通常资料只会将类加载过程概括…

OMG--DDS(Data Distribution Service)

OMG--DDS&#xff08;Data Distribution Service&#xff09; 1 介绍1.1 概述1.2 OMG 涉及的规范 2 内容概述介绍目标 Data-Centric Publish-Subscribe (DCPS) 以数据为中心的发布-订阅概要Platform Independent Model (PIM) 平台独立模型格式和约定概念图总体概念模型PIM 描述…

ChatGPT工作提效之数据可视化大屏组件Echarts的实战方案(大数据量加载、伪3D饼图、地图各省cp中心坐标属性、map3D材质)

ChatGPT工作提效系列文章目录 ChatGPT工作提效之初探路径独孤九剑遇强则强ChatGPT工作提效之在程序开发中的巧劲和指令(创建MySQL语句、PHP语句、Javascript用法、python的交互)ChatGPT工作提效之生成开发需求和报价单并转为Excel格式ChatGPT工作提效之小鹅通二次开发批量API对…

【电路】电路与电子技术基础 课堂笔记 第7章 晶体管放大电路

7.1 放大的概念 7.1.1 放大电路基础 放大电路可以将电信号不失真地进行放大&#xff0c;而且是幅度放大&#xff1b; 本质上&#xff0c;放大是对能量进行控制和转换&#xff0c; 由一个能量较小的输入信号控制直流电源&#xff0c; 将直流电源的能量转换成与输入信号频率…

yolov8量化部署(基于openvino和tensorrt)

yolov8 openvino量化部署 环境配置&#xff1a; pip install ultralytics && pip install openvino-dev将pytorch模型转为openvino模型: from ultralytics import YOLO# Load a model model YOLO("./yolov8n.pt") # load an official model# Export the…

S7-200 PLC编程软件介绍

更多关于西门子S7-200PLC内容请查看&#xff1a;西门子200系列PLC学习课程大纲(课程筹备中) 西门子200PLC编程软件采用的是STEP 7-Micro/WIN 软件。它可以进行编写程序&#xff0c;PLC程序下载与上传&#xff0c;编程向导&#xff0c;程序编译&#xff0c;PLC程序监控等等功能…

软件工程开发文档写作教程(12)—概要设计书的编制目标

本文原创作者&#xff1a;谷哥的小弟作者博客地址&#xff1a;http://blog.csdn.net/lfdfhl本文参考资料&#xff1a;电子工业出版社《软件文档写作教程》 马平&#xff0c;黄冬梅编著 概要设计书概述 《概要设计说明书》又称为《系统设计说明书》&#xff0c;编制的目的是说明…