我们的任务是帮助人事部门理解员工为何离职, 预测一个员工离职的可能性. 数据来源: 数据
提取码:3zon

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as matplot
import seaborn as sns
%matplotlib inline

数据读取

f = pd.read_csv
# 读入数据到Pandas Dataframe "df"
df = pd.read_csv('HR_comma_sep.csv', index_col=None)

数据预处理

# 检测是否有缺失数据
df.isnull().any()
# 数据的样例
df.head()# 重命名
df = df.rename(columns={'satisfaction_level': 'satisfaction', 'last_evaluation': 'evaluation','number_project': 'projectCount','average_montly_hours': 'averageMonthlyHours','time_spend_company': 'yearsAtCompany','Work_accident': 'workAccident','promotion_last_5years': 'promotion','sales' : 'department','left' : 'turnover'})# 将预测标签‘是否离职’放在第一列
front = df['turnover']
df.drop(labels=['turnover'], axis=1, inplace = True) # 。如果手动设定为True(默认为False),那么原数组直接就被替换。也就是说,采用inplace=True之后,原数组名对应的内存值直接改变
df.insert(0, 'turnover', front) # loc, column, value
df.head()

数据统计分析

# 共14999个样本,每一个样本中包含10个特征
df.shape# 特征数据类型.
df.dtypes# 离职率
turnover_rate = df.turnover.value_counts() / len(df)
turnover_rate# 显示统计数据
df.describe()# 分组的平均数据统计.   以结果分组进行数据统计
turnover_Summary = df.groupby('turnover')
turnover_Summary.mean()


相关性分析

  • 正相关的特征:

    • projectCount VS evaluation: 0.349333
    • projectCount VS averageMonthlyHours: 0.417211
    • averageMonthlyHours VS evaluation: 0.339742
  • 负相关的特征:
    • satisfaction VS turnover: -0.388375
      思考:
  • 什么特征的影响最大?
  • 什么特征之间相关性最大?
# 相关性矩阵
corr = df.corr()
sns.heatmap(corr, xticklabels=corr.columns.values,yticklabels=corr.columns.values)corr

# 比较离职和未离职员工的满意度
emp_population = df['satisfaction'][df['turnover'] == 0].mean()
emp_turnover_satisfaction = df[df['turnover']==1]['satisfaction'].mean()print( '未离职员工满意度: ' + str(emp_population))
print( '离职员工满意度: ' + str(emp_turnover_satisfaction) )

进行 T-Test

进行一个 t-test, 看离职员工的满意度是不是和未离职员工的满意度明显不同

