Home Backend Development Python Tutorial Decision Tree Classifier Example to Predict Customer Churn

Decision Tree Classifier Example to Predict Customer Churn

Dec 10, 2024 pm 01:30 PM

Decision Tree Classifier Example to Predict Customer Churn

Decision Tree Classifier Example to Predict Customer Churn

Overview

This project demonstrates how to predict customer churn (whether a customer leaves a service) using a Decision Tree Classifier. The dataset includes features like age, monthly charges, and customer service calls, with the goal of predicting whether a customer will churn or not.

The model is trained using Scikit-learn's Decision Tree Classifier, and the code visualizes the decision tree to better understand how the model is making decisions.


Technologies Used

  • Python 3.x: Primary language used for building the model.
  • Pandas: For data manipulation and handling datasets.
  • Matplotlib: For data visualization (plotting decision tree).
  • Scikit-learn: For machine learning, including model training and evaluation.

Steps Explained

1. Import Necessary Libraries

import pandas as pd
import matplotlib.pyplot as plt
import warnings
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import accuracy_score
from sklearn import tree
Copy after login
Copy after login
Copy after login
Copy after login
  • Pandas (pd):

    • This is used for data manipulation and loading data into DataFrame format. DataFrames allow you to organize and manipulate structured data like tables (rows and columns).
  • Matplotlib (plt):

    • This is a plotting library used to visualize data. Here, it’s used to plot the decision tree graphically, which helps in understanding how decisions are made at each node of the tree.
  • Warnings (warnings):

    • The warnings module is used to suppress or handle warnings. In this code, we’re ignoring unnecessary warnings to keep the output clean and readable.
  • Scikit-learn libraries:

    • train_test_split: This function splits the dataset into training and testing subsets. Training data is used to fit the model, and testing data is used to evaluate its performance.
    • DecisionTreeClassifier: This is the model that will be used to classify the data and predict customer churn. Decision Trees work by creating a tree-like model of decisions based on the features.
    • accuracy_score: This function calculates the accuracy of the model by comparing the predicted values with the actual values of the target variable (Churn).
    • tree: This module includes functions for visualizing the decision tree once it is trained.

2. Suppressing Warnings

import pandas as pd
import matplotlib.pyplot as plt
import warnings
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import accuracy_score
from sklearn import tree
Copy after login
Copy after login
Copy after login
Copy after login
  • This line tells Python to ignore all warnings. It can be helpful when you're running models and don't want warnings (such as those about deprecated functions) to clutter the output.

3. Creating a Synthetic Dataset

warnings.filterwarnings("ignore")
Copy after login
Copy after login
  • Here, we create a synthetic dataset for the project. This dataset simulates customer information for a telecom company, with features such as Age, MonthlyCharge, CustomerServiceCalls, and the target variable Churn (whether the customer churned or not).

    • CustomerID: Unique identifier for each customer.
    • Age: Customer’s age.
    • MonthlyCharge: Monthly bill of the customer.
    • CustomerServiceCalls: The number of times a customer called customer service.
    • Churn: Whether the customer churned (Yes/No).
  • Pandas DataFrame: The data is structured as a DataFrame (df), a 2-dimensional labeled data structure, allowing easy manipulation and analysis of data.

4. Splitting Data into Features and Target Variable

import pandas as pd
import matplotlib.pyplot as plt
import warnings
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import accuracy_score
from sklearn import tree
Copy after login
Copy after login
Copy after login
Copy after login
  • Features (X): The independent variables that are used to predict the target. In this case, it includes Age, MonthlyCharge, and CustomerServiceCalls.
  • Target variable (y): The dependent variable, which is the value you are trying to predict. Here, it is the Churn column, which indicates whether a customer will churn or not.

5. Splitting the Data into Training and Testing Sets

warnings.filterwarnings("ignore")
Copy after login
Copy after login
  • train_test_split splits the dataset into two parts: a training set (used to train the model) and a testing set (used to evaluate the model).
    • test_size=0.3: 30% of the data is set aside for testing, and the remaining 70% is used for training.
    • random_state=42 ensures reproducibility of results by fixing the seed for the random number generator.

6. Training the Decision Tree Model

data = {
    'CustomerID': range(1, 101),  # Unique ID for each customer
    'Age': [20, 25, 30, 35, 40, 45, 50, 55, 60, 65]*10,  # Age of customers
    'MonthlyCharge': [50, 60, 70, 80, 90, 100, 110, 120, 130, 140]*10,  # Monthly bill amount
    'CustomerServiceCalls': [1, 2, 3, 4, 0, 1, 2, 3, 4, 0]*10,  # Number of customer service calls
    'Churn': ['No', 'No', 'Yes', 'No', 'Yes', 'No', 'Yes', 'Yes', 'No', 'Yes']*10  # Churn status
}

