Python语言之概述建模步骤
从安 2019-06-11 来源 : 阅读 1600 评论 0

摘要:本篇文章主要讲述Python语言之概述建模步骤,希望阅读本篇文章以后大家有所收获,帮助大家对相关内容的理解更加深入。

本篇文章主要讲述Python语言之概述建模步骤,希望阅读本篇文章以后大家有所收获,帮助大家对相关内容的理解更加深入。

Python语言之概述建模步骤

#%%
#载入数据 、查看相关信息import pandas as pdimport numpy as npfrom  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/78788864from sklearn.metrics import classification_reportprint(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')

 

本文由职坐标整理发布,学习更多的相关知识,请关注职坐标IT知识库!

本文由 @从安 发布于职坐标。未经许可,禁止转载。
喜欢 | 0 不喜欢 | 1
看完这篇文章有何感觉?已经有1人表态,0%的人喜欢 快给朋友分享吧~
评论(0)
后参与评论

您输入的评论内容中包含违禁敏感词

我知道了

助您圆梦职场 匹配合适岗位
验证码手机号,获得海同独家IT培训资料
选择就业方向:
人工智能物联网
大数据开发/分析
人工智能Python
Java全栈开发
WEB前端+H5

请输入正确的手机号码

请输入正确的验证码

获取验证码

您今天的短信下发次数太多了,明天再试试吧!

提交

我们会在第一时间安排职业规划师联系您!

您也可以联系我们的职业规划师咨询:

小职老师的微信号:z_zhizuobiao
小职老师的微信号:z_zhizuobiao

版权所有 职坐标-一站式IT培训就业服务领导者 沪ICP备13042190号-4
上海海同信息科技有限公司 Copyright ©2015 www.zhizuobiao.com,All Rights Reserved.
 沪公网安备 31011502005948号    

©2015 www.zhizuobiao.com All Rights Reserved

208小时内训课程