help@rskworld.in +91 93305 39277
RSK World
  • Home
  • Development
    • Web Development
    • Mobile Apps
    • Software
    • Games
    • Project
  • Technologies
    • Data Science
    • AI Development
    • Cloud Development
    • Blockchain
    • Cyber Security
    • Dev Tools
    • Testing Tools
  • Blog
  • About
  • Contact

Theme Settings

Color Scheme
Display Options
Font Size
100%
Back to Project
RSK World
customer-churn
/
scripts
RSK World
customer-churn
Customer Churn Dataset
scripts
  • __init__.py332 B
  • data_exploration.py7.9 KB
  • data_preprocessing.py9.6 KB
  • feature_selection.py7.5 KB
  • generate_dataset.py5.7 KB
  • hyperparameter_tuning.py8.9 KB
  • model_training.py19.7 KB
test-commands.batREADME.mddata_exploration.py
README.md
Raw Download

README.md

<!--
Customer Churn Dataset - README
================================
Provided by: RSK World
Website: https://rskworld.in/
Email: help@rskworld.in
Phone: +91 93305 39277
Contact Page: https://rskworld.in/contact.php
-->

# Customer Churn Dataset

Comprehensive customer churn dataset with demographic, usage, and billing information for predicting customer retention and churn analysis.

## Description

This dataset contains customer information including demographics, account details, usage patterns, billing history, and churn status. Perfect for building classification models to predict customer churn, analyzing retention factors, and understanding customer behavior patterns.

## Features

- **Demographic and account information** - Age, gender, location, account type
- **Usage patterns and billing data** - Monthly usage, billing amount, payment method
- **Churn labels and timestamps** - Binary churn status with timestamps
- **Multiple feature categories** - 15+ features across different categories
- **Ready for ML model training** - Preprocessed and structured data

## Dataset Structure

The dataset includes the following columns:

- `CustomerID` - Unique customer identifier
- `Gender` - Customer gender (Male/Female)
- `Age` - Customer age
- `Tenure` - Number of months as customer
- `City` - Customer city
- `AccountType` - Type of account (Basic/Premium/Enterprise)
- `MonthlyUsage` - Monthly service usage
- `BillingAmount` - Monthly billing amount
- `PaymentMethod` - Payment method (Credit Card/Bank Transfer/Other)
- `ContractLength` - Contract length in months
- `SupportCalls` - Number of support calls
- `LastLogin` - Last login date
- `Churn` - Churn status (Yes/No)
- `ChurnDate` - Date when customer churned (if applicable)
- Additional feature columns...

## Technologies Used

- **CSV** - Comma-separated values format
- **Excel** - Microsoft Excel compatible format
- **Pandas** - Python data analysis library
- **NumPy** - Numerical computing library

## Difficulty Level

**Beginner** - Suitable for beginners learning data science and machine learning.

## Installation & Usage

### Prerequisites

```bash
pip install pandas numpy matplotlib seaborn scikit-learn
```

### Loading the Dataset

```python
import pandas as pd
import numpy as np

# Load the dataset
df = pd.read_csv('data/customer_churn.csv')

# Display basic information
print(df.info())
print(df.head())
print(df.describe())
```

### Basic Analysis

```python
# Check for missing values
print(df.isnull().sum())

# Churn distribution
print(df['Churn'].value_counts())

# Visualize churn rate
import matplotlib.pyplot as plt
df['Churn'].value_counts().plot(kind='bar')
plt.title('Churn Distribution')
plt.show()
```

### Advanced Preprocessing Pipeline

- Automatically skips header comments in `data/customer_churn.csv`
- Adds richer features (engagement score, tenure buckets, login recency, billing/usage ratios)
- Encodes categorical bands and scales features for model-friendly inputs
- Balances the training split with SMOTE to handle churn class imbalance
- Saves the ready-to-use dataset to `data/customer_churn_preprocessed.csv`

## Use Cases

1. **Churn Prediction** - Build classification models to predict customer churn
2. **Customer Segmentation** - Identify customer segments based on behavior
3. **Retention Analysis** - Analyze factors affecting customer retention
4. **Behavior Pattern Analysis** - Understand customer usage patterns
5. **ML Model Training** - Train and evaluate various ML algorithms

## Project Structure

```
customer-churn/
├── data/
│ └── customer_churn.csv # Main dataset file
├── scripts/
│ ├── data_exploration.py # Data exploration script
│ ├── data_preprocessing.py # Data preprocessing script
│ └── model_training.py # Model training script
├── notebooks/
│ └── analysis.ipynb # Jupyter notebook for analysis
├── index.html # Demo page
├── README.md # This file
└── customer-churn.zip # Compressed dataset
```

## Contact Information

**Provided by RSK World**

