IS361Group4 commited on
Commit
68c7b60
·
verified ·
1 Parent(s): ffa2a89

Update modules/churn_analysis.py

Browse files
Files changed (1) hide show
  1. modules/churn_analysis.py +143 -0
modules/churn_analysis.py CHANGED
@@ -0,0 +1,143 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import pandas as pd
3
+ import numpy as np
4
+ import joblib, os
5
+
6
+ script_dir = os.path.dirname(os.path.abspath(__file__))
7
+ pipeline_path = os.path.join(script_dir, 'toolkit', 'pipeline.joblib')
8
+ model_path = os.path.join(script_dir, 'toolkit', 'Random Forest Classifier.joblib')
9
+
10
+ # Load transformation pipeline and model
11
+ pipeline = joblib.load(pipeline_path)
12
+ model = joblib.load(model_path)
13
+
14
+ # Create a function to calculate TotalCharges
15
+ def calculate_total_charges(tenure, monthly_charges):
16
+ return tenure * monthly_charges
17
+
18
+ # Create a function that applies the ML pipeline and makes predictions
19
+ def predict(SeniorCitizen, Partner, Dependents, tenure,
20
+ InternetService, OnlineSecurity, OnlineBackup, DeviceProtection, TechSupport,
21
+ StreamingTV, StreamingMovies, Contract, PaperlessBilling, PaymentMethod,
22
+ MonthlyCharges):
23
+
24
+ # Calculate TotalCharges
25
+ TotalCharges = calculate_total_charges(tenure, MonthlyCharges)
26
+
27
+ # Create a dataframe with the input data
28
+ input_df = pd.DataFrame({
29
+ 'SeniorCitizen': [SeniorCitizen],
30
+ 'Partner': [Partner],
31
+ 'Dependents': [Dependents],
32
+ 'tenure': [tenure],
33
+ 'InternetService': [InternetService],
34
+ 'OnlineSecurity': [OnlineSecurity],
35
+ 'OnlineBackup': [OnlineBackup],
36
+ 'DeviceProtection': [DeviceProtection],
37
+ 'TechSupport': [TechSupport],
38
+ 'StreamingTV': [StreamingTV],
39
+ 'StreamingMovies': [StreamingMovies],
40
+ 'Contract': [Contract],
41
+ 'PaperlessBilling': [PaperlessBilling],
42
+ 'PaymentMethod': [PaymentMethod],
43
+ 'MonthlyCharges': [MonthlyCharges],
44
+ 'TotalCharges': [TotalCharges]
45
+ })
46
+
47
+ # Selecting categorical and numerical columns separately
48
+ cat_cols = [col for col in input_df.columns if input_df[col].dtype == 'object']
49
+ num_cols = [col for col in input_df.columns if input_df[col].dtype != 'object']
50
+
51
+ X_processed = pipeline.transform(input_df)
52
+
53
+ # Extracting feature names for categorical columns after one-hot encoding
54
+ cat_encoder = pipeline.named_steps['preprocessor'].named_transformers_['cat'].named_steps['onehot']
55
+ cat_feature_names = cat_encoder.get_feature_names_out(cat_cols)
56
+
57
+ # Concatenating numerical and categorical feature names
58
+ feature_names = num_cols + list(cat_feature_names)
59
+
60
+ # Convert X_processed to DataFrame
61
+ final_df = pd.DataFrame(X_processed, columns=feature_names)
62
+
63
+ # Extract the first three columns and remaining columns, then merge
64
+ first_three_columns = final_df.iloc[:, :3]
65
+ remaining_columns = final_df.iloc[:, 3:]
66
+ final_df = pd.concat([remaining_columns, first_three_columns], axis=1)
67
+
68
+ # Make predictions using the model
69
+ prediction_probs = model.predict_proba(final_df)[0]
70
+ prediction_label = {
71
+ "Prediction: CHURN 🔴": prediction_probs[1],
72
+ "Prediction: STAY ✅": prediction_probs[0]
73
+ }
74
+
75
+ return prediction_label
76
+
77
+ input_interface = []
78
+
79
+ with gr.Blocks(theme=gr.themes.Soft()) as app:
80
+
81
+ Title = gr.Label('Customer Churn Prediction App')
82
+
83
+ with gr.Row():
84
+ Title
85
+
86
+ with gr.Row():
87
+ gr.Markdown("This app predicts likelihood of a customer to leave or stay with the company")
88
+
89
+ with gr.Row():
90
+ with gr.Column():
91
+ input_interface_column_1 = [
92
+ gr.components.Radio(['Yes', 'No'], label="Are you a Seniorcitizen?"),
93
+ gr.components.Radio(['Yes', 'No'], label='Do you have Partner?'),
94
+ gr.components.Radio(['No', 'Yes'], label='Do you have any Dependents?'),
95
+ gr.components.Slider(label='Enter lenghth of Tenure in Months', minimum=1, maximum=73, step=1),
96
+ gr.components.Radio(['DSL', 'Fiber optic', 'No Internet'], label='What is your Internet Service?'),
97
+ gr.components.Radio(['No', 'Yes'], label='Do you have Online Security?'),
98
+ gr.components.Radio(['No', 'Yes'], label='Do you have Online Backup?'),
99
+ gr.components.Radio(['No', 'Yes'], label='Do you have Device Protection?')
100
+ ]
101
+
102
+ with gr.Column():
103
+ input_interface_column_2 = [
104
+ gr.components.Radio(['No', 'Yes'], label='Do you have Tech Support?'),
105
+ gr.components.Radio(['No', 'Yes'], label='Do you have Streaming TV?'),
106
+ gr.components.Radio(['No', 'Yes'], label='Do you have Streaming Movies?'),
107
+ gr.components.Radio(['Month-to-month', 'One year', 'Two year'], label='What is your Contract Type?'),
108
+ gr.components.Radio(['Yes', 'No'], label='Do you prefer Paperless Billing?'),
109
+ gr.components.Radio(['Electronic check', 'Mailed check', 'Bank transfer (automatic)', 'Credit card (automatic)'], label='Which PaymentMethod do you prefer?'),
110
+ gr.components.Slider(label="Enter monthly charges", minimum=18.40, maximum=118.65)
111
+ ]
112
+
113
+ with gr.Row():
114
+ input_interface.extend(input_interface_column_1)
115
+ input_interface.extend(input_interface_column_2)
116
+
117
+ with gr.Row():
118
+ predict_btn = gr.Button('Predict')
119
+ output_interface = gr.Label(label="churn")
120
+
121
+ with gr.Accordion("Open for information on inputs", open=False):
122
+ gr.Markdown("""This app receives the following as inputs and processes them to return the prediction on whether a customer, will churn or not.
123
+
124
+ - SeniorCitizen: Whether a customer is a senior citizen or not
125
+ - Partner: Whether the customer has a partner or not (Yes, No)
126
+ - Dependents: Whether the customer has dependents or not (Yes, No)
127
+ - Tenure: Number of months the customer has stayed with the company
128
+ - InternetService: Customer's internet service provider (DSL, Fiber Optic, No)
129
+ - OnlineSecurity: Whether the customer has online security or not (Yes, No, No Internet)
130
+ - OnlineBackup: Whether the customer has online backup or not (Yes, No, No Internet)
131
+ - DeviceProtection: Whether the customer has device protection or not (Yes, No, No internet service)
132
+ - TechSupport: Whether the customer has tech support or not (Yes, No, No internet)
133
+ - StreamingTV: Whether the customer has streaming TV or not (Yes, No, No internet service)
134
+ - StreamingMovies: Whether the customer has streaming movies or not (Yes, No, No Internet service)
135
+ - Contract: The contract term of the customer (Month-to-Month, One year, Two year)
136
+ - PaperlessBilling: Whether the customer has paperless billing or not (Yes, No)
137
+ - Payment Method: The customer's payment method (Electronic check, mailed check, Bank transfer(automatic), Credit card(automatic))
138
+ - MonthlyCharges: The amount charged to the customer monthly
139
+ """)
140
+
141
+ predict_btn.click(fn=predict, inputs=input_interface, outputs=output_interface)
142
+
143
+ app.launch(share=True)