DhominickJ commited on
Commit
2fc252e
·
0 Parent(s):

Compilation of the Application for Churning

Browse files
Files changed (3) hide show
  1. WA_Fn-UseC_-Telco-Customer-Churn.csv +0 -0
  2. app.py +143 -0
  3. requirements.txt +5 -0
WA_Fn-UseC_-Telco-Customer-Churn.csv ADDED
The diff for this file is too large to render. See raw diff
 
app.py ADDED
@@ -0,0 +1,143 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import pandas as pd
3
+ from sklearn.model_selection import train_test_split
4
+ from sklearn.preprocessing import StandardScaler, LabelEncoder
5
+ from sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier, AdaBoostClassifier
6
+ from sklearn.linear_model import LogisticRegression
7
+ from sklearn.svm import SVC
8
+ from sklearn.neighbors import KNeighborsClassifier
9
+ from sklearn.tree import DecisionTreeClassifier
10
+ from sklearn.naive_bayes import GaussianNB
11
+ from sklearn.metrics import accuracy_score, classification_report, confusion_matrix, roc_curve, auc
12
+ import matplotlib.pyplot as plt
13
+ import seaborn as sns
14
+
15
+ st.title("Customer Churn Prediction")
16
+
17
+ df =
18
+
19
+ # Data Loading and Preprocessing (same as before)
20
+ @st.cache_data
21
+ def load_and_preprocess_data(file_path):
22
+ df['TotalCharges'] = pd.to_numeric(df['TotalCharges'], errors='coerce')
23
+ df.dropna(inplace=True)
24
+
25
+ for col in ['gender', 'Partner', 'Dependents', 'PhoneService', 'MultipleLines', 'InternetService',
26
+ 'OnlineSecurity', 'OnlineBackup', 'DeviceProtection', 'TechSupport', 'StreamingTV',
27
+ 'StreamingMovies', 'Contract', 'PaperlessBilling', 'PaymentMethod', 'Churn']:
28
+ le = LabelEncoder()
29
+ df[col] = le.fit_transform(df[col])
30
+
31
+ numerical_cols = ['tenure', 'MonthlyCharges', 'TotalCharges']
32
+ scaler = StandardScaler()
33
+ df[numerical_cols] = scaler.fit_transform(df[numerical_cols])
34
+ return df
35
+
36
+ # file_path = st.file_uploader("Upload CSV file", type="csv")
37
+ file_path = "./WA_Fn-UseC_-Telco-Customer-Churn.csv"
38
+
39
+ if file_path is not None:
40
+ df = load_and_preprocess_data(file_path)
41
+ X = df.drop('Churn', axis=1)
42
+ y = df['Churn']
43
+ X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
44
+
45
+ # Model Training and Evaluation (using session state - same as before)
46
+ if 'models' not in st.session_state:
47
+ st.session_state.models = {}
48
+
49
+ def train_and_evaluate(model_name, model, X_train, y_train, X_test, y_test):
50
+ if model_name not in st.session_state.models:
51
+ model.fit(X_train, y_train)
52
+ st.session_state.models[model_name] = model
53
+ else:
54
+ model = st.session_state.models[model_name]
55
+
56
+ y_pred = model.predict(X_test)
57
+ accuracy = accuracy_score(y_test, y_pred)
58
+ report = classification_report(y_test, y_pred, output_dict=True)
59
+ cm = confusion_matrix(y_test, y_pred)
60
+
61
+ # ROC Curve and AUC
62
+ if hasattr(model, "predict_proba"): #check if model has predict_proba
63
+ y_prob = model.predict_proba(X_test)[:, 1]
64
+ fpr, tpr, _ = roc_curve(y_test, y_prob)
65
+ roc_auc = auc(fpr, tpr)
66
+ return accuracy, report, cm, model, fpr, tpr, roc_auc
67
+ else:
68
+ return accuracy, report, cm, model, None, None, None
69
+
70
+ models = {
71
+ "Logistic Regression": LogisticRegression(max_iter=1000, random_state=42),
72
+ "Random Forest": RandomForestClassifier(random_state=42),
73
+ "Gradient Boosting": GradientBoostingClassifier(random_state=42),
74
+ "AdaBoost": AdaBoostClassifier(random_state=42),
75
+ "SVM": SVC(probability=True, random_state=42), # probability=True for ROC Curve
76
+ "K-Nearest Neighbors": KNeighborsClassifier(),
77
+ "Decision Tree": DecisionTreeClassifier(random_state=42),
78
+ "Naive Bayes": GaussianNB(),
79
+ }
80
+
81
+ # Tabs for Comparison
82
+ tabs = ["Model Comparison", "Individual Model Performance"]
83
+ selected_tab = st.sidebar.radio("Select Tab", tabs)
84
+
85
+ if selected_tab == "Model Comparison":
86
+ st.subheader("Model Comparison")
87
+ results = []
88
+ for model_name, model in models.items():
89
+ accuracy, report, cm, trained_model, fpr, tpr, roc_auc = train_and_evaluate(model_name, model, X_train, y_train, X_test, y_test)
90
+ results.append([model_name, accuracy])
91
+
92
+ results_df = pd.DataFrame(results, columns=["Model", "Accuracy"])
93
+ st.dataframe(results_df.sort_values(by="Accuracy", ascending=False)) # Sort by accuracy
94
+
95
+ # Combined ROC Curve Plot
96
+ fig, ax = plt.subplots()
97
+ for model_name, model in models.items():
98
+ _, _, _, _, fpr, tpr, roc_auc = train_and_evaluate(model_name, model, X_train, y_train, X_test, y_test)
99
+ if fpr is not None and tpr is not None and roc_auc is not None:
100
+ ax.plot(fpr, tpr, label=f'{model_name} (AUC = {roc_auc:.2f})')
101
+
102
+ ax.plot([0, 1], [0, 1], 'k--') # Dashed diagonal
103
+ ax.set_xlabel('False Positive Rate')
104
+ ax.set_ylabel('True Positive Rate')
105
+ ax.set_title('ROC Curves')
106
+ ax.legend()
107
+ st.pyplot(fig)
108
+
109
+
110
+ elif selected_tab == "Individual Model Performance":
111
+ model_name = st.selectbox("Select Model", list(models.keys()))
112
+ accuracy, report, cm, trained_model, fpr, tpr, roc_auc = train_and_evaluate(model_name, models[model_name], X_train, y_train, X_test, y_test)
113
+
114
+ st.subheader(f"{model_name} Performance")
115
+ st.write(f"Accuracy: {accuracy:.4f}")
116
+ report_df = pd.DataFrame(report).transpose()
117
+ st.dataframe(report_df)
118
+
119
+ fig, ax = plt.subplots()
120
+ sns.heatmap(cm, annot=True, fmt="d", cmap="Blues", ax=ax)
121
+ plt.xlabel("Predicted Label")
122
+ plt.ylabel("True Label")
123
+ st.pyplot(fig)
124
+
125
+ if hasattr(trained_model, "feature_importances_"):
126
+ importances = trained_model.feature_importances_
127
+ feature_importance_df = pd.DataFrame({'Feature': X.columns, 'Importance': importances})
128
+ feature_importance_df = feature_importance_df.sort_values(by='Importance', ascending=False)
129
+ st.write("Feature Importance:")
130
+ st.dataframe(feature_importance_df)
131
+
132
+ if fpr is not None and tpr is not None and roc_auc is not None:
133
+ fig, ax = plt.subplots()
134
+ ax.plot(fpr, tpr, label=f'{model_name} (AUC = {roc_auc:.2f})')
135
+ ax.plot([0, 1], [0, 1], 'k--')
136
+ ax.set_xlabel('False Positive Rate')
137
+ ax.set_ylabel('True Positive Rate')
138
+ ax.set_title('ROC Curve')
139
+ ax.legend()
140
+ st.pyplot(fig)
141
+
142
+ else:
143
+ st.write("Please upload a CSV file to begin.")
requirements.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ streamlit
2
+ pandas
3
+ sklearn
4
+ matplotlib
5
+ seaborn