員工離職預測


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%。實際的數據並不會如此友好,想要達到很高的准確率非常困難。最后,本次項目雖然簡單,但是通過做本項目可以熟悉回顧數據項目的流程和基本思路。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM