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

3、逻辑回归


3.1、理论部分

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

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

逻辑回归这个名字不能体现什么,从公式上解读:称为对数几率回归
l o g p 1 − p = w ⋅ x + b log\frac{p}{1-p} = w·x+b log1pp=wx+b
整理后得到 p = e ( w ⋅ x + b ) 1 + e ( w ⋅ x + b ) p= \frac{e^{(w·x+b)}}{1+e^{(w·x+b)}} p=1+e(wx+b)e(wx+b)
进一步整理成最终形式 f ( x ) = 1 1 + e − ( w ⋅ x + b ) f(x) = \frac{1}{1 + e^{-(w·x+b)}} f(x)=1+e(wx+b)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 =<x^{(0)},x^{(1)},x^{(2)}>^T θT=<θ(0),θ(1),θ(2)>,x=<x(0),x(1),x(2)>T,(1,3)(3,1)得到一个1×1结果。

对文中向量上下角标解释:带上角标的,比如 Θ ( j ) Θ^{(j)} Θ(j)是向量Θ的第j个维度值, Θ i Θ_i Θi表示第i个Θ样本。维度范围:R∈N,样本数量最大为n。

逻辑回归的损失函数

在这里插入图片描述

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

应用场景:

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

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)坐标就几乎是无假阳率。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

来杯Sherry

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

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

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

打赏作者

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

抵扣说明:

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

余额充值