import scipy.stats as stats
# 满意度的t-Test
stats.ttest_1samp(a = df[df['turnover']==1]['satisfaction'], # 离职员工的满意度样本popmean = emp_population)  # 未离职员工的满意度均值

T-Test 显示pvalue (0) 非常小, 所以他们之间是显著不同的

degree_freedom = len(df[df['turnover']==1])
# 临界值
LQ = stats.t.ppf(0.025,degree_freedom)  # 95%致信区间的左边界
RQ = stats.t.ppf(0.975,degree_freedom)  # 95%致信区间的右边界
print ('The t-分布 左边界: ' + str(LQ))
print ('The t-分布 右边界: ' + str(RQ))
plt.rcParams['font.sans-serif']=['SimHei']   # 用来正常显示中文标签
plt.rcParams['axes.unicode_minus'] = False   # 用来正常显示负号
# 工作评价的概率密度函数估计
fig = plt.figure(figsize=(15,4),)
ax=sns.kdeplot(df.loc[(df['turnover'] == 0),'evaluation'] , color='b',shade=True,label='no turnover')
ax=sns.kdeplot(df.loc[(df['turnover'] == 1),'evaluation'] , color='r',shade=True, label='turnover')
ax.set(xlabel='工作评价', ylabel='频率')
plt.title('工作评价的概率密度函数 - 离职 V.S. 未离职')

# 月平均工作时长概率密度函数估计
fig = plt.figure(figsize=(15,4))
ax=sns.kdeplot(df.loc[(df['turnover'] == 0),'averageMonthlyHours'] , color='b',shade=True, label='no turnover')
ax=sns.kdeplot(df.loc[(df['turnover'] == 1),'averageMonthlyHours'] , color='r',shade=True, label='turnover')
ax.set(xlabel='月工作时长(时)', ylabel='频率')
plt.title('月工作时长(时) - 离职 V.S. 未离职')

# 员工满意度概率密度函数估计
fig = plt.figure(figsize=(15,4))
ax=sns.kdeplot(df.loc[(df['turnover'] == 0),'satisfaction'] , color='b',shade=True, label='no turnover')
ax=sns.kdeplot(df.loc[(df['turnover'] == 1),'satisfaction'] , color='r',shade=True, label='turnover')
plt.title('员工满意度 - 离职 V.S. 未离职')

from sklearn.preprocessing import LabelEncoder
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score, classification_report, precision_score, recall_score, confusion_matrix, precision_recall_curve# 将string类型转换为整数类型
# 通过pandas里面的 category数据类型,可以很方便的或者该编码
# 我们可以通过赋值新的列,保存其对应的code
# 通过这种方法可以舒服的数据,便于以后的数据分析以及整理
df["department"] = df["department"].astype('category').cat.codes
df["salary"] = df["salary"].astype('category').cat.codes# 产生X, y,即特征值与目标值
target_name = 'turnover'
X = df.drop('turnover', axis=1)
y = df[target_name]# 将数据分为训练和测试数据集
# 注意参数 stratify = y 意味着在产生训练和测试数据中, 离职的员工的百分比等于原来总的数据中的离职的员工的百分比
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.15, random_state=123, stratify=y)
# 显示前5行数据
df.head()

决策树和随机森林Decision Tree V.S. Random Forest

