1. #%%
  2. #载入数据 、查看相关信息
  3. import pandas as pd
  4. import numpy as np
  5. from sklearn.preprocessing import LabelEncoder
  6.  
  7. print('第一步:加载、查看数据')
  8.  
  9. file_path = r'D:\train\201905data\liwang.csv'
  10.  
  11. band_data = pd.read_csv(file_path,encoding='UTF-8')
  12.  
  13. band_data.info()
  14.  
  15. band_data.shape
  16.  
  17. #%%
  18. #
  19. print('第二步:清洗、处理数据,某些数据可以使用数据库处理数据代替')
  20.  
  21. #数据清洗:缺失值处理:丢去、
  22. #查看缺失值
  23. band_data.isnull().sum
  24.  
  25. band_data = band_data.dropna()
  26. #band_data = band_data.drop(['state'],axis=1)
  27. # 去除空格
  28. band_data['voice_mail_plan'] = band_data['voice_mail_plan'].map(lambda x: x.strip())
  29. band_data['intl_plan'] = band_data['intl_plan'].map(lambda x: x.strip())
  30. band_data['churned'] = band_data['churned'].map(lambda x: x.strip())
  31. band_data['voice_mail_plan'] = band_data['voice_mail_plan'].map({'no':0, 'yes':1})
  32. band_data.intl_plan = band_data.intl_plan.map({'no':0, 'yes':1})
  33.  
  34. for column in band_data.columns:
  35. if band_data[column].dtype == type(object):
  36. le = LabelEncoder()
  37. band_data[column] = le.fit_transform(band_data[column])
  38.  
  39. #band_data = band_data.drop(['phone_number'],axis=1)
  40. #band_data['churned'] = band_data['churned'].replace([' True.',' False.'],[1,0])
  41. #band_data['intl_plan'] = band_data['intl_plan'].replace([' yes',' no'],[1,0])
  42. #band_data['voice_mail_plan'] = band_data['voice_mail_plan'].replace([' yes',' no'],[1,0])
  43.  
  44. #%%
  45. # 模型 [重复、调优]
  46. print('第三步:选择、训练模型')
  47.  
  48. x = band_data.drop(['churned'],axis=1)
  49. y = band_data['churned']
  50.  
  51. from sklearn import model_selection
  52. train,test,t_train,t_test = model_selection.train_test_split(x,y,test_size=0.3,random_state=1)
  53.  
  54. from sklearn import tree
  55. model = tree.DecisionTreeClassifier(max_depth=2)
  56. model.fit(train,t_train)
  57.  
  58. fea_res = pd.DataFrame(x.columns,columns=['features'])
  59. fea_res['importance'] = model.feature_importances_
  60.  
  61. t_name= band_data['churned'].value_counts()
  62. t_name.index
  63.  
  64. import graphviz
  65.  
  66. import os
  67. os.environ["PATH"] += os.pathsep + r'D:\software\developmentEnvironment\graphviz-2.38\release\bin'
  68.  
  69. dot_data= tree.export_graphviz(model,out_file=None,feature_names=x.columns,max_depth=2,
  70. class_names=t_name.index.astype(str),
  71. filled=True, rounded=True,
  72. special_characters=False)
  73. graph = graphviz.Source(dot_data)
  74. #graph
  75. graph.render("dtr")
  76.  
  77. #%%
  78. print('第四步:查看、分析模型')
  79.  
  80. #结果预测
  81. res = model.predict(test)
  82.  
  83. #混淆矩阵
  84. from sklearn.metrics import confusion_matrix
  85. confmat = confusion_matrix(t_test,res)
  86. print(confmat)
  87.  
  88. #分类指标 https://blog.csdn.net/akadiao/article/details/78788864
  89. from sklearn.metrics import classification_report
  90. print(classification_report(t_test,res))
  91.  
  92. #%%
  93. print('第五步:保存模型')
  94.  
  95. from sklearn.externals import joblib
  96. joblib.dump(model,r'D:\train\201905data\mymodel.model')
  97.  
  98. #%%
  99. print('第六步:加载新数据、使用模型')
  100. file_path_do = r'D:\train\201905data\do_liwang.csv'
  101.  
  102. deal_data = pd.read_csv(file_path_do,encoding='UTF-8')
  103.  
  104. #数据清洗:缺失值处理
  105.  
  106. deal_data = deal_data.dropna()
  107. deal_data['voice_mail_plan'] = deal_data['voice_mail_plan'].map(lambda x: x.strip())
  108. deal_data['intl_plan'] = deal_data['intl_plan'].map(lambda x: x.strip())
  109. deal_data['churned'] = deal_data['churned'].map(lambda x: x.strip())
  110. deal_data['voice_mail_plan'] = deal_data['voice_mail_plan'].map({'no':0, 'yes':1})
  111. deal_data.intl_plan = deal_data.intl_plan.map({'no':0, 'yes':1})
  112.  
  113. for column in deal_data.columns:
  114. if deal_data[column].dtype == type(object):
  115. le = LabelEncoder()
  116. deal_data[column] = le.fit_transform(deal_data[column])
  117. #数据清洗
  118.  
  119. #加载模型
  120. model_file_path = r'D:\train\201905data\mymodel.model'
  121. deal_model = joblib.load(model_file_path)
  122. #预测
  123. res = deal_model.predict(deal_data.drop(['churned'],axis=1))
  124.  
  125. #%%
  126. print('第七步:执行模型,提供数据')
  127. result_file_path = r'D:\train\201905data\result_liwang.csv'
  128.  
  129. deal_data.insert(1,'pre_result',res)
  130. deal_data[['state','pre_result']].to_csv(result_file_path,sep=',',index=True,encoding='UTF-8')

