1 数据探索
import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns #导入数据集 df = pd.read_csv("G:\\employee_leave\\data.csv") df.head()
df.describe()
观察数据,数据表现较好,都没有缺失值
将特征重命名为中文,更为直观
#重命名列名 df.rename(columns={'satisfaction_level':'满意度', 'last_evaluation':'最新绩效评估', 'number_project':'项目数','average_montly_hours':'平均每月工时', 'time_spend_company':'在职时长','Work_accident':'工作事故', 'left':'是否离职','promotion_last_5years':'是否升职', 'sales':'岗位','salary':'薪资水平'}, inplace = True) df.head()
2 数据清洗
查看薪资水平都有那些,并用数值型进行替换,以便代入模型
df['薪资水平'].unique()
df['薪资水平'].replace({'low':1, 'medium':2, 'high':3},inplace = True)
3 特征工程
%matplotlib inline plt.rcParams['font.sans-serif']=['SimHei'] #正常显示中文标签 plt.rcParams['axes.unicode_minus']=False #用来正常显示负号 df_corr=df.corr() plt.figure(figsize=(10,10)) sns.heatmap(df_corr,annot=True,square=True,cmap="YlGnBu") #显示相关系数 #正方形 #黄绿蓝 plt.title('各属性相关性矩阵热图')
观察各特征与是否离职之间的关系,正数说明呈正相关,负数呈负相关
最新绩效评估影响最小,可以考虑暂时将其舍去
df_corr["是否离职"].sort_values(ascending=False)
4 模型选择
from sklearn.model_selection import train_test_split from sklearn.metrics import mean_squared_error from sklearn.cross_validation import cross_val_score from sklearn.tree import DecisionTreeClassifier from sklearn.ensemble import RandomForestClassifier
X= pd.get_dummies(df.drop(['是否离职','最新绩效评估'],axis=1)) y=df['是否离职']
将数据划分为两部分,一部分用来训练模型,一部分用来测试模型准确率
X_train,X_test,y_train,y_test= train_test_split(X,y, random_state=77,test_size=0.2) print('训练集数量:',X_train.shape[0]) print('测试集数量:',X_test.shape[0])
4.1 决策树
尝试用决策树进行训练,观察其得分
#决策树 tree = DecisionTreeClassifier() tree.fit(X_train, y_train) tree_pred = tree.predict(X_test) print('tree精确度 :',tree.score(X_test,y_test)) print('tree交叉验证得分:',cross_val_score(tree,X,y,cv=7).mean()) print('tree均方误差:',mean_squared_error(y_test,tree_pred))
4.2 随机森林
rmf=RandomForestClassifier(random_state=3) rmf.fit(X_train,y_train) rmf_pred = rmf.predict(X_test) print('rmf精确度:',rmf.score(X_test,y_test)) print('rmf交叉验证得分:',cross_val_score(rmf,X,y,cv=7).mean()) print('rmf均方误差:',mean_squared_error(y_test,rmf_pred))
将随机森林的特征按其重要性由小到大排序
# 将特征重要性从小到大排序 indices=np.argsort(rmf.feature_importances_)[::-1] print(indices)
5 参数调优
获取随机森林的最优参数
from sklearn.grid_search import GridSearchCV param_grid={'max_depth':np.arange(1,50)} grid=GridSearchCV(rmf,param_grid,cv=7) grid.fit(X_train,y_train)
6 训练模型与测试
按照最优参数训练模型
rmf_best=RandomForestClassifier(n_estimators=10,random_state=1, min_samples_split=2,oob_score=False, max_depth=19) rmf_best.fit(X_train,y_train) rmf_best_pred = rmf_best.predict(X_test) print('rmf精确度:',rmf_best.score(X_test,y_test)) print('rmf交叉验证得分:',cross_val_score(rmf_best,X,y,cv=7).mean()) print('rmf均方误差:',mean_squared_error(y_test,rmf_best_pred))
对测试集数据进行测试,并计算准确率
features = X_train.columns.values.tolist()
rmf_best = rmf_best.fit(X_train,y_train) predict_data = rmf_best.predict(X_test[features]) count = 0 for i in range(len(y_test)): if list(y_test)[i]==predict_data[i]: count += 1 score = count / len(y_test) score
7 总结
由于本次的数据集表现良好,不需对特征做多少处理,就能达到较高的分数,最后准确率高达98.9%。实际的数据并不会如此友好,想要达到很高的准确率非常困难。最后,本次项目虽然简单,但是通过做本项目可以熟悉回顾数据项目的流程和基本思路。