-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
145 lines (108 loc) · 4.12 KB
/
Copy pathapp.py
File metadata and controls
145 lines (108 loc) · 4.12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
import joblib
import os
import streamlit as st
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import LabelEncoder
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score, confusion_matrix
import matplotlib.pyplot as plt
st.title("👨💼 Employee Performance Predictor")
# Upload file
uploaded_file = st.file_uploader("Upload Employee Dataset", type=["csv"])
if uploaded_file is not None:
df = pd.read_csv(uploaded_file)
st.subheader("📊 Dataset Preview")
st.write(df.head())
# ---------------------------
# Encoding
# ---------------------------
dept_encoder = LabelEncoder()
perf_encoder = LabelEncoder()
df['Department'] = dept_encoder.fit_transform(df['Department'])
df['Performance'] = perf_encoder.fit_transform(df['Performance'])
# ---------------------------
# Features & Target
# ---------------------------
X = df.drop('Performance', axis=1)
y = df['Performance']
# Train-test split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
# ---------------------------
# Folders
# ---------------------------
os.makedirs("models", exist_ok=True)
os.makedirs("images", exist_ok=True)
# ---------------------------
# Model (Load or Train)
# ---------------------------
model_path = "models/performance_model.pkl"
if os.path.exists(model_path):
model = joblib.load(model_path)
else:
model = RandomForestClassifier()
model.fit(X_train, y_train)
joblib.dump(model, model_path)
# ---------------------------
# Prediction
# ---------------------------
y_pred = model.predict(X_test)
# Accuracy
acc = accuracy_score(y_test, y_pred)
st.subheader("📈 Model Accuracy")
st.write(f"Accuracy: {acc:.2f}")
# =====================================================
# 📉 CONFUSION MATRIX (FIXED + PROPER SIZE)
# =====================================================
cm = confusion_matrix(y_test, y_pred)
st.subheader("📉 Confusion Matrix")
fig, ax = plt.subplots(figsize=(7, 7)) # ✅ bigger size
im = ax.imshow(cm, cmap="Blues")
# Labels
ax.set_xlabel("Predicted")
ax.set_ylabel("Actual")
classes = perf_encoder.classes_
ax.set_xticks(range(len(classes)))
ax.set_yticks(range(len(classes)))
ax.set_xticklabels(classes, rotation=45)
ax.set_yticklabels(classes)
# Values inside matrix
for i in range(len(classes)):
for j in range(len(classes)):
ax.text(j, i, cm[i, j],
ha="center", va="center",
color="black", fontsize=12)
fig.colorbar(im)
# Save image
fig.savefig("images/confusion_matrix.png", bbox_inches="tight", dpi=300)
st.pyplot(fig)
# =====================================================
# 🔥 FEATURE IMPORTANCE
# =====================================================
st.subheader("🔥 Feature Importance")
importance = model.feature_importances_
features = X.columns
fig2, ax2 = plt.subplots(figsize=(7, 4))
ax2.barh(features, importance)
ax2.set_xlabel("Importance")
fig2.savefig("images/feature_importance.png", bbox_inches="tight", dpi=300)
st.pyplot(fig2)
# =====================================================
# 🔮 PREDICTION
# =====================================================
st.subheader("🔮 Predict New Employee Performance")
age = st.slider("Age", 20, 60)
exp = st.slider("Experience", 1, 20)
salary = st.number_input("Salary", min_value=10000)
training = st.slider("Training Hours", 1, 100)
dept = st.selectbox("Department", list(dept_encoder.classes_))
dept_encoded = dept_encoder.transform([dept])[0]
if st.button("Predict"):
input_df = pd.DataFrame(
[[age, exp, salary, training, dept_encoded]],
columns=X.columns
)
pred = model.predict(input_df)
result = perf_encoder.inverse_transform(pred)
st.success(f"Predicted Performance: {result[0]}")