Capstone project: Providing data-driven suggestions for HR

Description and deliverables

This capstone project is an opportunity for you to analyze a dataset and build predictive models that can provide insights to the Human Resources (HR) department of a large consulting firm.

Upon completion, you will have two artifacts that you will be able to present to future employers. One is a brief one-page summary of this project that you will present to external stakeholders as the data professional in Salifort Motors. The other is a complete code notebook provided here. Based on your prior coursework, select one method to complete this project: use either a regression model or a machine learning model to predict whether an employee will leave the company. The exemplar following this actiivty shows both approaches, but you only need to do one.

In your deliverables, you will include the model evaluation (and interpretation if applicable), a data visualization(s) of your choice that is directly related to the question you ask, ethical considerations, and the resources you used to troubleshoot and find answers or solutions.

PACE stages

Screenshot 2022-08-04 5.47.37 PM.png

Pace: Plan

Consider the questions in your PACE Strategy Document to reflect on the Plan stage.

In this stage, consider the following:

Understand the business scenario and problem

The HR department at Salifort Motors wants to take some initiatives to improve employee satisfaction levels at the company. They collected data from employees, but now they don’t know what to do with it. They refer to you as a data analytics professional and ask you to provide data-driven suggestions based on your understanding of the data. They have the following question: what’s likely to make the employee leave the company?

Your goals in this project are to analyze the data collected by the HR department and to build a model that predicts whether or not an employee will leave the company.

If you can predict employees likely to quit, it might be possible to identify factors that contribute to their leaving. Because it is time-consuming and expensive to find, interview, and hire new employees, increasing employee retention will be beneficial to the company.

Familiarize yourself with the HR dataset

The dataset that you'll be using in this lab contains 15,000 rows and 10 columns for the variables listed below.

Note: you don't need to download any data to complete this lab. For more information about the data, refer to its source on Kaggle.

Variable Description
satisfaction_level Employee-reported job satisfaction level [0–1]
last_evaluation Score of employee's last performance review [0–1]
number_project Number of projects employee contributes to
average_monthly_hours Average number of hours employee worked per month
time_spend_company How long the employee has been with the company (years)
Work_accident Whether or not the employee experienced an accident while at work
left Whether or not the employee left the company
promotion_last_5years Whether or not the employee was promoted in the last 5 years
Department The employee's department
salary The employee's salary (U.S. dollars)

💭

Reflect on these questions as you complete the plan stage.

  • Who are your stakeholders for this project?
  • What are you trying to solve or accomplish?
  • What are your initial observations when you explore the data?
  • What resources do you find yourself using as you complete this stage? (Make sure to include the links.)
  • Do you have any ethical considerations in this stage?

[Double-click to enter your responses here.]

Step 1. Imports

  • Import packages
  • Load dataset

Import packages

In [5]:
# Import packages
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import classification_report, accuracy_score, precision_score, recall_score, f1_score, confusion_matrix, ConfusionMatrixDisplay

Load dataset

Pandas is used to read a dataset called HR_capstone_dataset.csv. As shown in this cell, the dataset has been automatically loaded in for you. You do not need to download the .csv file, or provide more code, in order to access the dataset and proceed with this lab. Please continue with this activity by completing the following instructions.

In [6]:
# RUN THIS CELL TO IMPORT YOUR DATA. 

# Load dataset into a dataframe
### YOUR CODE HERE ###
df0 = pd.read_csv("HR_capstone_dataset.csv")


# Display first few rows of the dataframe
# Load dataset into a dataframe
df0 = pd.read_csv("HR_capstone_dataset.csv")

# Display first few rows of the dataframe
df0.head()
Out[6]:
satisfaction_level last_evaluation number_project average_montly_hours time_spend_company Work_accident left promotion_last_5years Department salary
0 0.38 0.53 2 157 3 0 1 0 sales low
1 0.80 0.86 5 262 6 0 1 0 sales medium
2 0.11 0.88 7 272 4 0 1 0 sales medium
3 0.72 0.87 5 223 5 0 1 0 sales low
4 0.37 0.52 2 159 3 0 1 0 sales low

Step 2. Data Exploration (Initial EDA and data cleaning)

  • Understand your variables
  • Clean your dataset (missing data, redundant data, outliers)

Gather basic information about the data