df = pd.DataFrame(data)
print(df.head())
Copy after login
  • DecisionTreeClassifier() initializes the decision tree model.
  • clf.fit(X_train, y_train) trains the model using the training data. The model learns patterns from the X_train features to predict the y_train target variable.

7. Making Predictions

X = df[['Age', 'MonthlyCharge', 'CustomerServiceCalls']]  # Features
y = df['Churn']  # Target Variable
Copy after login
  • clf.predict(X_test): After the model is trained, it is used to make predictions on the test set (X_test). These predicted values are stored in y_pred, and we will compare them with the actual values (y_test) to evaluate the model.

8. Evaluating the Model

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
Copy after login
  • accuracy_score(y_test, y_pred) calculates the accuracy of the model by comparing the predicted churn labels (y_pred) with the actual churn labels (y_test) from the test set.
  • The accuracy is a measure of how many predictions were correct. It is printed out for evaluation.

9. Visualizing the Decision Tree

clf = DecisionTreeClassifier()
clf.fit(X_train, y_train)
Copy after login
  • tree.plot_tree(clf, filled=True): Visualizes the trained decision tree model. The filled=True argument colors the nodes based on the class label (Churn/No Churn).
  • feature_names: Specifies the names of the features (independent variables) to display in the tree.
  • class_names: Specifies the class labels for the target variable (Churn).
  • plt.show(): Displays the tree visualization.

Running the Code

  1. Clone the repository or download the script.
  2. Install dependencies:
import pandas as pd
import matplotlib.pyplot as plt
import warnings
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import accuracy_score
from sklearn import tree
Copy after login
Copy after login
Copy after login
Copy after login
  1. Run the Python script or Jupyter notebook to train the model and visualize the decision tree.

The above is the detailed content of Decision Tree Classifier Example to Predict Customer Churn. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1668
14
PHP Tutorial
1273
29
C# Tutorial
1256
24
Python: Games, GUIs, and More Python: Games, GUIs, and More Apr 13, 2025 am 12:14 AM

Python excels in gaming and GUI development. 1) Game development uses Pygame, providing drawing, audio and other functions, which are suitable for creating 2D games. 2) GUI development can choose Tkinter or PyQt. Tkinter is simple and easy to use, PyQt has rich functions and is suitable for professional development.

Python vs. C  : Learning Curves and Ease of Use Python vs. C : Learning Curves and Ease of Use Apr 19, 2025 am 12:20 AM

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

Python and Time: Making the Most of Your Study Time Python and Time: Making the Most of Your Study Time Apr 14, 2025 am 12:02 AM

To maximize the efficiency of learning Python in a limited time, you can use Python's datetime, time, and schedule modules. 1. The datetime module is used to record and plan learning time. 2. The time module helps to set study and rest time. 3. The schedule module automatically arranges weekly learning tasks.

Python vs. C  : Exploring Performance and Efficiency Python vs. C : Exploring Performance and Efficiency Apr 18, 2025 am 12:20 AM

Python is better than C in development efficiency, but C is higher in execution performance. 1. Python's concise syntax and rich libraries improve development efficiency. 2.C's compilation-type characteristics and hardware control improve execution performance. When making a choice, you need to weigh the development speed and execution efficiency based on project needs.

Which is part of the Python standard library: lists or arrays? Which is part of the Python standard library: lists or arrays? Apr 27, 2025 am 12:03 AM

Pythonlistsarepartofthestandardlibrary,whilearraysarenot.Listsarebuilt-in,versatile,andusedforstoringcollections,whereasarraysareprovidedbythearraymoduleandlesscommonlyusedduetolimitedfunctionality.

Python: Automation, Scripting, and Task Management Python: Automation, Scripting, and Task Management Apr 16, 2025 am 12:14 AM

Python excels in automation, scripting, and task management. 1) Automation: File backup is realized through standard libraries such as os and shutil. 2) Script writing: Use the psutil library to monitor system resources. 3) Task management: Use the schedule library to schedule tasks. Python's ease of use and rich library support makes it the preferred tool in these areas.

Learning Python: Is 2 Hours of Daily Study Sufficient? Learning Python: Is 2 Hours of Daily Study Sufficient? Apr 18, 2025 am 12:22 AM

Is it enough to learn Python for two hours a day? It depends on your goals and learning methods. 1) Develop a clear learning plan, 2) Select appropriate learning resources and methods, 3) Practice and review and consolidate hands-on practice and review and consolidate, and you can gradually master the basic knowledge and advanced functions of Python during this period.

Python vs. C  : Understanding the Key Differences Python vs. C : Understanding the Key Differences Apr 21, 2025 am 12:18 AM

Python and C each have their own advantages, and the choice should be based on project requirements. 1) Python is suitable for rapid development and data processing due to its concise syntax and dynamic typing. 2)C is suitable for high performance and system programming due to its static typing and manual memory management.

See all articles