員工離職案例預測--R語言--kaggle資料
阿新 • • 發佈:2018-11-12
需要安裝的包:
library(plyr) # Rmisc的關聯包,若同時需要載入dplyr包,必須先載入plyr包 library(dplyr) # filter() library(ggplot2) # ggplot() library(DT) # datatable() 建立互動式資料表 library(caret) # createDataPartition() 分層抽樣函式 library(rpart) # rpart() library(e1071) # naiveBayes() library(pROC) # roc() library(Rmisc) # multiplot() 分割繪圖區域
################### ============== 載入包 =================== ################# library(lattice) #繪圖基準包,柵欄 library(plyr) # Rmisc的關聯包,若同時需要載入dplyr包,必須先載入plyr包 library("dplyr") # filter() library(ggplot2) # ggplot() library(DT) # datatable() 建立互動式資料表 library(caret) # createDataPartition() 分層抽樣函式 library(rpart) # rpart() library(e1071) # naiveBayes() #library("pROC") # roc() library(pROC) library(Rmisc) # multiplot() 分割繪圖區域 ################### ============= 匯入資料 ================== ################# hr <- read.csv("/RStudio/workSpace2018/kaggle案例課程/員工離職預測\\HR_comma_sep.csv") hr <- read.csv("D:/RStudio/workSpace2018/kaggle案例精講課程/員工離職預測\\HR_comma_sepp.csv") #D:/RStudio/workSpace2018/kaggle案例課程/員工離職預測\\HR_comma_sep.csv #D:/RStudio/workSpace2018/kaggle案例精講課程/員工離職預測\\HR_comma_sepp.csv ################### ============= 描述性分析 ================== ############### str(hr) # 檢視資料的基本資料結構 summary(hr) # 計算資料的主要描述統計量 # 後續的個別模型需要目標變數必須為因子型,我們將其轉換為因子型 hr$left <- factor(hr$left, levels = c('0', '1')) ## 探索員工對公司滿意度、績效評估和月均工作時長與是否離職的關係 # 繪製對公司滿意度與是否離職的箱線圖 box_sat <- ggplot(hr, aes(x = left, y = satisfaction_level, fill = left)) + geom_boxplot() + theme_bw() + # 一種ggplot的主題 labs(x = 'left', y = 'satisfaction_level') # 設定橫縱座標標籤 box_sat # 繪製績效評估與是否離職的箱線圖 box_eva <- ggplot(hr, aes(x = left, y = last_evaluation, fill = left)) + geom_boxplot() + theme_bw() + labs(x = 'left', y = 'last_evaluation') box_eva # 繪製平均月工作時長與是否離職的箱線圖 box_mon <- ggplot(hr, aes(x = left, y = average_montly_hours, fill = left)) + geom_boxplot() + theme_bw() + labs(x = 'left', y = 'average_montly_hours') box_mon # 繪製員工在公司工作年限與是否離職的箱線圖 box_time <- ggplot(hr, aes(x = left, y = time_spend_company, fill = left)) + geom_boxplot() + theme_bw() + labs(x = 'left', y = 'time_spend_company') box_time # 合併這些圖形在一個繪圖區域,cols = 2的意思就是排版為一行二列 multiplot(box_sat, box_eva, box_mon, box_time, cols = 2) ## 探索參與專案個數、五年內有沒有升職和薪資與離職的關係 # 繪製參與專案個數條形圖時需要把此變數轉換為因子型 hr$number_project <- factor(hr$number_project, levels = c('2', '3', '4', '5', '6', '7')) # 繪製參與專案個數與是否離職的百分比堆積條形圖 bar_pro <- ggplot(hr, aes(x = number_project, fill = left)) + geom_bar(position = 'fill') + # position = 'fill'即繪製百分比堆積條形圖 theme_bw() + labs(x = 'left', y = 'number_project') bar_pro # 繪製5年內是否升職與是否離職的百分比堆積條形圖 bar_5years <- ggplot(hr, aes(x = as.factor(promotion_last_5years), fill = left)) + geom_bar(position = 'fill') + theme_bw() + labs(x = 'left', y = 'promotion_last_5years') bar_5years # 繪製薪資與是否離職的百分比堆積條形圖 bar_salary <- ggplot(hr, aes(x = salary, fill = left)) + geom_bar(position = 'fill') + theme_bw() + labs(x = 'left', y = 'salary') bar_salary # 合併這些圖形在一個繪圖區域,cols = 3的意思就是排版為一行三列 multiplot(bar_pro, bar_5years, bar_salary, cols = 3) ############## =============== 提取優秀員工 =========== ################### # filter()用來篩選符合條件的樣本 hr_model <- filter(hr, last_evaluation >= 0.70 | time_spend_company >= 4 | number_project > 5) ############### ============ 自定義交叉驗證方法 ========== ################## # 設定5折交叉驗證 method = ‘cv’是設定交叉驗證方法,number = 5意味著是5折交叉驗證 train_control <- trainControl(method = 'cv', number = 5) ################ =========== 分成抽樣 ============== ########################## set.seed(1234) # 設定隨機種子,為了使每次抽樣結果一致 # 根據資料的因變數進行7:3的分層抽樣,返回行索引向量 p = 0.7就意味著按照7:3進行抽樣, # list=F即不返回列表,返回向量 index <- createDataPartition(hr_model$left, p = 0.7, list = F) traindata <- hr_model[index, ] # 提取資料中的index所對應行索引的資料作為訓練集 testdata <- hr_model[-index, ] # 其餘的作為測試集 ##################### ============= 迴歸樹 ============= ##################### # 使用caret包中的trian函式對訓練集使用5折交叉的方法建立決策樹模型 # left ~.的意思是根據因變數與所有自變數建模;trCintrol是控制使用那種方法進行建模 # methon就是設定使用哪種演算法 rpartmodel <- train(left ~ ., data = traindata, trControl = train_control, method = 'rpart') # 利用rpartmodel模型對測試集進行預測,([-7]的意思就是剔除測試集的因變數這一列) pred_rpart <- predict(rpartmodel, testdata[-7]) # 建立混淆矩陣,positive=‘1’設定我們的正例為“1” con_rpart <- table(pred_rpart, testdata$left) con_rpart ################### ============ Naives Bayes =============== ################# nbmodel <- train(left ~ ., data = traindata, trControl = train_control, method = 'nb') pred_nb <- predict(nbmodel, testdata[-7]) con_nb <- table(pred_nb, testdata$left) con_nb ################### ================ ROC ==================== ################# # 使用roc函式時,預測的值必須是數值型 pred_rpart <- as.numeric(as.character(pred_rpart)) pred_nb <- as.numeric(as.character(pred_nb)) roc_rpart <- roc(testdata$left, pred_rpart) # 獲取後續畫圖時使用的資訊 #假正例率:(1-Specififity[真反例率]) Specificity <- roc_rpart$specificities # 為後續的橫縱座標軸奠基,真反例率 Sensitivity <- roc_rpart$sensitivities # 查全率 : sensitivities,也是真正例率 # 繪製ROC曲線 #我們只需要橫縱座標 NULL是為了宣告我們沒有用任何資料 p_rpart <- ggplot(data = NULL, aes(x = 1- Specificity, y = Sensitivity)) + geom_line(colour = 'red') + # 繪製ROC曲線 geom_abline() + # 繪製對角線 annotate('text', x = 0.4, y = 0.5, label = paste('AUC=', #text是宣告圖層上新增文字註釋 #‘3’是round函式裡面的引數,保留三位小數 round(roc_rpart$auc, 3))) + theme_bw() + # 在圖中(0.4,0.5)處新增AUC值 labs(x = '1 - Specificity', y = 'Sensitivities') # 設定橫縱座標軸標籤 p_rpart roc_nb <- roc(testdata$left, pred_nb) Specificity <- roc_nb$specificities Sensitivity <- roc_nb$sensitivities p_nb <- ggplot(data = NULL, aes(x = 1- Specificity, y = Sensitivity)) + geom_line(colour = 'red') + geom_abline() + annotate('text', x = 0.4, y = 0.5, label = paste('AUC=', round(roc_nb$auc, 3))) + theme_bw() + labs(x = '1 - Specificity', y = 'Sensitivities') p_nb ######################### ============= 應用 =============#################### # 使用迴歸樹模型預測分類的概率,type=‘prob’設定預測結果為離職的概率和不離職的概率 pred_end <- predict(rpartmodel, testdata[-7], type = 'prob') # 合併預測結果和預測概率結果 data_end <- cbind(round(pred_end, 3), pred_rpart) # 為預測結果表重新命名 names(data_end) <- c('pred.0', 'pred.1', 'pred') # 生成一個互動式資料表 datatable(data_end)