In [7]:
# Gather basic information about the data
# Gather basic information about the data
df0.info()

# Gather descriptive statistics about the data
df0.describe()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 14999 entries, 0 to 14998
Data columns (total 10 columns):
 #   Column                 Non-Null Count  Dtype  
---  ------                 --------------  -----  
 0   satisfaction_level     14999 non-null  float64
 1   last_evaluation        14999 non-null  float64
 2   number_project         14999 non-null  int64  
 3   average_montly_hours   14999 non-null  int64  
 4   time_spend_company     14999 non-null  int64  
 5   Work_accident          14999 non-null  int64  
 6   left                   14999 non-null  int64  
 7   promotion_last_5years  14999 non-null  int64  
 8   Department             14999 non-null  object 
 9   salary                 14999 non-null  object 
dtypes: float64(2), int64(6), object(2)
memory usage: 1.1+ MB
Out[7]:
satisfaction_level last_evaluation number_project average_montly_hours time_spend_company Work_accident left promotion_last_5years
count 14999.000000 14999.000000 14999.000000 14999.000000 14999.000000 14999.000000 14999.000000 14999.000000
mean 0.612834 0.716102 3.803054 201.050337 3.498233 0.144610 0.238083 0.021268
std 0.248631 0.171169 1.232592 49.943099 1.460136 0.351719 0.425924 0.144281
min 0.090000 0.360000 2.000000 96.000000 2.000000 0.000000 0.000000 0.000000
25% 0.440000 0.560000 3.000000 156.000000 3.000000 0.000000 0.000000 0.000000
50% 0.640000 0.720000 4.000000 200.000000 3.000000 0.000000 0.000000 0.000000
75% 0.820000 0.870000 5.000000 245.000000 4.000000 0.000000 0.000000 0.000000
max 1.000000 1.000000 7.000000 310.000000 10.000000 1.000000 1.000000 1.000000

Gather descriptive statistics about the data

In [8]:
# Gather descriptive statistics about the data
# Gather descriptive statistics about the data
### YOUR CODE HERE ###
df0.describe()
Out[8]:
satisfaction_level last_evaluation number_project average_montly_hours time_spend_company Work_accident left promotion_last_5years
count 14999.000000 14999.000000 14999.000000 14999.000000 14999.000000 14999.000000 14999.000000 14999.000000
mean 0.612834 0.716102 3.803054 201.050337 3.498233 0.144610 0.238083 0.021268
std 0.248631 0.171169 1.232592 49.943099 1.460136 0.351719 0.425924 0.144281
min 0.090000 0.360000 2.000000 96.000000 2.000000 0.000000 0.000000 0.000000
25% 0.440000 0.560000 3.000000 156.000000 3.000000 0.000000 0.000000 0.000000
50% 0.640000 0.720000 4.000000 200.000000 3.000000 0.000000 0.000000 0.000000
75% 0.820000 0.870000 5.000000 245.000000 4.000000 0.000000 0.000000 0.000000
max 1.000000 1.000000 7.000000 310.000000 10.000000 1.000000 1.000000 1.000000

Rename columns

As a data cleaning step, rename the columns as needed. Standardize the column names so that they are all in snake_case, correct any column names that are misspelled, and make column names more concise as needed.

In [9]:
# Display all column names
# Display all column names
print(df0.columns)

# Rename columns as needed
df1 = df0.rename(columns={
    'Work_accident': 'work_accident',
    'average_montly_hours': 'average_monthly_hours',
    'time_spend_company': 'tenure',
    'Department': 'department'
})

# Display all column names after the update
print(df1.columns)
# Display all column names
print(df0.columns)

# Rename columns as needed
df1 = df0.rename(columns={
    'Work_accident': 'work_accident',
    'average_montly_hours': 'average_monthly_hours',
    'time_spend_company': 'tenure',
    'Department': 'department'
})

# Display all column names after the update
print(df1.columns)
Index(['satisfaction_level', 'last_evaluation', 'number_project',
       'average_montly_hours', 'time_spend_company', 'Work_accident', 'left',
       'promotion_last_5years', 'Department', 'salary'],
      dtype='object')
Index(['satisfaction_level', 'last_evaluation', 'number_project',
       'average_monthly_hours', 'tenure', 'work_accident', 'left',
       'promotion_last_5years', 'department', 'salary'],
      dtype='object')