from sklearn.metrics import roc_auc_score
from sklearn.metrics import classification_report
from sklearn.ensemble import RandomForestClassifier
from sklearn import tree
from sklearn.tree import DecisionTreeClassifier
from sklearn.tree import export_graphviz
from six import StringIO
from IPython.display import Image
import pydotplus
# 实例化
dtree = tree.DecisionTreeClassifier(criterion='entropy',#max_depth=3, # 定义树的深度, 可以用来防止过拟合min_weight_fraction_leaf=0.01 # 定义叶子节点最少需要包含多少个样本(使用百分比表达), 防止过拟合)
# 训练
dtree = dtree.fit(X_train,y_train)
# 指标计算
dt_roc_auc = roc_auc_score(y_test, dtree.predict(X_test))
print ("决策树 AUC = %2.2f" % dt_roc_auc)
print(classification_report(y_test, dtree.predict(X_test)))

决策树可视化

# 需安装GraphViz和pydotplus进行决策树的可视化
# 特征向量
feature_names = df.columns[1:]
# 文件缓存
dot_data = StringIO()
# 将决策树导入到dot中
export_graphviz(dtree, out_file=dot_data,  filled=True, rounded=True,special_characters=True,feature_names = feature_names,class_names=['0','1'])
# 将生成的dot文件生成graph
graph = pydotplus.graph_from_dot_data(dot_data.getvalue())
# 将结果存入到png文件中
graph.write_png('diabetes.png')
# 显示
Image(graph.create_png())

决策树的特征重要性分析

# 获取特征重要性
importances = dtree.feature_importances_
# 获取特征名称
feat_names = df.drop(['turnover'],axis=1).columns
# 排序
indices = np.argsort(importances)[::-1]
# 绘图
plt.figure(figsize=(12,6))
plt.title("Feature importances by Decision Tree")
plt.bar(range(len(indices)), importances[indices], color='lightblue',  align="center")
plt.step(range(len(indices)), np.cumsum(importances[indices]), where='mid', label='Cumulative')
plt.xticks(range(len(indices)), feat_names[indices], rotation='vertical',fontsize=14)
plt.xlim([-1, len(indices)])
plt.show()

随机森林

# 实例化随机森林
rf = RandomForestClassifier(criterion='entropy',n_estimators=3, max_depth=None, # 定义树的深度, 可以用来防止过拟合min_samples_split=10, # 定义至少多少个样本的情况下才继续分叉#min_weight_fraction_leaf=0.02 # 定义叶子节点最少需要包含多少个样本(使用百分比表达), 防止过拟合)
# 模型训练
rf.fit(X_train, y_train)
# 计算指标参数
rf_roc_auc = roc_auc_score(y_test, rf.predict(X_test))
print ("随机森林 AUC = %2.2f" % rf_roc_auc)
print(classification_report(y_test, rf.predict(X_test)))

随机森林可视化

# Graphviz中未提供多棵树的绘制方法,所以我们遍历森林中的树,分别进行绘制
Estimators = rf.estimators_
# 遍历
for index, model in enumerate(Estimators):# 文件缓存dot_data = StringIO()# 将决策树导入到dot_data中export_graphviz(model , out_file=dot_data,feature_names=df.columns[1:],class_names=['0','1'],filled=True, rounded=True,special_characters=True)# 从数据中生成graphgraph = pydotplus.graph_from_dot_data(dot_data.getvalue())  # 将结果写入到png文件中graph.write_png('Rf{}.png'.format(index))# 绘制图像plt.figure(figsize = (20,20))plt.imshow(plt.imread('Rf{}.png'.format(index)))plt.axis('off')

随机森林特征分析

# 特征的重要程度
importances = rf.feature_importances_
# 特征名称
feat_names = df.drop(['turnover'],axis=1).columns
# 排序
indices = np.argsort(importances)[::-1]
# 绘图
plt.figure(figsize=(12,6))
plt.title("Feature importances by RandomForest")
plt.bar(range(len(indices)), importances[indices], color='lightblue',  align="center")
plt.step(range(len(indices)), np.cumsum(importances[indices]), where='mid', label='Cumulative')
plt.xticks(range(len(indices)), feat_names[indices], rotation='vertical',fontsize=14)
plt.xlim([-1, len(indices)])
plt.show()

ROC曲线

# ROC 图
from sklearn.metrics import roc_curve
# 计算ROC曲线
rf_fpr, rf_tpr, rf_thresholds = roc_curve(y_test, rf.predict_proba(X_test)[:,1])
dt_fpr, dt_tpr, dt_thresholds = roc_curve(y_test, dtree.predict_proba(X_test)[:,1])plt.figure()# 随机森林 ROC
plt.plot(rf_fpr, rf_tpr, label='Random Forest (area = %0.2f)' % rf_roc_auc)# 决策树 ROC
plt.plot(dt_fpr, dt_tpr, label='Decision Tree (area = %0.2f)' % dt_roc_auc)
# 绘图
plt.xlim([0.0, 1.0])
plt.ylim([0.0, 1.05])
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.title('ROC Graph')
plt.legend(loc="lower right")
plt.show()

机器学习实例-决策树和随机森林预测员工离职率相关推荐

  1. 机器学习中决策树的随机森林_决策树和随机森林在机器学习中的使用

    机器学习中决策树的随机森林 机器学习 (Machine Learning) Machine learning is an application of artificial intelligence ...

  2. python在Scikit-learn中用决策树和随机森林预测NBA获胜者 1

    最近我们被要求撰写关于预测NBA的研究报告,包括一些图形和统计输出.我们将以Scikit-learn的决策树和随机森林预测NBA获胜者.美国国家篮球协会(NBA)是北美主要的男子职业篮球联赛,被广泛认 ...

  3. python在Scikit-learn中用决策树和随机森林预测NBA获胜者

    在本文中,我们将以Scikit-learn的决策树和随机森林预测NBA获胜者.美国国家篮球协会(NBA)是北美主要的男子职业篮球联赛,被广泛认为是首屈一指的男子职业篮球联赛在世界上.它有30个团队(美 ...

  4. Logisitc Regression 预测员工离职率

    Logistic Regression 基础 Logistic Regression 沿用了 Linear Regression 的思路和想法,通过使用线性关系拟合得到真实的函数关系.同样的,如果模型 ...

  5. 机器学习利器——决策树和随机森林

    更多深度文章,请关注:https://yq.aliyun.com/cloud 决策树(Decision Tree)是在已知各种情况发生概率的基础上,通过构成决策树来求取净现值的期望值大于等于零的概率, ...

  6. 使用决策树和随机森林预测NBA获胜球队

    NBA比赛通常是难分胜负,有些时候会在最后一刻才会决出胜负,因此,预测哪支球队最后获胜会非常困难.通常你看好的球队恰恰在这场比赛中就会输给比它弱的球队. 许多预测比赛胜负的研究往往会有准确率上限,根据 ...

  7. 机器学习 之 决策树和随机森林

    决策树和随机森林 什么是决策树 决策树组成 节点的确定方法 决策树基本流程 决策树的常用参数 代码实现决策树之分类树 决策树不同max_depth的学习曲线 网格搜索在分类树上的应用 回归树中不同ma ...

  8. 机器学习:决策树与随机森林

    决策树与随机森林 决策树 基本原理 优缺点 优点 缺点 使用决策树对鸢尾花分类 随机森林 基本原理 优缺点 优点 缺点 葡萄酒数据集的随机森林分类 决策树 基本原理 决策树算法是一种基于实例的算法,常 ...

  9. 机器学习之决策树与随机森林

    目录 1.了解熵.条件熵.互信息的概念及公式 1.1.熵 1.2.条件熵 1.3.信息增益/互信息 2.了解决策树 2.1.了解决策树的概念和特点以及和熵的关系 2.2.了解树生成的过程 2.3.了解 ...

  10. Spark 机器学习 —— 从决策树到随机森林

    构造训练数据 import org.apache.spark.mllib.linalg.Vectors import org.apache.spark.mllib.regression.Labeled ...

最新文章

  1. 链表问题13——删除无序单链表中值重复出现的节点
  2. 九种浏览器端缓存机制知多少(转)
  3. 粒子群算法参数w的改进
  4. eclipse 在 Linux中常用命令,持续更新....
  5. 解决Can't connect to MySQL server on 'localhost' (10048)
  6. 解决python中join路径分隔符跨平台移植性
  7. 「小算法」回文数与数值合法性检验
  8. ChineseSemanticKB,面向中文处理的12类、百万规模的语义常用词库存
  9. 集福宝 支付宝2021年最新一款集福神器
  10. [论文阅读] Cost-Effective REgion-based Active Learning for Semantic Segmentation
  11. falsk 项目中日志设置
  12. pc构件生产线及设备_筑友装备的PC生产线
  13. js 兼容设置透明度
  14. 显示visual studio试用版序列号输入框小程序_Visual Studio 2008试用版的评估期已经结束 的解决方法...
  15. win7计算机锁频图片怎么设置,win7锁屏背景壁纸如何修改
  16. 我很高兴,很欣慰:)
  17. java正则表达式控制半角字符串输入
  18. 我的偶像王坚博士,一位执着的学者!
  19. 【魔方攻略】镜面魔方教程(原创)
  20. 在刀尖跳舞的喜马拉雅

热门文章

  1. Minecraft Mod开发:1-配置工作环境
  2. java 匹配冒号,java 冒号参数 java 获取冒号后面的参数(正则)实现代码
  3. Windows XP 启动过程jjhou
  4. jupyter notebook 之 pandas
  5. mysql distance_MySql中的一些小坑
  6. 河南省周口市安吉软件测试培训中心第一次软件测试课程-计算机基础理论论篇
  7. Internet连接共享只能上qq不能打开网页的问题解决
  8. TreeSet的两种排序方式
  9. 二分法解经典题目:切木头
  10. FoxMail上配置163邮箱的方法