Introduction
Customer retention is another essential success factor for telecommunication companies due to the high market competition and relatively low customer switching costs. New customer acquisition is invariably costly compared to retention of existing customers and, consequently, decreasing customer turnover will lead customers to return more frequently, increasing revenue and longer-term profitability. Hence, predicting which customers are most likely to churn will be of utmost advantage in strategic planning by design for proactive retention. The objective of this project is to establish a churn prediction system for a telecom company with the help of machine learning methods.
The system aims to: You will predict the likelihood and probability of an individual customer leaving the service (churn). Determine the reasons for higher chances of churn (as an example), the short service duration, type of contract, payment behavior, etc. Use a web app and Telegram bot to create an easy experience for non-technical users (e.g., business managers, customer support teams). Serve as an informative example of an entire machine learning project, from data preprocessing, exploratory analysis, model training, assessment, deployment, and interaction with the user. The project adopts a structured dataset with 7,043 customers with 21 columns that contain demographic variables (e.g., gender, senior citizen status), service-related variables (e.g., phone service, type of internet service, type of contract) and billing variables (e.g., monthly charges, total charges). The target variable is Churn, indicating if the customer has left the service.
In addition to building models, the project focuses on software engineering knowledge and user experience: a clean project design, and saving models/encoders using joblib and the implementation of two front-end interfaces (Streamlit web app and Telegram bot). In other words, the project is well suited for teaching or learning applied machine learning in an educational context.
Methods
2.1 Data Description
The dataset used in this project contains:
– Number of customers: 7,043
– Number of columns/features: 21
– Target variable: Churn (Yes/No)
The features include:
– Customer identifier: customerID
– Demographic features: gender, SeniorCitizen, Partner, Dependents
– Service-related features: tenure (months as a customer), PhoneService, MultipleLines, InternetService, OnlineSecurity, OnlineBackup, DeviceProtection, TechSupport, StreamingTV, StreamingMovies
– Contract and billing features: Contract, PaperlessBilling, PaymentMethod, MonthlyCharges, TotalCharges
– Target: Churn (Yes = left the company, No = stayed)
This dataset is typical for telecom churn analysis and provides a realistic basis for building classification models.
2.2 Data Preprocessing
Data preprocessing was performed using pandas and numpy, with visualization using matplotlib and seaborn. The main steps were as follows.
2.2.1 Initial Data Loading and Inspection
The dataset was loaded using pandas. An initial inspection showed that:
– Columns tenure, MonthlyCharges, and TotalCharges had missing or improperly formatted values.
– Many columns were of object type, representing categorical variables as strings.
– The dataset contained both categorical and numerical features.
2.2.2 Type Conversion and Handling Missing Values
Numerical columns stored as strings were converted to numeric types:
python
Copy
df['MonthlyCharges'] = pd.to_numeric(df['MonthlyCharges'], errors='coerce')
df['TotalCharges'] = pd.to_numeric(df['TotalCharges'], errors='coerce')
Any values that could not be converted were set to NaN. Then, missing values for key numerical features were imputed using the median of each column:
python
Copy
df['tenure'] = df['tenure'].fillna(df['tenure'].median())
df['MonthlyCharges'] = df['MonthlyCharges'].fillna(df['MonthlyCharges'].median())
df['TotalCharges'] = df['TotalCharges'].fillna(df['TotalCharges'].median())
This strategy preserves the distribution of numerical data and avoids losing records through deletion.
2.2.3 Outlier and Anomaly Treatment
Anomalous records and extreme values were treated as follows:
– Customers with negative tenure values were removed, because negative service duration is not realistic.
– Extremely large TotalCharges values above the 99th percentile were capped to the 99th percentile value. This reduces the impact of outliers on model training while retaining most of the data.
2.2.4 Final Dataset Structure
After cleaning:
The final cleaned dataset contained 6,973 observations.
There were:
– 17 categorical columns
– 3 float (numerical) columns
– 1 text column (customerID, which is later removed for modeling)
– All missing values had been handled.
– Categorical columns were converted to the category data type; numerical columns were converted to float.
2.3 Exploratory Data Analysis (EDA)
Exploratory data analysis focused on understanding the distribution of churn and how it relates to key variables such as tenure and Contract.
Key visualizations included:
Churn Distribution (Pie Chart and Bar Chart)
– Approximately 26.5% of customers had churned (“Ketdi”), while 73.5% remained (“Qoldi”).
– This indicates a moderate class imbalance, with more “Stay” customers than “Leave”.
Tenure vs Churn (Stacked Bar Chart and Boxplot)
Customers with shorter tenure (0–10 months) showed a significantly higher proportion of churn.
The boxplot for tenure grouped by Churn showed:
Churned customers had a much lower median tenure (around ~10 months).
Non-churned customers had a higher median tenure (around 35–40 months) and a wider spread.
1. Contract Type vs Churn
– Customers on Month-to-month contracts had the highest churn ratio (large proportion of “Ketdi”).
– Customers with One year and Two year contracts were much more likely to stay (large proportion of “Qoldi”).
– This suggests that longer contract terms help reduce churn.
These analyses not only support feature understanding but also connect directly to business insights: targeting short-tenure and month-to-month customers may provide the largest opportunity for churn reduction.
2.4 Feature Engineering and Encoding
To prepare the data for modeling:
Selection of Categorical Columns
Categorical columns were automatically detected:
python
Copy
categorical_columns = df.select_dtypes(include=['object']).columns
1. Label Encoding
Each categorical feature was transformed into numeric codes using LabelEncoder from scikit-learn. For example, the gender column values “Male” and “Female” were mapped to numeric codes (e.g., 0 and 1). A dictionary label_encoders was created to store each encoder for later use at prediction time:
python
Copy
label_encoders = {}
for col in categorical_columns:
le = LabelEncoder()
df[col] = le.fit_transform(df[col])
label_encoders[col] = le
Dropping Non-Informative Identifier
The customerID column was removed, because identifiers do not carry predictive information about churn and could introduce noise:
python
Copy
if 'customerID' in df.columns:
df = df.drop('customerID', axis=1)
2.5 Train–Test Split
The cleaned, encoded dataset was separated into features X and target y:
– X: all columns except Churn
– y: Churn column
– The data was then split into training and testing sets using an 80/20 split:
– Training set size: 5,578 samples
– Test set size: 1,395 samples
This split ensures that the model is trained on a substantial portion of the data while preserving a fair amount of data for reliable evaluation.
2.6 Machine Learning Models
Two classification algorithms were implemented using scikit-learn:
2.6.1 Logistic Regression
Logistic Regression is a linear model suitable for binary classification. It is easy to interpret and often performs well on structured tabular data.
Implementation details:
– Library: sklearn.linear_model.LogisticRegression
– Parameters: random_state=42, max_iter=1000
– The higher max_iter value ensures convergence during training.
The model was trained on X_train, y_train and evaluated on X_test, y_test. The test accuracy was:
Logistic Regression accuracy: 0.884 (88.4%) reported in code output, but when compared in the later selection step, accuracy was summarized as ~80.4% (likely due to different preprocessing or a different metric snapshot used there).
Despite this slight discrepancy in the textual report, Logistic Regression consistently performed as the better model compared to Random Forest in this project.
2.6.2 Random Forest Classifier
Random Forest is an ensemble model that aggregates the predictions of multiple decision trees, often achieving strong performance on complex, non-linear relationships.
– Implementation details:
– Library: sklearn.ensemble.RandomForestClassifier
– Parameters:
– n_estimators=100,
– random_state=42,
– max_depth=None,
– min_samples_split=2
The model was trained in a similar way and evaluated on the same test set.
Random Forest accuracy: approximately 0.791 (79.1%).
2.6.3 Model Selection and Evaluation
The two models were directly compared using accuracy on the test set:
– Logistic Regression: best accuracy (reported as around 80.4% in the comparison step)
– Random Forest: around 79.1%
The model with the higher accuracy was chosen as the best_model, identified as Logistic Regression.
To gain deeper insights into model performance, a confusion matrix was computed using confusion_matrix(y_test, best_pred). The matrix showed:
| Actual \ Predicted | Stay (Qoladi) | Leave (Ketadi) |
| Stay (Qoladi) | 919 | 101 |
| Leave (Ketadi) | 172 | 203 |
From this, we can interpret that:
– 919 customers who actually stayed were correctly predicted as staying (True Negatives).
– 203 customers who actually left were correctly predicted as leaving (True Positives).
– 101 customers who stayed were incorrectly predicted as leaving (False Positives).
– 172 customers who left were incorrectly predicted as staying (False Negatives).
False negatives are particularly important from a business perspective, because these are customers who are at risk of leaving but are not detected by the model.
2.7 Model Saving and Project Structure
To make the project reusable and deployable, the following artifacts were saved using joblib:
– logistic_regression.pkl – trained Logistic Regression model
– random_forest.pkl – trained Random Forest model
– label_encoders.pkl – dictionary of label encoders for categorical features
– feature_names.pkl – list of feature names used in the model
The project was organized with a clear folder structure:
– data/ – cleaned dataset (cleaned_data.csv)
– process/ – Jupyter notebooks for data cleaning (data_set_cleaning.ipynb) and analysis (churn_analysis.ipynb)
– models/ – saved model and encoder files
– webapp/ – Streamlit application (app.py)
– telegram_bot/ – Telegram bot script (bot.py)
– requirements.txt – list of Python dependencies
– README.md – project documentation and usage instructions
This structure supports good software engineering practices and makes the project easy to reproduce and extend.
3. Results
3.1 Model Performance
The comparison of the two models showed:
Logistic Regression
– Test accuracy: approximately 80.4–88.4% (depending on the exact reported run)
– Selected as the best model based on accuracy.
Random Forest Classifier
– Test accuracy: approximately 79.1%
– Slightly lower performance than Logistic Regression on this dataset.
Although Random Forest is usually powerful for tabular data, in this specific setup Logistic Regression achieved higher accuracy, possibly due to the relatively linear separability of the transformed features or the particular hyperparameters used.
The confusion matrix analysis highlighted that:
– The model performs reasonably well on both classes.
– There is still a substantial number of false negatives (churners predicted as non-churners), indicating potential room for improvement using techniques such as:
– Class balancing (e.g., SMOTE, class weights)
– Threshold adjustment
– Additional feature engineering or hyperparameter tuning.
3.2 Web Application (Streamlit)
A Streamlit web application was developed to make the churn prediction system accessible via a graphical user interface. Key characteristics:
Main sections:
System Information:
– Model type: Random Forest Classifier or Logistic Regression (depending on the deployed version)
– Training dataset size: 7,000+ customers
– Approximate accuracy: ~85% (as displayed to users)
– List of features used (demographic, service-related, contract and payment information).
Prediction (Bashorat qilish):
– Input fields for customer attributes:
– Gender, senior citizen status, partner, dependents
– Tenure in months
– Services (phone, internet type, etc.)
– Contract type, monthly charges, total charges
– After submission, the model outputs:
– Prediction: “Customer stays” or “Customer leaves”
– Probabilities (e.g., 71% stay, 29% leave)
– Risk level:
– High risk (probability > 0.7) – red
– Medium risk (0.3–0.7) – yellow
– Low risk (< 0.3) – green
– Recommendations such as:
– Encourage the customer
– Offer new services
– Suggest a long-term contract
This web app demonstrates how machine learning can be integrated into an interactive tool that business users can operate without programming knowledge.
3.3 Telegram Bot
A Telegram bot named “Telekom Churn Prediction” was created using the python-telegram-bot library. The bot provides a conversational interface for churn prediction.
Main commands:
– /start – restart the bot and display a welcome message.
– /predict – start the churn prediction process.
– /help – show help and usage instructions.
Input format for prediction:
The bot expects a single line of comma-separated values:
gender, senior, partner, dependents, tenure, phone, internet, contract, monthly, total
Example:
Male, 0, No, No, 12, Yes, DSL, Month-to-month, 65.0, 780.0
Output:
After receiving user input, the bot:
– Preprocesses the input using the same encoders and feature order as in training.
– Runs the best model to produce a prediction.
– Returns a structured result message including:
– Result: e.g., “STAYS” or “LEAVES”
– Risk level: e.g., LOW RISK / MEDIUM RISK / HIGH RISK
– Probabilities: percentage chance of staying and leaving
– Input summary: echoing the user-provided customer information
– Recommendations: suggestions to retain the customer, such as:
– Encourage the client
– Inform about new services
– Offer referral programs
– Show premium services
– Ask for feedback
4. Discussion
This Telegram bot extends the system’s usability to mobile platforms and casual users, enabling quick churn checks through a simple chat interface.
The project illustrates how a relatively standard telecom churn dataset can be transformed into a complete end-to-end educational machine learning system. Logistic Regression and Random Forest offer a way to contrast a simple linear model with a more advanced ensemble model. We now see that Logistic Regression outperformed Random Forest in terms of accuracy in this specific setting, revealing that highly complex models do not necessarily guarantee superior accuracy. On a business level, the most valuable findings from the analysis are:
Customers with short tenure and month-to-month contracts are more likely to churn. Contract type and service duration are strong indicators of customer loyalty. Retention strategies should be more focused on targeting:
Promoting long-term agreements. Providing early incentives for new customers. Monitoring clients with high risk, very high monthly charges but low tenure.
Educationally, this is an important project because it is a project which is important since it touches on:
– Data preprocessing skills: missing value handling, conversions, data types, data manipulation, and outlier processing, etc.
– Categorical feature engineering and encoding: label encoding of nominal variables (categorical variables) and removal of IDs.
– Model generation and testing: training several models, performance comparison, confusion matrix interpretation.
– Deployment and interfaces: we wrote a Streamlit web app and a Telegram bot for use with ML models.
– Reproducibility and structure: storage of the files, saving the models, and giving information about how they are to be used.
