List of Topics:
Location Research Breakthrough Possible @S-Logix pro@slogix.in

Office Address

Social List

How to Build a Predictive Model for Telephone Churn Using MLP Classifier

Predictive Model for Telephone Churn Using MLP Classifier

Condition for Preprocessing and Predicting Telephone Churn Using MLP Classifier

  • Description:
    This code preprocesses a telephone churn dataset by encoding categorical variables, handling missing values, and scaling the features. It then trains an MLP Classifier on the data to predict customer churn. Finally, the model's performance is evaluated using confusion matrix, classification report, and accuracy metrics.
Step-by-Step Process
  • Import Libraries:
    Import necessary libraries such as pandas, sklearn, matplotlib, seaborn, and MLPClassifier for preprocessing and model building.
  • Load and Inspect Data:
    Load the dataset from a CSV file and inspect for missing or null values.
  • Preprocess Data:
    Handle missing values, encode categorical variables, and scale features using StandardScaler.
  • Train Model:
    Train the MLP Classifier on the preprocessed dataset with training and testing data split.
  • Evaluate and Visualize:
    Evaluate the model's performance using metrics like classification report, confusion matrix, and accuracy score, and visualize the results using a heatmap.
Sample Source Code
  • # Import Necessary Libraries
    import pandas as pd
    from sklearn.preprocessing import LabelEncoder, StandardScaler
    import matplotlib.pyplot as plt
    import seaborn as sns
    from sklearn.neural_network import MLPClassifier
    from sklearn.model_selection import train_test_split
    import warnings
    warnings.filterwarnings("ignore")
    from sklearn.metrics import (classification_report, confusion_matrix, accuracy_score, f1_score, recall_score, precision_score)
    df = pd.read_csv("/home/soft12/Downloads/sample_dataset/Website/Dataset/churn-bigml-20.csv")

    # Check Nan values
    print("Check Nan values\n")
    print(df.isna().sum())

    # Check Null Values
    print("\n")
    print("Check Null Values\n")
    print(df.isnull().sum())

    # Check Data types
    print("\n")
    print("Check Data types\n")
    print(df.dtypes)

    # Convert object type columns into numeric
    label = LabelEncoder()
    for i in df.columns:
    if df[i].dtypes == 'object':
    df[i] = label.fit_transform(df[i])
    elif df[i].dtypes == 'bool':
    df[i] = df[i].astype(int)

    # Compute the correlation matrix
    correlation_matrix = df.corr()

    # Display the correlation matrix
    print(correlation_matrix)

    # Plot the heatmap
    plt.figure(figsize=(10, 8))
    sns.heatmap(correlation_matrix, annot=True, cmap='coolwarm', fmt='.2f', linewidths=0.5)
    plt.title('Correlation Heatmap')
    plt.show()

    x = df.drop('Churn', axis=1)
    y = df['Churn']

    # Scaling the input data
    scaler = StandardScaler()
    x = scaler.fit_transform(x)

    # Split the train-test data
    X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=.2, random_state=42)

    # Define the MLP Classifier
    mlp = MLPClassifier(hidden_layer_sizes=(64, 64, 32),
    activation='relu',
    solver='adam',
    max_iter=10,
    batch_size=2,
    random_state=42,
    verbose=True)

    # Train the model
    mlp.fit(X_train, y_train)

    # Make predictions
    y_pred = mlp.predict(X_test)

    # Calculate confusion matrix
    cm = confusion_matrix(y_test, y_pred)

    class_labels = ['Not Churn', 'Churn']

    # Plot the heatmap with correct labels
    plt.figure(figsize=(6, 5))
    sns.heatmap(cm, annot=True, fmt='d', cmap='Blues', xticklabels=class_labels, yticklabels=class_labels)
    plt.title('Confusion Matrix Heatmap')
    plt.xlabel('Predicted Label')
    plt.ylabel('True Label')
    plt.show()

    print("___Performance_Metrics___\n")
    print('Classification_Report:\n', classification_report(y_test, y_pred))
    print('Confusion_Matrix:\n', confusion_matrix(y_test, y_pred))
    print('Accuracy_Score: ', accuracy_score(y_test, y_pred))
    print('F1_Score: ', f1_score(y_test, y_pred))
    print('Recall_Score: ', recall_score(y_test, y_pred))
    print('Precision_Score: ', precision_score(y_test, y_pred))
Screenshots
  • MLP Classifier Output Screenshot