前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >python 数据分析基础 day19-使用statsmodels进行逻辑回归

python 数据分析基础 day19-使用statsmodels进行逻辑回归

作者头像
billyang916
发布2018-05-02 10:18:16
4.8K0
发布2018-05-02 10:18:16
举报
文章被收录于专栏:python读书笔记python读书笔记

今天是读《python数据分析基础》的第19天,读书笔记内容为使用statsmodels进行逻辑回归。 以下代码将按数据清洗、训练模型、得出测试集的预测值这三个步骤展示 逻辑回归模型的使用。

注: 1.数据来源于https://github.com/cbrownley/foundations-for-analytics-with-python/tree/master/statistics/churn.csv 2.使用statsmodels构建逻辑回归模型之前,需要手动为自变量添加常数项

代码语言:javascript
复制
#使用逻辑回归预测客户流失概率

import pandas as pd
import numpy as np
import statsmodels.api as sma 

#导入数据
inputCsv='数据路径'
churn=pd.read_csv(inputCsv)


#数据预处理
#将列标题的空格替换为下划线,将引号和问号去除,标题字母变为小写
churn.columns=churn.columns.str.replace(' ','_').str.replace('\'','').str.strip('?').str.lower()
#将churn字段值中'.'删除,
churn.churn=churn.churn.str.strip('.')
#print(churn.head(5))
#新增一个字段,将churn字段转换为01编码字段
churn['churn01']=np.where(churn.churn=='True',1,0)
#对字段intl_plan及vmail_plan进行独热编码(新增虚拟变量)
intl_plan_dummy=pd.get_dummies(churn.intl_plan,prefix='intl_plan')
vmail_plan_dummy=pd.get_dummies(churn.vmail_plan,prefix='vmail_plan')
#添加常数项及生成自变量和因变量
churnInd=sma.add_constant(churn[churn.columns.difference(['intl_plan','vmail_plan','churn01','churn','state','phone','account_length','area_code'])].join(intl_plan_dummy.intl_plan_yes).join(vmail_plan_dummy.vmail_plan_yes))
churnDep=churn['churn01']


#将数据划分为训练集和测试集,训练集为第一行至倒数第10行,测试集为最后10行
churnIndTrain=churnInd.iloc[0:-10,:]
churnDepTrain=churnDep.iloc[0:-10]
churnIndTest=churnInd.tail(10)


#根据训练集训练获取模型参数
lr=sma.Logit(churnDepTrain,churnIndTrain)
result=lr.fit()
print(result.summary2())


#根据模型获取测试集结果
predictedValue=lr.fit().predict(churnIndTest)
compare=pd.DataFrame({'predictedValue':predictedValue,'actualValue':churnDep.tail(10)})
print(compare)
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018.04.01 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档