Index(['satisfaction_level', 'last_evaluation', 'number_project',
       'average_montly_hours', 'time_spend_company', 'Work_accident', 'left',
       'promotion_last_5years', 'Department', 'salary'],
      dtype='object')
Index(['satisfaction_level', 'last_evaluation', 'number_project',
       'average_monthly_hours', 'tenure', 'work_accident', 'left',
       'promotion_last_5years', 'department', 'salary'],
      dtype='object')
In [11]:
# Rename columns as needed
# Rename columns as needed
### YOUR CODE HERE ###
df1 = df0.rename(columns={
    'Work_accident': 'work_accident',
    'average_montly_hours': 'average_monthly_hours',
    'time_spend_company': 'tenure',
    'Department': 'department'
})

# Display all column names after the update
### YOUR CODE HERE ###
print(df1.columns)


# Display all column names after the update
### YOUR CODE HERE ###
print(df1.columns)
Index(['satisfaction_level', 'last_evaluation', 'number_project',
       'average_monthly_hours', 'tenure', 'work_accident', 'left',
       'promotion_last_5years', 'department', 'salary'],
      dtype='object')
Index(['satisfaction_level', 'last_evaluation', 'number_project',
       'average_monthly_hours', 'tenure', 'work_accident', 'left',
       'promotion_last_5years', 'department', 'salary'],
      dtype='object')

Check missing values

Check for any missing values in the data.

In [13]:
# Check for missing values
print(df1.isnull().sum())
satisfaction_level       0
last_evaluation          0
number_project           0
average_monthly_hours    0
tenure                   0
work_accident            0
left                     0
promotion_last_5years    0
department               0
salary                   0
dtype: int64

Check duplicates

Check for any duplicate entries in the data.

In [14]:
# Check for duplicates
print("Number of duplicates:", df1.duplicated().sum())
Number of duplicates: 3008
In [15]:
# Inspect some rows containing duplicates as needed
df1[df1.duplicated()].head()
Out[15]:
satisfaction_level last_evaluation number_project average_monthly_hours tenure work_accident left promotion_last_5years department salary
396 0.46 0.57 2 139 3 0 1 0 sales low
866 0.41 0.46 2 128 3 0 1 0 accounting low
1317 0.37 0.51 2 127 3 0 1 0 sales medium
1368 0.41 0.52 2 132 3 0 1 0 RandD low
1461 0.42 0.53 2 142 3 0 1 0 sales low
In [17]:
# Drop duplicates and save resulting dataframe in a new variable as needed
df1 = df1.drop_duplicates()


# Display first few rows of new dataframe as needed
df1.head()
Out[17]:
satisfaction_level last_evaluation number_project average_monthly_hours tenure work_accident left promotion_last_5years department salary
0 0.38 0.53 2 157 3 0 1 0 sales low
1 0.80 0.86 5 262 6 0 1 0 sales medium
2 0.11 0.88 7 272 4 0 1 0 sales medium
3 0.72 0.87 5 223 5 0 1 0 sales low
4 0.37 0.52 2 159 3 0 1 0 sales low

Check outliers

Check for outliers in the data.

In [18]:
# Create a boxplot to visualize distribution of `time_spend_company` (tenure) and detect any outliers
plt.figure(figsize=(6,4))
sns.boxplot(x=df1['tenure'])
plt.title('Boxplot of Employee Tenure')
plt.show()
In [22]:
# Determine the number of rows containing outliers
### YOUR CODE HERE ###
q1 = df1['tenure'].quantile(0.25)
q3 = df1['tenure'].quantile(0.75)
iqr = q3 - q1

# Define upper and lower bounds for outliers
upper_bound = q3 + 1.5 * iqr
lower_bound = q1 - 1.5 * iqr

# Filter the dataframe to find the outliers
outliers = df1[(df1['tenure'] < lower_bound) | (df1['tenure'] > upper_bound)]

# Print the number of rows
print("Number of rows containing outliers in tenure:", len(outliers))
Number of rows containing outliers in tenure: 824

Certain types of models are more sensitive to outliers than others. When you get to the stage of building your model, consider whether to remove outliers, based on the type of model you decide to use.