Python 建模步骤的更多相关文章

  1. Python学习步骤如何安排?

    一.清楚学习目标 无论是学习什么知识,都要有一个对学习目标的清楚认识. 只有这样才能朝着目标持续前进,少走弯路,从学习中得到不断的提升,享受python学习计划的过程. 二.基本python 知识学习 ...

  2. Linux系统下升级Python版本步骤(suse系统)

    Linux系统下升级Python版本步骤(suse系统) http://blog.csdn.net/lifengling1234/article/details/53536493

  3. 决策树python建模中的坑 :ValueError: Expected 2D array, got 1D array instead:

    决策树python建模中的坑 代码 #coding=utf-8 from sklearn.feature_extraction import DictVectorizerimport csvfrom ...

  4. odoo 14 python 单元测试步骤

    # odoo 14 python 单元测试步骤 # 一.在模块根目录创建tests目录 # 二.在tests目录下创建__init__.py文件 # 三.继承TransactionCase(Singl ...

  5. 逻辑回归--美国挑战者号飞船事故_同盾分数与多头借贷Python建模实战

    python信用评分卡(附代码,博主录制) https://study.163.com/course/introduction.htm?courseId=1005214003&utm_camp ...

  6. Python机器学习步骤

    推荐学习顺序 学习机器学习得有个步骤, 下面大家就能按照自己所需, 来探索这个网站. 图中请找到 "Start", 然后依次沿着箭头, 看看有没有不了解/没学过的地方, 接着, 就 ...

  7. 正态分布-python建模

    sklearn实战-乳腺癌细胞数据挖掘 https://study.163.com/course/introduction.htm?courseId=1005269003&utm_campai ...

  8. T分布在医药领域应用-python建模

    sklearn实战-乳腺癌细胞数据挖掘 https://study.163.com/course/introduction.htm?courseId=1005269003&utm_campai ...

  9. 下载及安装Python详细步骤

    安装python分三个步骤: *下载python *安装python *检查是否安装成功 1.下载Python (1)python下载地址https://www.python.org/download ...

随机推荐

  1. python进阶04 装饰器、描述器、常用内置装饰器

    python进阶04 装饰器.描述器.常用内置装饰器 一.装饰器 作用:能够给现有的函数增加功能 如何给一个现有的函数增加执行计数的功能 首先用类来添加新功能 def fun(): #首先我们定义一个 ...

  2. Jmeter4.0----设置集合点_并发(11)

    1.说明 LR中集合点可以设置多个虚拟用户等待到一个点,同时触发一个事务,以达到模拟真实环境下多个用户同时操作,实现性能测试的最终目的. jmeter中使用Synchronizing Timer实现L ...

  3. NET Core 2.0 使用支付宝

    ASP.NET Core 2.0 使用支付宝PC网站支付   前言 最近在使用ASP.NET Core来进行开发,刚好有个接入支付宝支付的需求,百度了一下没找到相关的资料,看了官方的SDK以及Demo ...

  4. LINUX中IPTABLES防火墙使用

    对于有公网IP的生产环境VPS,仅仅开放需要的端口,即采用ACL来控制IP和端口(Access Control List). 这里可以使用Linux防火墙netfilter的用户态工具 iptable ...

  5. C#知识点-StopWatch-计时

    目录 简单介绍 基本用法 结尾 简单介绍 Stopwatch 可以测量一个时间间隔的运行时间,也可以测量多个时间间隔的总运行时间.一般用来测量代码执行所用的时间或者计算性能数据,在优化代码性能上可以使 ...

  6. CSS中垂直水平居中

    方法一:使用flex布局,父级元素设置justify-content和align-items <div class="cont"> <div class=&quo ...

  7. Java中的switch语句——通过示例学习Java编程(8)

    作者:CHAITANYA SINGH 来源:https://www.koofun.com//pro/kfpostsdetail?kfpostsid=19 当我们在代码逻辑中有多个选项,而且需要为每个选 ...

  8. 使用AuthToken架构保护用户帐号验证Cookie的安全性

    在项目或者网站开发中,我们很多人很多时候喜欢使用微软的FormsAuthentication类的GetAuthCookie函数生成需要在访客客户端放置的帐号校验Cookie,这个本身没问题,但是很多人 ...

  9. 【extjs6学习笔记】Mastering Ext JS, 2nd Edition

    我不知道在别人看来,我是什么样的人:但在我自己看来,我不过就象是一个在海滨玩耍的小孩,为不时发现比寻常更为光滑的一块卵石或比寻常更为美丽的一片贝壳而沾沾自喜,而对于展现在我面前的浩瀚的真理的海洋,却全 ...

  10. HttpRunner环境搭建

    官方文档地址:http://cn.httprunner.org/官方源码地址:https://github.com/HttpRunner/HttpRunner HttpRunner 是一款面向 HTT ...