RJuro commited on
Commit
1a4754d
Β·
verified Β·
1 Parent(s): 9404508

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +196 -0
app.py ADDED
@@ -0,0 +1,196 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Import necessary libraries
2
+ import streamlit as st
3
+ import pandas as pd
4
+ import altair as alt
5
+ import matplotlib.pyplot as plt
6
+ import seaborn as sns
7
+ from duckduckgo_search import DDGS
8
+
9
+
10
+ # Function to load the dataset
11
+ @st.cache_data # Cache the function to enhance performance
12
+ def load_data():
13
+ # Define the file path
14
+ file_path = 'https://raw.githubusercontent.com/aaubs/ds-master/main/apps/M1-attrition-streamlit/HR-Employee-Attrition-synth.csv'
15
+
16
+ # Load the CSV file into a pandas dataframe
17
+ df = pd.read_csv(file_path)
18
+
19
+ # Create age groups and add as a new column
20
+ bin_edges = [18, 25, 35, 45, 60]
21
+ bin_labels = ['18-24', '25-34', '35-44', '45-60']
22
+ df['AgeGroup'] = pd.cut(df['Age'], bins=bin_edges, labels=bin_labels, right=False)
23
+
24
+ return df
25
+
26
+ # Load the data using the defined function
27
+ df = load_data()
28
+
29
+ # Set the app title and sidebar header
30
+ st.title("Employee Attrition Dashboard πŸ˜ŠπŸ“ˆ")
31
+ st.sidebar.header("Filters πŸ“Š")
32
+
33
+ # Introduction
34
+
35
+ # HR Attrition Dashboard
36
+
37
+ st.markdown("""
38
+ Welcome to the HR Attrition Dashboard. In the backdrop of rising employee turnovers, HR departments are stressing the significance of predicting and understanding employee departures. Through the lens of data analytics, this dashboard unveils the deeper causes of employee churn and proposes strategies to boost employee retention.
39
+ """)
40
+ with st.expander("πŸ“Š **Objective**"):
41
+ st.markdown("""
42
+ At the heart of this dashboard is the mission to visually decode data, equipping HR experts with insights to tackle these queries:
43
+ - Which company factions face a greater likelihood of employee exits?
44
+ - What might be pushing these individuals to part ways?
45
+ - Observing the discerned trends, what incentives might hold the key to decreasing the attrition rate?
46
+ """
47
+ )
48
+
49
+ # Tutorial Expander
50
+ with st.expander("How to Use the Dashboard πŸ“š"):
51
+ st.markdown("""
52
+ 1. **Filter Data** - Use the sidebar filters to narrow down specific data sets.
53
+ 2. **Visualize Data** - From the dropdown, select a visualization type to view patterns.
54
+ 3. **Insights & Recommendations** - Scroll down to see insights derived from the visualizations and actionable recommendations.
55
+ """)
56
+
57
+
58
+ # Sidebar filter: Age Group
59
+ selected_age_group = st.sidebar.multiselect("Select Age Groups πŸ•°οΈ", df['AgeGroup'].unique().tolist(), default=df['AgeGroup'].unique().tolist())
60
+ if not selected_age_group:
61
+ st.warning("Please select an age group from the sidebar ⚠️")
62
+ st.stop()
63
+ filtered_df = df[df['AgeGroup'].isin(selected_age_group)]
64
+
65
+ # Sidebar filter: Department
66
+ departments = df['Department'].unique().tolist()
67
+ selected_department = st.sidebar.multiselect("Select Departments 🏒", departments, default=departments)
68
+ if not selected_department:
69
+ st.warning("Please select a department from the sidebar ⚠️")
70
+ st.stop()
71
+ filtered_df = filtered_df[filtered_df['Department'].isin(selected_department)]
72
+
73
+ # Sidebar filter: Monthly Income Range
74
+ min_income = int(df['MonthlyIncome'].min())
75
+ max_income = int(df['MonthlyIncome'].max())
76
+ income_range = st.sidebar.slider("Select Monthly Income Range πŸ’°", min_income, max_income, (min_income, max_income))
77
+ filtered_df = filtered_df[(filtered_df['MonthlyIncome'] >= income_range[0]) & (filtered_df['MonthlyIncome'] <= income_range[1])]
78
+
79
+ # Sidebar filter: Job Satisfaction Level
80
+ satisfaction_levels = sorted(df['JobSatisfaction'].unique().tolist())
81
+ selected_satisfaction = st.sidebar.multiselect("Select Job Satisfaction Levels 😊", satisfaction_levels, default=satisfaction_levels)
82
+ if not selected_satisfaction:
83
+ st.warning("Please select a job satisfaction level from the sidebar ⚠️")
84
+ st.stop()
85
+ filtered_df = filtered_df[filtered_df['JobSatisfaction'].isin(selected_satisfaction)]
86
+
87
+ # Displaying the Attrition Analysis header
88
+ st.header("Attrition Analysis πŸ“Š")
89
+
90
+ # Dropdown to select the type of visualization
91
+ visualization_option = st.selectbox(
92
+ "Select Visualization 🎨",
93
+ ["Attrition by Age Group",
94
+ "KDE Plot: Distance from Home by Attrition",
95
+ "Attrition by Job Role",
96
+ "Attrition Distribution by Gender",
97
+ "MonthlyRate and DailyRate by JobLevel"]
98
+ )
99
+
100
+ # Visualizations based on user selection
101
+ if visualization_option == "Attrition by Age Group":
102
+ # Bar chart for attrition by age group
103
+ chart = alt.Chart(filtered_df).mark_bar().encode(
104
+ x='AgeGroup',
105
+ y='count()',
106
+ color='Attrition'
107
+ ).properties(
108
+ title='Attrition Rate by Age Group'
109
+ )
110
+ st.altair_chart(chart, use_container_width=True)
111
+
112
+ elif visualization_option == "KDE Plot: Distance from Home by Attrition":
113
+ # KDE plot for Distance from Home based on Attrition
114
+ plt.figure(figsize=(10, 6))
115
+ sns.kdeplot(data=filtered_df, x='DistanceFromHome', hue='Attrition', fill=True, palette='Set2')
116
+ plt.xlabel('Distance From Home')
117
+ plt.ylabel('Density')
118
+ plt.title('KDE Plot of Distance From Home by Attrition')
119
+ st.pyplot(plt)
120
+
121
+ elif visualization_option == "Attrition by Job Role":
122
+ # Bar chart for attrition by job role
123
+ chart = alt.Chart(filtered_df).mark_bar().encode(
124
+ y='JobRole',
125
+ x='count()',
126
+ color='Attrition'
127
+ ).properties(
128
+ title='Attrition by Job Role'
129
+ )
130
+ st.altair_chart(chart, use_container_width=True)
131
+
132
+ elif visualization_option == "Attrition Distribution by Gender":
133
+ # Pie chart for attrition distribution by gender
134
+ pie_chart_data = filtered_df[filtered_df['Attrition'] == 'Yes']['Gender'].value_counts().reset_index()
135
+ pie_chart_data.columns = ['Gender', 'count']
136
+
137
+ chart = alt.Chart(pie_chart_data).mark_arc().encode(
138
+ theta='count:Q',
139
+ color='Gender:N',
140
+ tooltip=['Gender', 'count']
141
+ ).properties(
142
+ title='Attrition Distribution by Gender',
143
+ width=300,
144
+ height=300
145
+ ).project('identity')
146
+ st.altair_chart(chart, use_container_width=True)
147
+
148
+ elif visualization_option == "MonthlyRate and DailyRate by JobLevel":
149
+ # Boxplots for MonthlyRate and DailyRate by JobLevel
150
+ fig, ax = plt.subplots(1, 2, figsize=(15, 7))
151
+
152
+ # MonthlyRate by JobLevel
153
+ sns.boxplot(x="JobLevel", y="MonthlyRate", data=filtered_df, ax=ax[0], hue="JobLevel", palette='Set2', legend=False)
154
+ ax[0].set_title('MonthlyRate by JobLevel')
155
+ ax[0].set_xlabel('Job Level')
156
+ ax[0].set_ylabel('Monthly Rate')
157
+
158
+ # DailyRate by JobLevel
159
+ sns.boxplot(x="JobLevel", y="DailyRate", data=filtered_df, ax=ax[1], hue="JobLevel", palette='Set2', legend=False)
160
+ ax[1].set_title('DailyRate by JobLevel')
161
+ ax[1].set_xlabel('Job Level')
162
+ ax[1].set_ylabel('Daily Rate')
163
+
164
+ plt.tight_layout()
165
+ st.pyplot(fig)
166
+
167
+ # Display dataset overview
168
+ st.header("Dataset Overview")
169
+ st.dataframe(df.describe())
170
+
171
+
172
+
173
+
174
+ # Insights from Visualization Section Expander
175
+ with st.expander("Insights from Visualization 🧠"):
176
+ st.markdown("""
177
+ 1. **Age Groups & Attrition** - The 'Attrition by Age Group' plot showcases which age brackets face higher attrition.
178
+ 2. **Home Distance's Impact** - The 'KDE Plot: Distance from Home by Attrition' visualizes if being farther away influences leaving tendencies.
179
+ 3. **Roles & Attrition** - 'Attrition by Job Role' reveals which roles might be more attrition-prone.
180
+ 4. **Gender & Attrition** - The pie chart for 'Attrition Distribution by Gender' provides insights into any gender-based patterns.
181
+ 5. **Earnings Patterns** - 'MonthlyRate and DailyRate by JobLevel' boxplots display the compensation distribution across job levels.
182
+ """)
183
+
184
+ # Recommendations Expander
185
+ with st.expander("Recommendations for Action 🌟"):
186
+ st.markdown("""
187
+ - 🎁 **Incentive Programs:** Introduce incentives tailored for groups showing higher attrition tendencies.
188
+ - 🏑 **Remote Work Options:** Providing flexibility, especially for those living farther from the workplace, could reduce attrition.
189
+ - πŸš€ **Training & Growth:** Invest in employee development, especially in roles with higher attrition rates.
190
+ - πŸ‘« **Gender Equality:** Foster an environment that supports equal opportunities regardless of gender.
191
+ - πŸ’Έ **Compensation Review:** Regularly review and adjust compensation structures to stay competitive and retain talent.
192
+ """)
193
+
194
+ if st.button('AI Eval'):
195
+ with st.expander("AI Assistant Evaluation"):
196
+ st.markdown(DDGS().chat("You are a smart HR person: Provide a concise 3 sententce evaluation of the HR situation given some key datapoints here: "+str(df.describe()), model='claude-3-haiku'))