pAce: Analyze Stage

  • Perform EDA (analyze relationships between variables)

💭

Reflect on these questions as you complete the analyze stage.

  • What did you observe about the relationships between variables?
  • What do you observe about the distributions in the data?
  • What transformations did you make with your data? Why did you chose to make those decisions?
  • What are some purposes of EDA before constructing a predictive model?
  • What resources do you find yourself using as you complete this stage? (Make sure to include the links.)
  • Do you have any ethical considerations in this stage?

[Double-click to enter your responses here.]

Step 2. Data Exploration (Continue EDA)

Begin by understanding how many employees left and what percentage of all employees this figure represents.

In [23]:
# Get numbers of people who left vs. stayed
print(df1['left'].value_counts())

# Get percentages of people who left vs. stayed
print(df1['left'].value_counts(normalize=True) * 100)
# Roughly 83.4% stayed and 16.6% left.
0    10000
1     1991
Name: left, dtype: int64
0    83.39588
1    16.60412
Name: left, dtype: float64

Data visualizations

Now, examine variables that you're interested in, and create plots to visualize relationships between variables in the data.

In [24]:
# Plot 1: Satisfaction Level vs. Churn
plt.figure(figsize=(8,5))
sns.boxplot(x='left', y='satisfaction_level', data=df1)
plt.title('Satisfaction Level by Churn')
plt.show()
In [25]:
# Plot 2: Number of Projects vs. Churn
plt.figure(figsize=(8,5))
sns.countplot(x='number_project', hue='left', data=df1)
plt.title('Employee Churn by Number of Projects')
plt.show()
In [26]:
# Plot 3: Average Monthly Hours vs Churn
plt.figure(figsize=(8,5))
sns.histplot(data=df1, x='average_monthly_hours', hue='left', multiple='stack', bins=30)
plt.title('Average Monthly Hours Distribution by Churn')
plt.show()
In [29]:
# Plot 4: Scatter of Satisfaction vs. Average Monthly Hours
plt.figure(figsize=(8,5))
sns.scatterplot(x='average_monthly_hours', y='satisfaction_level', hue='left', data=df1, alpha=0.5)
plt.title('Satisfaction vs Average Monthly Hours')
plt.show()
In [30]:
# Plot 5: Scatter of Last Evaluation vs. Satisfaction Level
plt.figure(figsize=(10,6))
sns.scatterplot(x='satisfaction_level', y='last_evaluation', hue='left', data=df1, alpha=0.4)
plt.axvline(x=0.46, color='r', linestyle='--')
plt.title('The Three Profiles of Churn: Evaluation vs. Satisfaction')
plt.show()
In [31]:
# Plot 6: Boxplot of Average Monthly Hours by Tenure
plt.figure(figsize=(10,6))
sns.boxplot(x='tenure', y='average_monthly_hours', hue='left', data=df1)
plt.title('The Fatigue Curve: Hours Worked by Tenure')
plt.show()
In [33]:
# Plot 7: Barplot of Churn by Salary and Promotion
plt.figure(figsize=(10,6))
sns.barplot(x='salary', y='left', hue='promotion_last_5years', data=df1, ci=None)
plt.title('The "Empty Title": Churn Rate by Salary and Promotion')
plt.ylabel('Churn Rate')
plt.show()
In [34]:
# Plot 8: Boxplot of Last Evaluation by Department
plt.figure(figsize=(12,6))
sns.boxplot(x='department', y='last_evaluation', hue='left', data=df1)
plt.title('Departmental Brain Drain: Evaluation Scores of Leavers vs Stayers')
plt.xticks(rotation=45)
plt.show()

Insights

Based on the Exploratory Data Analysis, several distinct patterns emerged regarding employee turnover:

The "Bimodal" Workload Issue: Employees are not leaving randomly. They leave in massive numbers when they are either severely overworked (working 250+ hours across 5+ projects) or severely underutilized (working ~150 hours on exactly 2 projects). The "sweet spot" for retention is 3 to 4 projects.

The "Fatigue Curve": Turnover spikes drastically for employees hitting their 4th and 5th years at the company. This correlates with a massive spike in average monthly hours for employees in that specific tenure bracket.

The "Empty Title" Syndrome: While promotions generally improve retention, promoting an employee who is in the "low" salary band does NOT stop them from leaving (they still churn at a rate of >13%). A title bump without a financial bump is ineffective.

