回归分析是通过建立模型来研究变量之间相互关系的密切程度、结构状态及进行模型预测的一种有效工具。
对于二分类的Logistic回归,因变量y只有“是、否”两个取值,记为1和0。假设在自变量x1,x2,…,xp作用下,y取“是”的概率是p,则取“否”的概率是1-p,研究的是当y取“是”发生的概率p与自变量x1,x2,…,xp的关系。
二分类Logistic回归模型的原理如下:
1. Logistic函数
Logistic回归模型中的因变量的只有1-0(如是和否、发生和不发生)两种取值。假设在p个独立自变量x1,x2,…,xp作用下,记y取1的概率是p=P(y=1|X),取0概率是1-p,取1和取0的概率之比为p/(1-p),称为事件的优势比(odds),对odds取自然对数即得Logistic变换Logit(p)=ln[p/(1-p)]。
令$$Logit(p)=ln[\frac{p}{1-p}]=z$$则$$p=\frac{1}{1+e^{-z}}$$即为Logistic函数.
当p在(0,1)之间变化时,odds的取值范围是(0,+∞),则ln[p/(1-p)]的取值范围是(-∞,+∞)。
2. Logistic回归模型
Logistic回归模型是建立ln[p/(1-p)]与自变量的线性回归模型。
Logistic回归模型为: $$ln\frac{p}{1-p}=\beta_0+{\beta_1}x_1+...+{\beta_p}x_p+\epsilon$$
因为ln[p/(1-p)]的取值范围是(-∞,+∞),这样,自变量x1,x2,…,xp可在任意范围内取值。
记$$g(x)=\beta_0+{\beta_1}x_1+...+{\beta_p}x_p+\epsilon$$得到:$$p=P(y=1|X)=\frac{1}{1+e^{-g(x)}}$$
$$1-p=P(y=0|X)=\frac{1}{1+e^{g(x)}}$$3. Logistic回归模型解释
$$\frac{p}{1-p}=e^{\beta_0+{\beta_1}x_1+...+{\beta_p}x_p+\epsilon}$$
βi:某自变量Xi变化一单位时,y=1与y=0发生概率之比的对数的变化值。
以以下某银行贷款拖欠率数据为例,我们想要知道贷款拖欠率与哪些因素有关
import pandas as pd
#参数初始化
filename = 'data/bankloan.xls'
data = pd.read_excel(filename)
x = data.iloc[:,:8].as_matrix()
y = data.iloc[:,8].as_matrix()
data.head()
年龄 | 教育 | 工龄 | 地址 | 收入 | 负债率 | 信用卡负债 | 其他负债 | 违约 | |
---|---|---|---|---|---|---|---|---|---|
0 | 41 | 3 | 17 | 12 | 176 | 9.3 | 11.359392 | 5.008608 | 1 |
1 | 27 | 1 | 10 | 6 | 31 | 17.3 | 1.362202 | 4.000798 | 0 |
2 | 40 | 1 | 15 | 14 | 55 | 5.5 | 0.856075 | 2.168925 | 0 |
3 | 41 | 1 | 15 | 14 | 120 | 2.9 | 2.658720 | 0.821280 | 0 |
4 | 24 | 2 | 2 | 0 | 28 | 17.3 | 1.787436 | 3.056564 | 1 |
利用Scikit-Learn对这个数据进行逻辑回归分析。
# 导入包
from sklearn.linear_model import LogisticRegression as LR
from sklearn.linear_model import RandomizedLogisticRegression as RLR
rlr = RLR() #建立随机逻辑回归模型,筛选变量
rlr.fit(x, y) #训练模型
rlr.get_support() #获取特征筛选结果,也可以通过.scores_方法获取各个特征的分数
print('通过随机逻辑回归模型筛选特征结束。')
通过随机逻辑回归模型筛选特征结束。
print(u'有效特征为:%s' % ','.join(data.columns[rlr.get_support()]))
有效特征为:工龄,地址,负债率,信用卡负债
C:\Anaconda3\lib\site-packages\pandas\indexes\base.py:1275: VisibleDeprecationWarning: boolean index did not match indexed array along dimension 0; dimension is 9 but corresponding boolean dimension is 8 result = getitem(key)
这样,我们就得到了对违约有预测作用的变量。接下来,我们利用这些变量建模,并计算给出模型的平均正确率。
x = data[data.columns[rlr.get_support()]].as_matrix() #筛选好特征
lr = LR() #建立logistic模型
lr.fit(x, y) #用筛选后的特征数据来训练模型
print(u'逻辑回归模型训练结束。')
print(u'模型的平均正确率为:%s' % lr.score(x, y)) #给出模型的平均正确率,
C:\Anaconda3\lib\site-packages\pandas\indexes\base.py:1275: VisibleDeprecationWarning: boolean index did not match indexed array along dimension 0; dimension is 9 but corresponding boolean dimension is 8 result = getitem(key)
逻辑回归模型训练结束。 模型的平均正确率为:0.814285714286