-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcreate_notebook.py
More file actions
202 lines (200 loc) · 8.17 KB
/
Copy pathcreate_notebook.py
File metadata and controls
202 lines (200 loc) · 8.17 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
import json
notebook = {
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Task 4 \u2014 Customer Churn Prediction System\n",
"This notebook implements a machine learning model to predict whether a customer will leave (churn) or continue using a service."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 1. Data Collection\n",
"Load the customer churn dataset."
]
},
{
"cell_type": "code",
"execution_count": None,
"metadata": {},
"outputs": [],
"source": [
"import pandas as pd\n",
"import numpy as np\n",
"import matplotlib.pyplot as plt\n",
"import seaborn as sns\n",
"\n",
"# Load the dataset\n",
"df = pd.read_csv('Telco-Customer-Churn.csv')\n",
"display(df.head())"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 2. Data Preprocessing & 4. Feature Engineering\n",
"Handle missing values, encode categorical variables, create new features, and scale data."
]
},
{
"cell_type": "code",
"execution_count": None,
"metadata": {},
"outputs": [],
"source": [
"# 4. Feature Engineering: Remove irrelevant columns\n",
"df.drop('customerID', axis=1, inplace=True)\n",
"\n",
"# Convert TotalCharges to numeric, coerce errors to NaN\n",
"df['TotalCharges'] = pd.to_numeric(df['TotalCharges'], errors='coerce')\n",
"\n",
"# 2. Data Preprocessing: Handle missing values\n",
"df['TotalCharges'].fillna(df['TotalCharges'].median(), inplace=True)\n",
"\n",
"# 4. Feature Engineering: Create Average Monthly Spend (already have MonthlyCharges, but let's demonstrate)\n",
"df['Avg_Monthly_Spend'] = np.where(df['tenure'] > 0, df['TotalCharges'] / df['tenure'], df['MonthlyCharges'])\n",
"\n",
"# 4. Feature Engineering: Contract type grouping (Month-to-month vs Long-term)\n",
"df['Is_Long_Term_Contract'] = df['Contract'].apply(lambda x: 1 if x in ['One year', 'Two year'] else 0)\n",
"\n",
"# 2. Data Preprocessing: Encode categorical variables\n",
"from sklearn.preprocessing import LabelEncoder\n",
"le = LabelEncoder()\n",
"\n",
"for col in df.select_dtypes(include=['object']).columns:\n",
" df[col] = le.fit_transform(df[col])\n",
"\n",
"display(df.head())"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 3. Exploratory Data Analysis (EDA)\n",
"Visualize churn distribution, charges vs churn, tenure vs churn, and correlation."
]
},
{
"cell_type": "code",
"execution_count": None,
"metadata": {},
"outputs": [],
"source": [
"plt.figure(figsize=(6,4))\n",
"sns.countplot(data=df, x='Churn')\n",
"plt.title('Churn Distribution (0: No, 1: Yes)')\n",
"plt.show()\n",
"\n",
"plt.figure(figsize=(6,4))\n",
"sns.boxplot(x='Churn', y='MonthlyCharges', data=df)\n",
"plt.title('Monthly Charges vs Churn')\n",
"plt.show()\n",
"\n",
"plt.figure(figsize=(6,4))\n",
"sns.boxplot(x='Churn', y='tenure', data=df)\n",
"plt.title('Tenure vs Churn')\n",
"plt.show()\n",
"\n",
"plt.figure(figsize=(12,8))\n",
"sns.heatmap(df.corr(), annot=False, cmap='coolwarm')\n",
"plt.title('Correlation Heatmap')\n",
"plt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 5. Model Building & 6. Model Evaluation\n",
"Train Logistic Regression, Decision Tree, Random Forest, and KNN. Evaluate using Accuracy, Precision, Recall, F1 Score, and Confusion Matrix."
]
},
{
"cell_type": "code",
"execution_count": None,
"metadata": {},
"outputs": [],
"source": [
"from sklearn.model_selection import train_test_split\n",
"from sklearn.preprocessing import StandardScaler\n",
"from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, confusion_matrix, ConfusionMatrixDisplay\n",
"from sklearn.linear_model import LogisticRegression\n",
"from sklearn.tree import DecisionTreeClassifier\n",
"from sklearn.ensemble import RandomForestClassifier\n",
"from sklearn.neighbors import KNeighborsClassifier\n",
"\n",
"# Prepare data\n",
"X = df.drop('Churn', axis=1)\n",
"y = df['Churn']\n",
"\n",
"# Train-test split\n",
"X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n",
"\n",
"# Feature scaling\n",
"scaler = StandardScaler()\n",
"X_train_scaled = scaler.fit_transform(X_train)\n",
"X_test_scaled = scaler.transform(X_test)\n",
"\n",
"# Initialize models\n",
"models = {\n",
" 'Logistic Regression': LogisticRegression(),\n",
" 'Decision Tree': DecisionTreeClassifier(random_state=42),\n",
" 'Random Forest': RandomForestClassifier(random_state=42),\n",
" 'KNN': KNeighborsClassifier()\n",
"}\n",
"\n",
"# Train and evaluate models\n",
"results = []\n",
"for name, model in models.items():\n",
" model.fit(X_train_scaled, y_train)\n",
" y_pred = model.predict(X_test_scaled)\n",
" \n",
" acc = accuracy_score(y_test, y_pred)\n",
" prec = precision_score(y_test, y_pred)\n",
" rec = recall_score(y_test, y_pred)\n",
" f1 = f1_score(y_test, y_pred)\n",
" cm = confusion_matrix(y_test, y_pred)\n",
" \n",
" results.append({\n",
" 'Model': name,\n",
" 'Accuracy': acc,\n",
" 'Precision': prec,\n",
" 'Recall': rec,\n",
" 'F1 Score': f1\n",
" })\n",
" \n",
" print(f\"\\n{name} Confusion Matrix:\")\n",
" disp = ConfusionMatrixDisplay(confusion_matrix=cm)\n",
" disp.plot(cmap='Blues')\n",
" plt.title(f'{name} Confusion Matrix')\n",
" plt.show()\n",
"\n",
"# Display evaluation metrics\n",
"results_df = pd.DataFrame(results)\n",
"display(results_df)"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"name": "python",
"version": "3.9"
}
},
"nbformat": 4,
"nbformat_minor": 4
}
with open('Customer_Churn_Prediction.ipynb', 'w') as f:
json.dump(notebook, f, indent=4)
print("Notebook generated successfully!")