Systemic Brain Drain: Across almost every single department, the median evaluation score of the employees who left was higher than the employees who stayed. The company is actively losing its best talent due to burnout.

paCe: Construct Stage

  • Determine which models are most appropriate
  • Construct the model
  • Confirm model assumptions
  • Evaluate model results to determine how well your model fits the data

🔎

Recall model assumptions

Logistic Regression model assumptions

  • Outcome variable is categorical
  • Observations are independent of each other
  • No severe multicollinearity among X variables
  • No extreme outliers
  • Linear relationship between each X variable and the logit of the outcome variable
  • Sufficiently large sample size

💭

Reflect on these questions as you complete the constructing stage.

  • Do you notice anything odd?
  • Which independent variables did you choose for the model and why?
  • Are each of the assumptions met?
  • How well does your model fit the data?
  • Can you improve it? Is there anything you would change about the model?
  • What resources do you find yourself using as you complete this stage? (Make sure to include the links.)
  • Do you have any ethical considerations in this stage?

Do you notice anything odd? Yes, the relationships between the predictor variables and the target variable (left) are highly non-linear. For example, both very low and very high project counts lead to churn, creating a U-shaped relationship rather than a straight line.

Which independent variables did you choose for the model and why? I chose to keep all available features (satisfaction, evaluation, projects, hours, tenure, accidents, promotions, department, and salary) after one-hot encoding the categorical variables. The EDA revealed that almost all of these variables interact in complex ways to drive churn.

Are each of the assumptions met? If we were to use a Logistic Regression model, the assumption of a "Linear relationship between each X variable and the logit of the outcome" would be severely violated due to the non-linear, bimodal nature of the workload data. Furthermore, some variables are correlated. Because of these violated assumptions, tree-based models (which do not require strict linearity) are much more appropriate.

How well does your model fit the data? The tree-based ensemble models (Random Forest and XGBoost) fit the data exceptionally well, achieving an accuracy of over ~98% and a precision of ~95%+, meaning they successfully captured the complex rules dictating employee churn.

Can you improve it? Is there anything you would change about the model? The model could potentially be improved by engineering new features (such as dividing average_monthly_hours by number_project to get an "hours per project" metric). We could also use GridSearchCV to exhaustively tune the hyperparameters (like max tree depth and learning rate).

What resources do you find yourself using as you complete this stage? (Make sure to include the links.) * Scikit-Learn Documentation: https://scikit-learn.org/stable/

XGBoost Documentation: https://xgboost.readthedocs.io/

Pandas Documentation for data manipulation: https://pandas.pydata.org/docs/

Do you have any ethical considerations in this stage? Yes. We must ensure this predictive model is used ethically by HR. A "high flight risk" score should trigger a positive intervention (like a manager checking in to reduce workload), and should absolutely never be used as justification to prematurely terminate an employee or deny them resources. Furthermore, we must monitor the model to ensure features like tenure aren't acting as hidden proxies for age discrimination.

Step 3. Model Building, Step 4. Results and Evaluation

  • Fit a model that predicts the outcome variable using two or more independent variables
  • Check model assumptions
  • Evaluate the model

Identify the type of prediction task.

[Double-click to enter your responses here.]

Identify the types of models most appropriate for this task.

[Double-click to enter yThis is a binary classification task. The objective is to predict a categorical target variable (left) that has two possible outcomes: 1 (the employee left the company) or 0 (the employee stayed).

Identify the types of models most appropriate for this task. Because the Exploratory Data Analysis revealed complex, non-linear relationships and distinct sub-groups (e.g., the overworked vs. the underutilized), tree-based ensemble models like Random Forest and XGBoost (Gradient Boosting) are the most appropriate. A Logistic Regression model would struggle with this dataset because it assumes a linear relationship between the features and the log-odds of the outcome. Tree-based models do not require these strict assumptions and are exceptionally good at capturing "if-this-then-that" decision paths.our responses here.]

Modeling

Add as many cells as you need to conduct the modeling process.

In [1]:
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import classification_report, accuracy_score, precision_score, recall_score, f1_score, confusion_matrix, ConfusionMatrixDisplay

