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

Office Address

Social List

How to Build and Evaluate an ANN Model for Customer Churn Prediction Using Python

ANN Model for Customer Churn Prediction in Python

Condition for Building and Evaluating an ANN Model for Customer Churn Prediction Using Python

  • Description:
    This code demonstrates building and evaluating an Artificial Neural Network (ANN) model to predict customer churn using the Churn_Modelling dataset. It includes data preprocessing steps like encoding categorical variables, scaling features, addressing class imbalance, and splitting data into training and testing sets. The model is trained with binary cross-entropy loss, and performance metrics such as accuracy, precision, recall, and a confusion matrix are calculated and visualized.
Step-by-Step Process
  • Import Libraries:
    Import the necessary libraries for data manipulation, visualization, and model building.
  • Examine the Dataset:
    Check for missing or NaN values in the dataset.
  • Preprocess the Data:
    Convert categorical features into numeric using LabelEncoder, scale the data using StandardScaler.
  • Visualize the Data:
    Visualize class distribution and any class imbalance using Seaborn.
  • Build and Train the ANN Model:
    Create a neural network with hidden layers and ReLU activation, using sigmoid for output.
  • Evaluate the Model:
    Calculate accuracy, precision, recall, F1-score, and plot the confusion matrix.
Sample Source Code
  • # Code for ANN Model

    import pandas as pd
    from sklearn.preprocessing import LabelEncoder, StandardScaler
    import matplotlib.pyplot as plt
    import seaborn as sns
    from sklearn.model_selection import train_test_split
    import warnings
    warnings.filterwarnings("ignore")

    from tensorflow.keras.layers import Dense, Input
    from tensorflow.keras.models import Model

    from sklearn.metrics import (classification_report, confusion_matrix, accuracy_score, f1_score, recall_score, precision_score)

    df = pd.read_csv("/path/to/Churn_Modelling.csv")

    print("Columns")
    print(df.columns)

    # Check for missing values
    print("Checking Missing Values")
    print(df.isnull().sum())

    # Convert categorical features into numeric
    label = LabelEncoder()
    for i in df.columns:
    if df[i].dtypes == object:
    df[i] = label.fit_transform(df[i])

    # Split dataset
    x = df.drop('Exited', axis=1)
    y = df['Exited']

    # Normalize data
    scaler = StandardScaler()
    x = scaler.fit_transform(x)

    # Plot class distribution
    sns.countplot(x=y)

    # Split train and test data
    X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.2, random_state=42)

    def ANN_model(input_shape):
    inputs = Input(shape=(input_shape,))
    layer1 = Dense(64, activation='relu')(inputs)
    layer2 = Dense(32, activation='relu')(layer1)
    output_layer = Dense(1, activation='sigmoid')(layer2)
    ann_model = Model(inputs=inputs, outputs=output_layer)
    ann_model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
    return ann_model

    model = ANN_model(X_train.shape[1])

    model.fit(X_train, y_train, batch_size=2, epochs=10, validation_data=(X_test, y_test))

    y_pred = model.predict(X_test)
    y_pred = [1 if i > 0.5 else 0 for i in y_pred]

    print("Performance Metrics")
    print('Classification Report:', classification_report(y_test, y_pred))
    print('Confusion Matrix:', confusion_matrix(y_test, y_pred))
    print('Accuracy:', accuracy_score(y_test, y_pred))
    print('F1 Score:', f1_score(y_test, y_pred))
    print('Recall:', recall_score(y_test, y_pred))
    print('Precision:', precision_score(y_test, y_pred))

    # Plot Confusion Matrix
    cm = confusion_matrix(y_test, y_pred)
    plt.figure(figsize=(6, 6))
    sns.heatmap(cm, annot=True, fmt='d', cmap='Blues')
    plt.show()
Screenshots
  • ANN Model Output