-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
294 lines (207 loc) · 9.83 KB
/
Copy pathmain.py
File metadata and controls
294 lines (207 loc) · 9.83 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
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
import streamlit as st
import pandas as pd
import pickle
import numpy as np
import os
from openai import OpenAI
import utils as ut
# initialize the OpenAI API client with a GROQ API endpoint (this is the interface)
client = OpenAI(
base_url="https://api.groq.com/openai/v1",
api_key=os.environ.get("GROQ_API_KEY")
)
# OpenAI library provides a standard API that most other LLMs API providers have adopted.
# all we need to do is change the base url and api key and use other API providers
# groq api is free and has the fastest inference, has their own HW called LPU: Language processing unit
def load_model(filename):
with open(filename, "rb") as file:
return pickle.load(file)
xgboost_model = load_model('xgb_model.pkl')
naive_bayes_model = load_model('nb_model.pkl')
random_forest_model = load_model('rf_model.pkl')
decision_tree_model = load_model('dt_model.pkl')
svm_model = load_model('svm_model.pkl')
knn_model = load_model('knn_model.pkl')
voting_classifier_model = load_model('voting_clf_model.pkl')
xgboost_SMOTE_model = load_model('xgboost-SMOTE_model.pkl')
gbc_model = load_model('gbc_model.pkl')
xgboost_featureEngineered_model = load_model('xgboost-featureEngineered_model.pkl')
# Prepare the input data for the functions
def prepare_input(credit_score, location, gender, age, tenure, balance, num_products, has_credit_card, is_active_member, estimated_salary, ):
input_dict = {
'CreditScore': credit_score,
'Age': age,
'Tenure': tenure,
'Balance': balance,
'NumOfProducts': num_products,
'HasCrCard': has_credit_card,
'IsActiveMember': int(is_active_member),
'EstimatedSalary': estimated_salary,
'Geography_France': 1 if location == 'France' else 0,
'Geography_Germany': 1 if location == 'Germany' else 0,
'Geography_Spain' : 1 if location == 'Spain' else 0,
'Gender_Male': 1 if gender == 'Male' else 0,
'Gender_Female': 1 if gender == 'Female' else 0,
# 'CLV' : (balance * estimated_salary)/100000,
# 'TenureAgeRatio': tenure/age,
# 'AgeGroup_MiddleAge': 1 if (age >= 30 and age<45) else 0,
# 'AgeGroup_Senior': 1 if (age >= 45 and age<60) else 0,
# 'AgeGroup_Elderly': 1 if (age >= 60 and age< 100) else 0
}
input_df = pd.DataFrame([input_dict])
return input_df, input_dict
def make_predictions(input_df, input_dict):
probabilities = {
'XGBoost' : xgboost_model.predict_proba(input_df)[0][1],
'Random Forest': random_forest_model.predict_proba(input_df)[0][1],
'K-Nearest Neighbors': knn_model.predict_proba(input_df)[0][1],
# 'Voting Classifiers': voting_classifier_model.predict_proba(input_df)[0][1],
# 'Gradient Boosting Classifier': gbc_model.predict_proba(input_df)[0][1]
}
avg_probability = np.mean(list(probabilities.values()))
col1, col2 = st.columns(2)
# display the guage chart
with col1:
fig = ut.create_gauge_chart(avg_probability)
st.plotly_chart(fig, use_container_width=True)
st.write(f"The customer has a {avg_probability*100:.2f}% chance of churning.")
# display the model probability chart
with col2:
fig_probs = ut.create_model_probability_chart(probabilities)
st.plotly_chart(fig_probs, use_container_width=True)
st.markdown("### Model Probabilities by %")
for model, prob in probabilities.items():
st.write(f"{model} : {prob * 100:.2f}%")
st.write(f"Average Probability: {avg_probability * 100:.2f}%")
return avg_probability
def explain_prediction(probability, input_dict, surname):
prompt = f"""You are an expert data scientist at a bank, where you specialize in interpreting and explaining predictions of machine learning models.
Your machine learning model has predicted that a customer named {surname} has a {round(probability * 100, 1)}% probability of churning, based on the information provided below.
Here is the customer information:
{input_dict}
Here are the machine learning model's top 10 most important features for predicting the churn:
Feature | Importance
-----------------------
NumOfProducts | 0.323888
IsActiveMember | 0.164146
Age | 0.109550
Geography_Germany | 0.091373
Balance | 0.052786
Geography_France | 0.046463
Gender_Female | 0.045283
Geography_Spain | 0.036855
CreditScore | 0.035005
EstimatedSalary | 0.032655
HasCrCard | 0.031940
Tenure | 0.030054
Gender_Male | 0.000000
{pd.set_option('display.max_columns', None)}
Here are some summary statistics for churned customers:
{df[df['Exited'] == 1].describe()}
Here are some summary statistics for non-churned customers:
{df[df['Exited'] == 0].describe()}
- If the customer has over a 40% risk of churning, generate 3 sentences explaining why they are at a risk of churning.
- If the customer has less than a 40% risk of churning, generate 3 sentences explaining why they might not be at a risk of churning.
- Just give an explanation using the customer's information, the summary statistics of churned and not churned customers, and the feature importances provided.
Don't ever mention the probability of churning or the machine learning model, or say anything like "Based on the machine learning model's prediction and top 10 most importance features", just explain the prediction.
"""
print("EXPLANATION PROMPT", prompt)
raw_response = client.chat.completions.create(
model = "llama-3.1-70b-versatile",
messages = [{
'role':'user',
'content': prompt
}]
)
return raw_response.choices[0].message.content
def generate_email(probability, input_dict, explanation, surname):
prompt = f"""You are a manager at HS bank, You are responsible for ensuring customers stay with the bak and are incentivized with various offers.
You noticed a customer named {surname} has a {round(probability * 100, 1)}% probability of churning.
Here is the customer information:
{input_dict}
Here is some explanation as to why the customer might be at the risk of churning:
{explanation}
Generate an email to the customer based on their information, asking them to stay with the bank if they are at a risk of churning, or offering them incentives so that they become more loyal to the bank.
Make sure to list out a set of incentives to stay based on their information, in bullet point format (each bullet starting in a new line) Don't ever mention the probability of churning, or the machine model to the customer.
"""
raw_response = client.chat.completions.create(
model = "llama-3.1-70b-versatile",
messages = [{
"role":"user",
"content":prompt
}]
)
print("\n\nEMAIL PROMPT", prompt)
return raw_response.choices[0].message.content
st.title("Customer Churn Prediction")
df = pd.read_csv("churn.csv")
# Create a list of customers to create a dropdown menu
customers = [f"{row['CustomerId']} - {row['Surname']}" for _, row in df.iterrows()]
# display the list using streamlit select box
selected_customer_option = st.selectbox("Select a customer", customers)
# split the selected customer option into customer id and surname
if selected_customer_option:
selected_customer_id = int(selected_customer_option.split(' - ')[0])
print("Selected Customer ID: ",selected_customer_id)
selected_customer_surname = selected_customer_option.split(' - ')[1]
print("Selected Customer Surname: ", selected_customer_surname)
# filter the dataframe to get the selected customer data, iloc is used to get the row by index
selected_customer = df.loc[df['CustomerId'] == selected_customer_id].iloc[0]
print("Selected Customer Data: ", selected_customer)
# display the selected customer data in columns on the webapp
col1, col2 = st.columns(2)
with col1:
credit_score = st.number_input("Credit Score",
min_value = 300,
max_value = 850,
value = int(selected_customer['CreditScore']))
location = st.selectbox(
"Location", ["Spain", "France", "Germany"],
index=["Spain", "France", "Germany"].index(selected_customer['Geography']))
gender = st.radio("Gender", ["Male", "Female"],
index = 0 if selected_customer['Gender'] == "Male" else 1)
age = st.number_input(
"Age",
min_value = 18,
max_value = 100,
value = int(selected_customer['Age']))
tenure = st.number_input(
"Tenure (years)",
min_value = 0,
max_value=50,
value = int(selected_customer['Tenure'])
)
with col2:
balance = st.number_input(
"Balance",
min_value = 0.0,
value = float(selected_customer['Balance']))
num_products = st.number_input(
"Number of Products",
min_value = 1,
max_value = 10,
value = int(selected_customer['NumOfProducts'])
)
has_credit_card = st.checkbox(
"Has Credit Card",
value = bool(selected_customer['HasCrCard']))
is_active_member = st.checkbox(
"Is Active Member",
value = bool(selected_customer['IsActiveMember'])
)
estimated_salary = st.number_input(
"Estimated Salary",
min_value = 0.0,
value = float(selected_customer['EstimatedSalary'])
)
if st.button("Predict Churn!"):
input_df, input_dict = prepare_input(credit_score, location, gender, age, tenure, balance, num_products, has_credit_card, is_active_member, estimated_salary)
avg_probability = make_predictions(input_df, input_dict)
explanation = explain_prediction(avg_probability, input_dict, selected_customer['Surname'])
st.markdown("---")
st.subheader("Explanation of Prediction")
st.markdown(explanation)
email = generate_email(avg_probability, input_dict, explanation, selected_customer['Surname'])
st.markdown("---")
st.subheader("Personalized Email")
st.markdown(email)