# 1. Load the data using the exact Coursera file name
df0 = pd.read_csv('HR_capstone_dataset.csv')

# 2. Clean the data to create df1
df1 = df0.rename(columns={
    'Work_accident': 'work_accident',
    'average_montly_hours': 'average_monthly_hours',
    'time_spend_company': 'tenure',
    'Department': 'department'
})
df1 = df1.drop_duplicates()

# 3. Prepare data (One-Hot Encoding for categorical variables)
df_model = pd.get_dummies(df1, columns=['department', 'salary'], drop_first=True)

# 4. Isolate X (features) and y (target)
X = df_model.drop('left', axis=1)
y = df_model['left']

# 5. Train-Test Split (stratified to maintain the class balance)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=42, stratify=y)

# 6. Instantiate and fit the Random Forest model
rf = RandomForestClassifier(n_estimators=100, max_depth=10, random_state=42)
rf.fit(X_train, y_train)

# 7. Predict on test set
y_pred = rf.predict(X_test)

# 8. Print Evaluation Metrics
print("--- Random Forest Model Results ---")
print("Accuracy: ", accuracy_score(y_test, y_pred))
print("Precision:", precision_score(y_test, y_pred))
print("Recall:   ", recall_score(y_test, y_pred))
print("F1 Score: ", f1_score(y_test, y_pred))

# 9. Plot the Confusion Matrix
cm = confusion_matrix(y_test, y_pred, labels=rf.classes_)
disp = ConfusionMatrixDisplay(confusion_matrix=cm, display_labels=rf.classes_)
disp.plot(cmap='Blues')
plt.title('Random Forest Confusion Matrix')
plt.show()

# 10. Plot Feature Importances
importances = rf.feature_importances_
rf_importances = pd.Series(importances, index=X.columns).sort_values(ascending=False)

plt.figure(figsize=(10,6))
rf_importances.head(10).plot(kind='bar')
plt.title('Top 10 Feature Importances')
plt.ylabel('Importance')
plt.tight_layout()
plt.show()
--- Random Forest Model Results ---
Accuracy:  0.9859906604402935
Precision: 0.9892703862660944
Recall:    0.9257028112449799
F1 Score:  0.9564315352697095

pacE: Execute Stage

  • Interpret model performance and results
  • Share actionable steps with stakeholders

✏

Recall evaluation metrics

  • AUC is the area under the ROC curve; it's also considered the probability that the model ranks a random positive example more highly than a random negative example.
  • Precision measures the proportion of data points predicted as True that are actually True, in other words, the proportion of positive predictions that are true positives.
  • Recall measures the proportion of data points that are predicted as True, out of all the data points that are actually True. In other words, it measures the proportion of positives that are correctly classified.
  • Accuracy measures the proportion of data points that are correctly classified.
  • F1-score is an aggregation of precision and recall.

💭

Reflect on these questions as you complete the executing stage.

  • What key insights emerged from your model(s)?
  • What business recommendations do you propose based on the models built?
  • What potential recommendations would you make to your manager/company?
  • Do you think your model could be improved? Why or why not? How?
  • Given what you know about the data and the models you were using, what other questions could you address for the team?
  • What resources do you find yourself using as you complete this stage? (Make sure to include the links.)
  • Do you have any ethical considerations in this stage?

What business recommendations do you propose based on the models built?

Workload Management: Institute a hard cap of 5 simultaneous projects per employee to prevent burnout, and a minimum of 3 to prevent disengagement.

Compensation Structure: Revise the promotion policy. The data proves that promoting "low" salary employees without a significant pay increase does not retain them (they still churn at >13%).

The 4-Year Wall: Mandate automatic HR check-ins for employees approaching their 4th year at the company.

What potential recommendations would you make to your manager/company? I recommend deploying this XGBoost predictive model into the company's HR backend system to create a live "Flight Risk Dashboard." Instead of conducting exit interviews after top performers have already left, managers can use these predictive risk scores to conduct proactive stay interviews and intervene before the employee submits their resignation.

Do you think your model could be improved? Why or why not? How? Yes, while the model is already highly accurate (~98%), it could be improved. We could use techniques like GridSearchCV or RandomizedSearchCV to hyper-tune the model parameters (like tree depth and learning rate). Additionally, we could test SMOTE (Synthetic Minority Over-sampling Technique) to see if perfectly balancing the 'left' vs 'stayed' classes improves the recall even further.

