#%%
#载入数据 、查看相关信息
import pandas as pd
import numpy as np
from sklearn.preprocessing import LabelEncoder print('第一步:加载、查看数据') file_path = r'D:\train\201905data\liwang.csv' band_data = pd.read_csv(file_path,encoding='UTF-8') band_data.info() band_data.shape #%%
#
print('第二步:清洗、处理数据,某些数据可以使用数据库处理数据代替') #数据清洗:缺失值处理:丢去、
#查看缺失值
band_data.isnull().sum band_data = band_data.dropna()
#band_data = band_data.drop(['state'],axis=1)
# 去除空格
band_data['voice_mail_plan'] = band_data['voice_mail_plan'].map(lambda x: x.strip())
band_data['intl_plan'] = band_data['intl_plan'].map(lambda x: x.strip())
band_data['churned'] = band_data['churned'].map(lambda x: x.strip())
band_data['voice_mail_plan'] = band_data['voice_mail_plan'].map({'no':0, 'yes':1})
band_data.intl_plan = band_data.intl_plan.map({'no':0, 'yes':1}) for column in band_data.columns:
if band_data[column].dtype == type(object):
le = LabelEncoder()
band_data[column] = le.fit_transform(band_data[column]) #band_data = band_data.drop(['phone_number'],axis=1)
#band_data['churned'] = band_data['churned'].replace([' True.',' False.'],[1,0])
#band_data['intl_plan'] = band_data['intl_plan'].replace([' yes',' no'],[1,0])
#band_data['voice_mail_plan'] = band_data['voice_mail_plan'].replace([' yes',' no'],[1,0]) #%%
# 模型 [重复、调优]
print('第三步:选择、训练模型') x = band_data.drop(['churned'],axis=1)
y = band_data['churned'] from sklearn import model_selection
train,test,t_train,t_test = model_selection.train_test_split(x,y,test_size=0.3,random_state=1) from sklearn import tree
model = tree.DecisionTreeClassifier(max_depth=2)
model.fit(train,t_train) fea_res = pd.DataFrame(x.columns,columns=['features'])
fea_res['importance'] = model.feature_importances_ t_name= band_data['churned'].value_counts()
t_name.index import graphviz import os
os.environ["PATH"] += os.pathsep + r'D:\software\developmentEnvironment\graphviz-2.38\release\bin' dot_data= tree.export_graphviz(model,out_file=None,feature_names=x.columns,max_depth=2,
class_names=t_name.index.astype(str),
filled=True, rounded=True,
special_characters=False)
graph = graphviz.Source(dot_data)
#graph
graph.render("dtr") #%%
print('第四步:查看、分析模型') #结果预测
res = model.predict(test) #混淆矩阵
from sklearn.metrics import confusion_matrix
confmat = confusion_matrix(t_test,res)
print(confmat) #分类指标 https://blog.csdn.net/akadiao/article/details/78788864
from sklearn.metrics import classification_report
print(classification_report(t_test,res)) #%%
print('第五步:保存模型') from sklearn.externals import joblib
joblib.dump(model,r'D:\train\201905data\mymodel.model') #%%
print('第六步:加载新数据、使用模型')
file_path_do = r'D:\train\201905data\do_liwang.csv' deal_data = pd.read_csv(file_path_do,encoding='UTF-8') #数据清洗:缺失值处理 deal_data = deal_data.dropna()
deal_data['voice_mail_plan'] = deal_data['voice_mail_plan'].map(lambda x: x.strip())
deal_data['intl_plan'] = deal_data['intl_plan'].map(lambda x: x.strip())
deal_data['churned'] = deal_data['churned'].map(lambda x: x.strip())
deal_data['voice_mail_plan'] = deal_data['voice_mail_plan'].map({'no':0, 'yes':1})
deal_data.intl_plan = deal_data.intl_plan.map({'no':0, 'yes':1}) for column in deal_data.columns:
if deal_data[column].dtype == type(object):
le = LabelEncoder()
deal_data[column] = le.fit_transform(deal_data[column])
#数据清洗 #加载模型
model_file_path = r'D:\train\201905data\mymodel.model'
deal_model = joblib.load(model_file_path)
#预测
res = deal_model.predict(deal_data.drop(['churned'],axis=1)) #%%
print('第七步:执行模型,提供数据')
result_file_path = r'D:\train\201905data\result_liwang.csv' deal_data.insert(1,'pre_result',res)
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. 【手撸一个ORM】第一步、实体约定和描述

    一.约定 数据实体必须实现 IEntity 接口,该接口定义了一个int类型的Id属性,既每个实体必须有一个名称为Id的自增主键. 若数据表的主键列名称不是Id,可以通过 [MyKey("主 ...

  2. centOS6.5 关闭关盖待机

    因为centOS安装在笔记本上面的,有时要把电脑放在一边,用SSH连接 所以需要关盖不休眠 用命令没找到怎么设置 后面在桌面电脑选项里面设置的,设置成黑屏或者不执行动作应该都是可以的.

  3. Hart协议

    官方https://fieldcommgroup.org/technologies/hart/documents-and-downloads-hart 参考网页http://www.eeworld.c ...

  4. DevExpress GridControl 控件二表连动

    using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; usin ...

  5. 专题《一》 mysql优化

    从今天开始,在这里记录面试会问的问题,针对java高级开发,架构师方向. 1.数据库设计要合理.开发经验不同  设计表水平不同  影响后面操作 三范式:1------------原子约束,每列不可分割 ...

  6. JAVA基础之项目分包

    个人理解: 项目分层分包适合多人开发合作的,最好一个界面设置一个view,同时注释一定设置好,按照顺序:从前向后进行传递参数,从后向前进行传递返回值来进行判断是否真正的执行了sql语句(可以不返回), ...

  7. SpringMVC的基础配置及视图定位

    概要 记录一下搭建SpringMVC框架的步骤 视图定位也就是改变jsp在项目中的路径 一.新建javaweb项目springmvc1,在lib中导入jar包 此项目上传了GitHub,方便去下载ja ...

  8. iPad开发简单介绍

    iPad开发最大的不同在于iPhone的就是屏幕控件的适配,以及横竖屏的旋转. Storyboard中得SizeClass的横竖屏配置,也不支持iPad开发. 1.在控制器中得到设备的旋转方向 在 i ...

  9. Windows Azure 配置Active Directory 主机(1)

    现在越来越多企业将自己业务系统迁移云端,方便公司日常运维管理.这篇文章将简单介绍一下,从 Windows Azure 虚拟网络上的虚拟机 (VM) 中的 Corp Active Directory 林 ...

  10. UWP开发:自动生成迷宫&自动寻路算法(1)

    (1)前端篇 首先,我们创建一个新的Universal Windows Platform程序.这些小方块是通过GridView来罗列的,这样可以避免MainPaga.xaml的<Rectangl ...