- 🌐 **Website:** [https://rskworld.in/](https://rskworld.in/)
- 📧 **Email:** [help@rskworld.in](mailto:help@rskworld.in)
- 📱 **Phone:** [+91 93305 39277](tel:+919330539277)
- 📞 **Contact Page:** [https://rskworld.in/contact.php](https://rskworld.in/contact.php)

## License

This dataset is provided for educational and research purposes. Please refer to the LICENSE file for more details.

## Contributing

Contributions, issues, and feature requests are welcome! Feel free to contact us through our website.

## Acknowledgments

- Dataset provided by RSK World
- For more resources, visit [https://rskworld.in/](https://rskworld.in/)

scripts/data_exploration.py
Raw Download
Find: Go to:
"""
Customer Churn Dataset - Data Exploration Script
================================================
Provided by: RSK World
Website: https://rskworld.in/
Email: help@rskworld.in
Phone: +91 93305 39277
Contact Page: https://rskworld.in/contact.php
"""

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns

# Set style for better visualizations
sns.set_style("whitegrid")
plt.rcParams['figure.figsize'] = (12, 6)

def load_data(file_path='../data/customer_churn.csv'):
    """
    Load the customer churn dataset
    
    Args:
        file_path (str): Path to the CSV file
        
    Returns:
        pd.DataFrame: Loaded dataset
    """
    df = pd.read_csv(file_path, comment="#", na_values=["", "NA", "NaN"])
    return df

def basic_info(df):
    """
    Display basic information about the dataset
    
    Args:
        df (pd.DataFrame): Dataset to analyze
    """
    print("=" * 60)
    print("DATASET BASIC INFORMATION")
    print("=" * 60)
    print(f"\nDataset Shape: {df.shape}")
    print(f"Number of Rows: {df.shape[0]}")
    print(f"Number of Columns: {df.shape[1]}")
    
    print("\n" + "-" * 60)
    print("DATASET INFO:")
    print("-" * 60)
    print(df.info())
    
    print("\n" + "-" * 60)
    print("FIRST 5 ROWS:")
    print("-" * 60)
    print(df.head())
    
    print("\n" + "-" * 60)
    print("DATASET STATISTICS:")
    print("-" * 60)
    print(df.describe())

def missing_values(df):
    """
    Check for missing values in the dataset
    
    Args:
        df (pd.DataFrame): Dataset to analyze
    """
    print("\n" + "=" * 60)
    print("MISSING VALUES ANALYSIS")
    print("=" * 60)
    missing = df.isnull().sum()
    missing_percent = (missing / len(df)) * 100
    missing_df = pd.DataFrame({
        'Missing Count': missing,
        'Missing Percentage': missing_percent
    })
    missing_df = missing_df[missing_df['Missing Count'] > 0]
    
    if len(missing_df) > 0:
        print(missing_df)
    else:
        print("No missing values found!")

def churn_analysis(df):
    """
    Analyze churn distribution
    
    Args:
        df (pd.DataFrame): Dataset to analyze
    """
    print("\n" + "=" * 60)
    print("CHURN ANALYSIS")
    print("=" * 60)
    
    churn_counts = df['Churn'].value_counts()
    churn_percent = df['Churn'].value_counts(normalize=True) * 100
    
    print("\nChurn Distribution:")
    print(churn_counts)
    print("\nChurn Percentage:")
    print(churn_percent)
    
    # Visualize churn distribution
    plt.figure(figsize=(10, 6))
    plt.subplot(1, 2, 1)
    churn_counts.plot(kind='bar', color=['green', 'red'])
    plt.title('Churn Distribution')
    plt.xlabel('Churn Status')
    plt.ylabel('Count')
    plt.xticks(rotation=0)
    
    plt.subplot(1, 2, 2)
    churn_percent.plot(kind='pie', autopct='%1.1f%%', colors=['green', 'red'])
    plt.title('Churn Percentage')
    plt.ylabel('')
    
    plt.tight_layout()
    plt.savefig('../output/churn_distribution.png')
    plt.show()

def demographic_analysis(df):
    """
    Analyze demographic features
    
    Args:
        df (pd.DataFrame): Dataset to analyze
    """
    print("\n" + "=" * 60)
    print("DEMOGRAPHIC ANALYSIS")
    print("=" * 60)
    
    # Gender distribution
    print("\nGender Distribution:")
    print(df['Gender'].value_counts())
    
    # Age distribution
    print("\nAge Statistics:")
    print(df['Age'].describe())
    
    # Visualize demographics
    fig, axes = plt.subplots(2, 2, figsize=(14, 10))
    
    # Gender distribution
    df['Gender'].value_counts().plot(kind='bar', ax=axes[0, 0], color=['blue', 'pink'])
    axes[0, 0].set_title('Gender Distribution')
    axes[0, 0].set_xlabel('Gender')
    axes[0, 0].set_ylabel('Count')
    
    # Age distribution
    df['Age'].hist(bins=20, ax=axes[0, 1], color='skyblue')
    axes[0, 1].set_title('Age Distribution')
    axes[0, 1].set_xlabel('Age')
    axes[0, 1].set_ylabel('Frequency')
    
    # Tenure distribution
    df['Tenure'].hist(bins=20, ax=axes[1, 0], color='lightgreen')
    axes[1, 0].set_title('Tenure Distribution')
    axes[1, 0].set_xlabel('Tenure (months)')
    axes[1, 0].set_ylabel('Frequency')
    
    # Account type distribution
    df['AccountType'].value_counts().plot(kind='bar', ax=axes[1, 1], color='orange')
    axes[1, 1].set_title('Account Type Distribution')
    axes[1, 1].set_xlabel('Account Type')
    axes[1, 1].set_ylabel('Count')
    axes[1, 1].tick_params(axis='x', rotation=45)
    
    plt.tight_layout()
    plt.savefig('../output/demographic_analysis.png')
    plt.show()

def usage_billing_analysis(df):
    """
    Analyze usage and billing patterns
    
    Args:
        df (pd.DataFrame): Dataset to analyze
    """
    print("\n" + "=" * 60)
    print("USAGE & BILLING ANALYSIS")
    print("=" * 60)
    
    print("\nMonthly Usage Statistics:")
    print(df['MonthlyUsage'].describe())
    
    print("\nBilling Amount Statistics:")
    print(df['BillingAmount'].describe())
    
    # Visualize usage and billing
    fig, axes = plt.subplots(2, 2, figsize=(14, 10))
    
    # Monthly usage distribution
    df['MonthlyUsage'].hist(bins=30, ax=axes[0, 0], color='purple')
    axes[0, 0].set_title('Monthly Usage Distribution')
    axes[0, 0].set_xlabel('Monthly Usage')
    axes[0, 0].set_ylabel('Frequency')
    
    # Billing amount distribution
    df['BillingAmount'].hist(bins=30, ax=axes[0, 1], color='teal')
    axes[0, 1].set_title('Billing Amount Distribution')
    axes[0, 1].set_xlabel('Billing Amount ($)')
    axes[0, 1].set_ylabel('Frequency')
    
    # Usage vs Churn
    df.boxplot(column='MonthlyUsage', by='Churn', ax=axes[1, 0])
    axes[1, 0].set_title('Monthly Usage by Churn Status')
    axes[1, 0].set_xlabel('Churn Status')
    axes[1, 0].set_ylabel('Monthly Usage')
    
    # Billing vs Churn
    df.boxplot(column='BillingAmount', by='Churn', ax=axes[1, 1])
    axes[1, 1].set_title('Billing Amount by Churn Status')
    axes[1, 1].set_xlabel('Churn Status')
    axes[1, 1].set_ylabel('Billing Amount ($)')
    
    plt.tight_layout()
    plt.savefig('../output/usage_billing_analysis.png')
    plt.show()

def correlation_analysis(df):
    """
    Analyze correlations between numerical features
    
    Args:
        df (pd.DataFrame): Dataset to analyze
    """
    print("\n" + "=" * 60)
    print("CORRELATION ANALYSIS")
    print("=" * 60)
    
    # Select numerical columns
    numerical_cols = df.select_dtypes(include=[np.number]).columns.tolist()
    
    if 'CustomerID' in numerical_cols:
        numerical_cols.remove('CustomerID')
    
    correlation_matrix = df[numerical_cols].corr()
    
    print("\nCorrelation Matrix:")
    print(correlation_matrix)
    
    # Visualize correlation matrix
    plt.figure(figsize=(10, 8))
    sns.heatmap(correlation_matrix, annot=True, cmap='coolwarm', center=0,
                square=True, linewidths=1, cbar_kws={"shrink": 0.8})
    plt.title('Correlation Matrix of Numerical Features')
    plt.tight_layout()
    plt.savefig('../output/correlation_matrix.png')
    plt.show()

def main():
    """
    Main function to run all analyses
    """
    print("Customer Churn Dataset - Data Exploration")
    print("Provided by: RSK World (https://rskworld.in/)")
    print("-" * 60)
    
    # Load data
    df = load_data()
    
    # Run analyses
    basic_info(df)
    missing_values(df)
    churn_analysis(df)
    demographic_analysis(df)
    usage_billing_analysis(df)
    correlation_analysis(df)
    
    print("\n" + "=" * 60)
    print("ANALYSIS COMPLETE")
    print("=" * 60)
    print("\nFor more information, visit: https://rskworld.in/")
    print("Contact: help@rskworld.in | +91 93305 39277")

if __name__ == "__main__":
    main()

280 lines•7.9 KB
python
🚀 Support RSK World

Subscribe to our YouTube channel for latest tutorials & updates!



Click subscribe & support our work ❤️

About RSK World

Founded by Molla Samser, with Designer & Tester Rima Khatun, RSK World is your one-stop destination for free programming resources, source code, and development tools.

Founder: Molla Samser
Designer & Tester: Rima Khatun

Development

  • Game Development
  • Web Development
  • Mobile Development
  • AI Development
  • Development Tools

Legal

  • Terms & Conditions
  • Privacy Policy
  • Disclaimer

Contact Info

Nutanhat, Mongolkote
Purba Burdwan, West Bengal
India, 713147

+91 93305 39277

hello@rskworld.in
support@rskworld.in

© 2026 RSK World. All rights reserved.

Content used for educational purposes only. View Disclaimer