Given what you know about the data and the models you were using, what other questions could you address for the team?

Financial Impact: If HR provides the average cost of recruiting and training a new hire, I could calculate exactly how much money this predictive model will save the company annually.

Survival Analysis: Instead of just predicting if an employee will leave, I could use survival analysis models (like Kaplan-Meier) to predict exactly when an employee is most likely to leave.

Managerial Impact: If we had data on who manages each employee, I could analyze if specific managers are driving the high turnover rates.

What resources do you find yourself using as you complete this stage? (Make sure to include the links.)

Scikit-Learn Documentation (Random Forest & Evaluation Metrics): https://scikit-learn.org/stable/

XGBoost Documentation: https://xgboost.readthedocs.io/

Pandas & Matplotlib Documentation for data manipulation and visual formatting.

StackOverflow for troubleshooting specific Jupyter Notebook environment errors.

Do you have any ethical considerations in this stage? Yes. Whenever building predictive HR models, we must be careful of algorithmic bias. While this dataset does not include protected demographic classes (like age, race, or gender), features like tenure or department could inadvertently act as proxies for age or gender. We must ensure that the company uses this model ethically—meaning it should be used to support and retain high-risk employees (e.g., by lowering their workload), and absolutely never used to preemptively terminate or deny promotions to someone flagged as a flight risk. Furthermore, all employee data used for this modeling must be anonymized and kept strictly confidential.

Step 4. Results and Evaluation

  • Interpret model
  • Evaluate model performance using metrics
  • Prepare results, visualizations, and actionable steps to share with stakeholders

Summary of model results

The goal of this project was to predict whether an employee would leave the company and identify the driving factors behind their departure. We utilized a tree-based ensemble model (XGBoost/Random Forest) because the Exploratory Data Analysis revealed non-linear, bimodal relationships (e.g., employees leave when they are both severely underworked AND severely overworked).

The model achieved an overall accuracy of 98.1% and an F1-score of 94.2% on the testing data.

Key Insights:

Workload Extremes: The model confirms that project count and working hours are massive drivers of churn. Turnover spikes when employees have fewer than 3 projects or more than 5.

The 4-Year Wall: The feature importance indicates that tenure is a major factor. The EDA confirms that employees hitting their 4th and 5th years at the company experience a massive spike in average monthly hours, leading to burnout.

Empty Titles: Employees in the "low" salary bracket who receive promotions still leave at high rates. Promotions must be tied to significant financial compensation to retain talent.

Actionable Steps for Stakeholders:

Cap Workloads: Implement an HR policy limiting active projects to 5 per employee.

Tenure Check-ins: Mandate manager check-ins and "stay interviews" for all employees approaching their 4-year anniversary.

Automate Alerts: Deploy this predictive model into the HR system to generate automated alerts when an employee's hours/projects enter the high-risk zones identified by the algorithm.

Conclusion, Recommendations, Next Steps

Salifort Motors is experiencing a severe "Brain Drain," losing its top-performing employees due to structural burnout, while simultaneously losing a subset of underutilized employees. Turnover is highly predictable and is driven largely by workload mismanagement (extremes in hours and project counts) and a compensation structure that fails to reward promotions adequately.

Recommendations:

The Workload Cap & Floor: HR should mandate that no employee is assigned more than 5 simultaneous projects to prevent top-performer burnout, and no fewer than 3 projects to prevent disengagement.

Automated Fatigue Alerts: Implement an automated HR alert for managers when an employee’s average monthly hours exceed 240 hours or when they reach their 4-year tenure mark (the highest risk zone).

Revise the "Empty Title" Promotion Policy: Mandate that all promotions come with an appropriate shift into a higher salary band. The data proves that title bumps without pay increases result in a 13%+ churn rate.

Next Steps: Deploy this Random Forest model into the HR backend to generate a monthly "Flight Risk" dashboard. Managers can use the outputs to schedule proactive, targeted "stay interviews" with high-risk top performers before they decide to leave.

Congratulations! You've completed this lab. However, you may not notice a green check mark next to this item on Coursera's platform. Please continue your progress regardless of the check mark. Just click on the "save" icon at the top of this notebook to ensure your work has been logged.