scieee AI-readable full text Open interactive document viewer

Application of Predicted Models in Debt Management: Developing a Machine Learning Algorithm to Predict Customer Risk at EDP Comercial

Melo, Inês Pires

Abstract

This report is a result of a nine-month internship at EDP Comercial where the main project of research was the application of artificial intelligence tools in the field of debt management. Debt management involves a set of strategies and processes aimed at reducing or eliminating debt and the use of artificial intelligence has shown great potential to optimize these processes and minimize the risk of debt for individuals and organizations. In terms of monitoring and controlling the creditworthiness and quality of clients, debt management has mainly been responsive and reactive, attempting to recover losses after a client has become delinquent. There is a gap in the knowledge of how to proactively identify at-risk accounts before they fall behind on payments. To avoid the constant reactive response in the field, it was developed a machine-learning algorithm that predicts the risk of a client becoming in debt by analyzing their scorecard, which measures the quality of a client based on their infringement history. After preprocessing the data, XGBoost was implemented to a dataset of 3M customers with at least one active contract on EDP, on electricity or gas. Hyperparameter tuning was performed on the model to reach an F1 score of 0.7850 on the training set and 0.7835 on the test set. The results were discussed and based on those, recommendations and improvements were also identified.

Full text

i Master Degree Program in Data Science and Advanced Analytics Application of Predicted Models in Debt Management Developing a Machine Learning Algorithm to Predict Customer Risk at EDP Comercial Inês Pires Melo Internship Report presented as partial requirement for obtaining the Master Degree Program in Data Science and Advanced Analytics NOVA Information Management School Instituto Superior de Estatística e Gestão de Informação Universidade Nova de Lisboa MDSAA i [this page should not be included in the digital version. Its purpose is only for the printed version] Title: Subtitle: Student full name MDSAA 2022 i NOVA Information Management School Instituto Superior de Estatística e Gestão de Informação Universidade Nova de Lisboa APPLICATION OF PREDICTED MODELS IN DEBT MANAGEMENT by Inês Pires Melo Internship report presented as partial requirement for obtaining the Master’s degree in Advanced Analytics, with a Specialization in Data Science Supervisor: Mauro Castelli February 2023 ii STATEMENT OF INTEGRITY I hereby declare having conducted this academic work with integrity. I confirm that I have not used plagiarism or any form of undue use of information or falsification of results along the process leading to its elaboration. I further declare that I have fully acknowledge the Rules of Conduct and Code of Honor from the NOVA Information Management School. Inês Melo Lisboa, 2023 iii ACKNOWLEDGEMENTS I would like to express my gratitude to my internship team at EDP for their unwavering support and positive spirit throughout my internship, especially to Hélder Oliveira, who was always available to help me and believed in me from the start. I also cannot thank my family enough, my parents and sister, who have always supported me and been a great pillar, as well as my friends and housemates, Mariana and Sofia, who put up with me every day and have my full heart. Lastly, I would like to thank my professors whose guidance and mentorship have been instrumental in shaping not only my knowledge but also my character and overall development as an individual. iv ABSTRACT This report is a result of a nine-month internship at EDP Comercial where the main project of research was the application of artificial intelligence tools in the field of debt management. Debt management involves a set of strategies and processes aimed at reducing or eliminating debt and the use of artificial intelligence has shown great potential to optimize these processes and minimize the risk of debt for individuals and organizations. In terms of monitoring and controlling the creditworthiness and quality of clients, debt management has mainly been responsive and reactive, attempting to recover losses after a client has become delinquent. There is a gap in the knowledge of how to proactively identify at-risk accounts before they fall behind on payments. To avoid the constant reactive response in the field, it was developed a machine-learning algorithm that predicts the risk of a client becoming in debt by analyzing their scorecard, which measures the quality of a client based on their infringement history. After preprocessing the data, XGBoost was implemented to a dataset of 3M customers with at least one active contract on EDP, on electricity or gas. Hyperparameter tuning was performed on the model to reach an F1 score of 0.7850 on the training set and 0.7835 on the test set. The results were discussed and based on those, recommendations and improvements were also identified. KEYWORDS Debt Management; Machine Learning; Scorecard Prediction; Artificial intelligence v INDEX 1. Introduction .................................................................................................................. 1 1.1. Company Overview ............................................................................................... 1 1.2. The project ............................................................................................................. 2 2. Literature review .......................................................................................................... 3 2.1. Artificial intelligence (AI) ....................................................................................... 3 2.2. Data Mining ........................................................................................................... 3 2.3. CRISP-DM ............................................................................................................... 4 2.4. Machine Learning .................................................................................................. 6 2.4.1. Decision Trees ................................................................................................ 6 2.4.2. Gradient Boosting ........................................................................................... 8 2.4.3. XGBoost .......................................................................................................... 8 2.5. Classification Model Evaluation .......................................................................... 10 2.5.1. Confusion Matrix .......................................................................................... 10 2.5.2. Accuracy ....................................................................................................... 11 2.5.3. Precision ....................................................................................................... 11 2.5.4. Recall ............................................................................................................ 11 2.5.5. F1 Score ........................................................................................................ 12 2.6. Debt management in the energy sector ............................................................. 12 3. Methodology .............................................................................................................. 14 3.1. Business understanding ....................................................................................... 14 3.2. Data Understanding ............................................................................................ 14 3.2.1. Data sources ................................................................................................. 14 3.2.2. Main Findings ............................................................................................... 16 3.2.3. Target analysis .............................................................................................. 19 3.3. Data Preparation ................................................................................................. 20 3.3.1. Feature engineering ..................................................................................... 20 3.3.2. Adding demographic features ...................................................................... 20 3.3.3. Missing values .............................................................................................. 21 3.3.4. Outlier detection .......................................................................................... 21 3.3.5. Categorical features ..................................................................................... 21 3.3.6. Feature scaling.............................................................................................. 21 3.3.7. Target distribution ........................................................................................ 22 3.3.8. Dealing with correlated features.................................................................. 22 vi 3.3.9. Feature Selection .......................................................................................... 23 3.4. Model Selection And Evaluation ......................................................................... 23 4. Results and discussion ................................................................................................ 25 4.1. Evaluating first results ......................................................................................... 25 4.2. Hyperparameter tuning ....................................................................................... 25 4.3. Discuss final results ............................................................................................. 28 5. Conclusion .................................................................................................................. 30 6. Limitations and recommendations for future works ................................................. 31 7. References .................................................................................................................. 32 Appendix.......................................................................................................................... 34 vii LIST OF FIGURES Figura 1 - Phases of CRISP-DM Process Model Source: (Martinez-Plumed, F. et al., 2000) ....... 5 Figura 2- Elements of a Decision tree ......................................................................................... 7 Figura 3 - L1 and L2 Regularization formula .............................................................................. 9 Figura 4 - Average expeted annual Consumption by type of consumption ............................. 16 Figura 5 - Pie Chart of Types of Consumption .......................................................................... 16 Figura 6 - Client distribution of years of consumption ............................................................. 16 Figura 7- Distribution of types of Contracts ............................................................................. 17 Figura 8 - Target distribution ................................................................................................... 19 Figura 9 - F1 Score vs Learning rate ......................................................................................... 26 Figura 10 - F1 Score vs Number of estimators ......................................................................... 27 Figura 11 - Confusion Matrix of Test set .................................................................................. 28 Figura 12- Outliers Visualization .............................................................................................. 35 Figura 13- Ouliers Visualizations part 2 ................................................................................... 36 Figura 14- Pearson's correlation matrix ................................................................................... 37 Figura 15 - Spearman's rank correlation matrix ...................................................................... 38 Figura 16 - Feature Selection Decision Trees: Gini and Entropy ............................................... 39 Figura 17- Feature Selection using Ridge Classifier .................................................................. 40 Figura 18- Feature Selection using Lasso Classifier .................................................................. 41 5 that the CRISP-DM approach is flexible, allowing for modifications to be made to fit the specific needs of a project. As it is shown in the figure, the six steps of the CRISP-DM process are as follows: Business Understanding: In this step, the objectives of the project are defined and the requirements of the stakeholders are gathered. The goals and expected outcomes of the project are identified, and the feasibility of the project is assessed. It is important to evaluate the business situation to understand what resources are available and what resources will be required. (Schröer, Kruse, & Gómez, 2021). Data Understanding: the data that is to be used for the project is collected and summarized. Data exploration and visualization are performed to gain an understanding of the structure and contents of the data. (Schröer, Kruse, & Gómez, 2021). Data Preparation: In this step, the data is cleaned, transformed, and integrated to prepare it for analysis. This may involve removing duplicates, dealing with missing values, and dealing with outliers. To select the appropriate data for analysis, specific criteria need to be established for what data should be included and excluded. If the data is of low quality, cleaning methods can be employed to address the issue. (Schröer, Kruse, & Gómez, 2021). Modeling: In this step, statistical and machine learning models are applied to the data to uncover patterns and relationships. This step is where the data is mined for insights. In the data modeling phase, the appropriate modeling technique is chosen and a test case and model are developed. The selection of the data mining technique to be used typically depends on the business problem and the data available. (Schröer, Kruse, & Gómez, 2021). Evaluation: In this step, the results of the modeling process are evaluated to determine if they meet the goals and expectations of the project. During the evaluation phase, the outcomes are measured against the predetermined business goals. This requires interpreting the results and identifying any necessary follow-up actions. Additionally, it is important to conduct a general review of the entire data mining process. (Schröer, Kruse, & Gómez, 2021). Figura 1 - Phases of CRISP-DM Process Model Source: (Martinez-Plumed, F. et al., 2000) 6 Deployment: In this final step, the results of the project are deployed and the findings are communicated to the stakeholders. The results can be used to make decisions, solve problems, or support operations. 2.4. MACHINE LEARNING Machine learning is a subset of artificial intelligence that concentrates on developing algorithms capable of learning from data and making predictions or decisions. These algorithms have found numerous applications, including image recognition, natural language processing, and forecasting customer behaviour. (James, Witten, Hastie, & Tibshirani, 2021). There are four main types of machine learning: • Supervised learning: a type of machine learning in which the input data used to train the algorithm includes the correct answers, also known as labels. This type of learning is often used for classification tasks, such as distinguishing between spam and non-spam emails in a spam filter. The algorithm is fed examples of both types of emails, along with their corresponding labels, and uses this information to learn how to accurately classify new, previously unseen emails. (Géron, 2019) • Unsupervised learning: a type of machine learning that does not use labelled data for training. Instead, it allows the algorithm to find patterns and relationships in the data on its own. In other words, the algorithm must identify similarities and differences in the data without being told what these patterns are. Clustering is a common application of unsupervised learning, where the algorithm groups similar data points together based on their characteristics. (Géron, 2019) • Semi-Supervised learning: the model is trained using a mixture of labelled and unlabeled data. The goal of semi-supervised learning is to make the most of the labelled data while also taking advantage of the unlabeled data to improve the model's performance. • Reinforcement learning: the model learns through trial and error. The model receives feedback in the form of rewards or penalties for its actions, and it uses this feedback to make decisions about which actions to take in the future. Reinforcement learning is a technique used in robotics, gaming, and navigation, among other areas, to train a model by allowing it to learn through trial and error without human guidance. (Géron, 2019) In the energy field, machine learning is increasingly being applied to improve the efficiency and effectiveness of energy production, distribution, and consumption. The next topics will discuss several machine learning algorithms that will be used or it is important to know the concept of them in this research. 2.4.1. Decision Trees Decision Trees are a popular and widely used supervised machine learning technique. They are used for both regression and classification problems and they are tree-based models that are easy to interpret and implement. Decision Trees are used to determine a decision or prediction by breaking down a large dataset into smaller and simpler sub-problems until reaching a conclusion. 7 As stated by (Breiman, Friedman, Olshen, & Stone, 1984), A decision tree is a graphical representation that uses tree-like branches to display different possible outcomes based on the values of various attributes or features. Each branch in the tree represents a different path or choice, and each internal node is a test or decision based on one of the attributes. The terminal nodes, or leaves, represent the final classification or prediction. An example of a graphical representation of a decision tree: Construction of Decision Tree The learning algorithms for decision trees construct a tree by recursively splitting instances into subsets (James, Witten, Hastie, & Tibshirani, 2021). The splits in the tree are determined based on the feature values, with the objective of maximizing the reduction in impurity in the target variable. The selection of the method for dividing the data at each level of a decision tree affects both the shape of the tree and the effectiveness of the classification. Two popular methods for this are the Gini impurity and information gain. (Hastie, Tibshirani, & Friedman, 2008) "Gini impurity" is calculated as the sum of the squared probabilities of each class occurring in the node, and ranges from 0 (pure node) to 1 (equal distribution of classes). Suppose we have a dataset D with samples from k different classes. The probability of a sample belonging to a specific class i at a certain node can be represented by 𝑝𝑖. The Gini Impurity of D can be defined as: 𝐺𝑖𝑛𝑖(𝐷)=1 − ∑𝑝𝑖2 𝑘 𝑖=1 The idea behind “information gain” is that the feature that provides the most information about the target variable, or the most reduction in the uncertainty of the target variable, should be selected as the splitting feature. A feature with a high information gain is considered to be more useful for splitting the data into different classes or categories. In theory, it represents the reduction in entropy achieved by partitioning the data on a particular feature. Entropy, on the other hand, is a measure of the amount of uncertainty or randomness in the data. In decision tree models, it is used to evaluate the purity of a set of examples. The formula for calculating information gain is as follows: Information Gain = Entropy(parent) - [Weighted Average]*Entropy(children) Where Entropy(parent) is the entropy of the parent node, and Entropy(children) is the entropy of the child nodes created by splitting the parent node. The weighted average is taken over all child nodes, Figura 2- Elements of a Decision tree 8 with the weight given by the proportion of examples in each child node. Entropy is calculated as follows: 𝐸(𝑆)=∑𝑝𝑖 𝑐 𝑖=1 𝑙𝑜𝑔2𝑝𝑖 Where S represents the sample in which we want to calculate the entropy and p is the proportion of examples in a given class. The entropy is maximum when the data is equally distributed among all classes, and minimum when all the data belongs to a single class. 2.4.2. Gradient Boosting Gradient boosting is a popular algorithm used in machine learning that can solve various classification and regression problems. It works by combining multiple weak prediction models, often decision trees, into a single strong prediction model, known as an ensemble. This process is done in a way that gradually improves the overall performance of the model. (Friedman, 2001) In a gradient boosting algorithm, the base learner is typically a decision tree. The algorithm builds an initial model, and then in each subsequent iteration, a new decision tree is added to the ensemble that tries to correct the errors of the previous trees. As described by (Chen & Guestrin, 2016), Gradient boosting is an algorithm that creates a prediction model by adding multiple weak prediction models together in a step-by-step manner. This process enables it to optimize any loss function that can be differentiated. The main idea behind Gradient Boosting aims to minimize the error of a model by adding new models to the existing ones. This is done in a step-by-step manner, where each new model is added to minimize the loss function at each iteration. The method can be thought of as an approximation to the steepest descent optimization of a general loss function. (Hastie, Tibshirani, & Friedman, 2008). One of the most popular implementations of gradient boosting is XGBoost (Chen & Guestrin, 2016), which has become a de facto standard for many machine learning tasks. XGBoost provides a highly efficient and scalable implementation of gradient boosting that can handle large datasets and highdimensional feature spaces. 2.4.3. XGBoost XGBoost stands for Extreme Gradient Boosting and is an advanced gradient boosting algorithm. XGBoost has been a popular choice for machine learning and data science tasks because of its high level of efficiency, robustness, and accuracy, specially when handling problems that involve large datasets and multi-class classification. In XGBoost, several decision trees are combined together to make more accurate predictions, which is known as an ensemble learning method. At its core, XGBoost uses decision trees as weak learners, which are combined to form a stronger model. It creates these decision trees iteratively, with each new tree attempting to correct the errors made by the previous tree, this is known as gradient boosting. (Chen & Guestrin, 2016) 9 XGBoost goes beyond the standard gradient boosting framework by adding several enhancements, including: Regularization: To prevent the model from overfitting, the XGBoost algorithm uses regularization techniques such as weight decay, L1 and L2 regularization, and column subsampling. L1 and L2 are two popular forms of regularization, a technique used in machine learning to reduce overfitting. L1 regularization is also called Lasso regularization and adds the absolute values of the coefficients to the loss function. L2 regularization is also called Ridge regularization and adds the squares of the coefficients to the loss function. (Géron, 2019). L1 regularization tends to produce sparse models where many of the coefficients are zero, which can be useful for feature selection, while L2 regularization produces models with smaller but non-zero coefficients. The strength of the regularization penalty is controlled by a hyperparameter, with higher values resulting in more regularization and smaller coefficients. Adjusting the hyperparameters of L1 and L2 regularization can help find a balance between a model's complexity and its capacity to apply to new data, resulting in improved performance on the test set. (Hastie, Tibshirani, & Friedman, 2008). Handling missing values: XGBoost can handle missing values automatically. It can handle missing values in the data by learning how to replace them with a default value. It does this by learning a direction for missing value imputation during the tree construction process. At each node, the algorithm checks if a feature is missing a value and decides on the direction to take based on the gain, which is calculated as the difference between the parent node's loss and the weighted sum of losses in the child nodes. This process helps to improve the performance of the algorithm on data with missing values. (Chen & Guestrin, 2016) Parallel processing: XGBoost can take advantage of multiple CPUs or GPUs to train and make predictions faster. XGBoost is known for its ability to efficiently use available computational resources, and one of its main strengths is its ability to parallelize the construction and evaluation of decision trees. This allows XGBoost to take advantage of multi-core processors and distributed computing environments for faster processing. (Chen & Guestrin, 2016) Figura 3 - L1 and L2 Regularization formula 10 Weighted instances: XGBoost allows you to assign weights to instances, which can be useful for imbalanced datasets. Weighting instances is a technique that can be used to balance the positive and negative weights of imbalanced datasets. By assigning weights to the instances, the algorithm can focus on the underrepresented class and improve its performance on the test set. (Chen & Guestrin, 2016) The final model in XGBoost is a combination of all the decision trees created during training. Each tree outputs a prediction, and these predictions are combined using weighted averaging. The weights assigned to each tree depend on its performance during training. 2.5. CLASSIFICATION MODEL EVALUATION Classification metrics are used to assess the accuracy and performance of a classification model. These metrics provide a way to measure how well the model can correctly classify instances into different classes based on the input features. Evaluation of classification models is essential to build a reliable and effective model. Many of these metrics are based on the Confusion Matrix, which summarizes the actual and predicted classification outcomes, making it a useful tool to analyze the model's performance. (Grandini, Bagli, & Visani, 2020). 2.5.1. Confusion Matrix A confusion matrix is a technique used to evaluate the performance of a classification model on a dataset where the outcomes are already known. It offers a means to measure the accuracy of the model and is particularly useful when dealing with imbalanced categories. (Géron, 2019) A confusion matrix displays the actual classes of the data along one axis and the predicted classes along the other. Each cell of the matrix shows the count of instances that were classified as belonging to a particular class. The cells along the diagonal correspond to the correctly classified instances, while the cells off the diagonal correspond to the instances that were classified incorrectly. Actual values Positive (1) Negative (0) Predicted Values Positive (1) TP FP Negative (0) FN TP Tabela 1- Confusion Matrix In other words, is composed of four main components: true positives (TP), false positives (FP), true negatives (TN), and false negatives (FN). According to (Géron, 2019), True positives refer to the instances where the model correctly identified the positive class, while false positives are the instances where the model incorrectly identified a negative instance as positive. True negatives refer to the instances where the model correctly identified the negative class, and false negatives are the instances where the model incorrectly identified a positive instance as negative. 11 2.5.2. Accuracy Accuracy is a widely used metric for evaluating classification models that measures the number of correct predictions divided by the total number of predictions. It provides an overall idea of the model's performance by computing the proportion of true positives and true negatives in the predicted data. (Hossin & M.N, 2015) 𝐴𝑐𝑐𝑢𝑟𝑎𝑐𝑦= 𝑇𝑟𝑢𝑒 𝑃𝑜𝑠𝑖𝑡𝑖𝑣𝑒+𝑇𝑟𝑢𝑒 𝑁𝑒𝑔𝑎𝑡𝑖𝑣𝑒 𝑇𝑟𝑢𝑒 𝑃𝑜𝑠𝑖𝑡𝑖𝑣𝑒+ 𝐹𝑎𝑙𝑠𝑒 𝑃𝑜𝑠𝑖𝑡𝑖𝑣𝑒+ 𝑇𝑟𝑢𝑒 𝑁𝑒𝑔𝑎𝑡𝑖𝑣𝑒+ 𝐹𝑎𝑙𝑠𝑒 𝑁𝑒𝑔𝑎𝑡𝑖𝑣𝑒 While accuracy is a useful metric for balanced datasets, it can be misleading in the case of imbalanced datasets where the number of instances in each class is different. In such cases, a model that always predicts the majority class will have high accuracy, but will not necessarily perform well in predicting the minority class. 2.5.3. Precision Precision is a classification metric that quantifies the accuracy of positive predictions made by a model. It is defined by dividing the number of true positives by the sum of true positives and false positives. In other words, precision measures the proportion of true positive predictions out of all the positive predictions made by the model. (Géron, 2019). 𝑃𝑟𝑒𝑐𝑖𝑠𝑖𝑜𝑛= 𝑇𝑟𝑢𝑒 𝑃𝑜𝑠𝑖𝑡𝑖𝑣𝑒 𝑇𝑟𝑢𝑒 𝑃𝑜𝑠𝑖𝑡𝑖𝑣𝑒+ 𝐹𝑎𝑙𝑠𝑒 𝑃𝑜𝑠𝑖𝑡𝑖𝑣𝑒 A high precision means that the model is predicting correctly a high proportion of positive cases. Precision is commonly used to evaluate the performance of a model in situations where the cost of a false positive is high, i.e., when the model falsely classifies a negative instance as a positive class. In such cases, the focus is on minimizing the number of false positives, and the precision metric is used to measure the proportion of true positives among the predicted positives. 2.5.4. Recall Recall (otherwise known as sensitivity or true positive rate) is a measure of the classifier's capability to correctly identify positive occurrences. It is calculated by dividing the number of true positive predictions by the sum of true positives and false negatives, representing the proportion of actual positive instances that are correctly identified by the classifier. (Géron, 2019). This means that recall is a measure of how well the classifier is able to correctly identify instances of the positive class (i.e., true positives) among all instances that actually belong to the positive class (true positives + false negatives). 𝑅𝑒𝑐𝑎𝑙𝑙 = 𝑇𝑟𝑢𝑒 𝑃𝑜𝑠𝑖𝑡𝑖𝑣𝑒 𝑇𝑟𝑢𝑒 𝑃𝑜𝑠𝑖𝑡𝑖𝑣𝑒+ 𝐹𝑎𝑙𝑠𝑒 𝑁𝑒𝑔𝑎𝑡𝑖𝑣𝑒 In situations where the number of positive instances is significantly lower than the number of negative instances, imbalanced datasets for example, recall is often considered a more useful metric than accuracy. This is because recall measures the ability of the model to correctly identify important instances, even if they are rare, while accuracy only measures the overall number of correct predictions. (Fawcett, 2006). 12 2.5.5. F1 Score According to (Géron, 2019), The F1 score is a metric that takes into account both precision and recall to provide an overall evaluation of the performance of a classification model. 𝐹1=2 𝑝𝑟𝑒𝑐𝑖𝑠𝑖𝑜𝑛×𝑟𝑒𝑐𝑎𝑙𝑙 𝑝𝑟𝑒𝑐𝑖𝑠𝑖𝑜𝑛+𝑟𝑒𝑐𝑎𝑙𝑙 It is calculated as the harmonic mean of precision and recall, and is useful in situations where both metrics are important. This metric is particularly helpful in scenarios where there is an imbalance between the number of positive and negative instances or when the cost of false positives and false negatives is not the same. The F1 score ranges from 0 to 1, with 1 being the best possible score. A high F1 score indicates good performance in both precision and recall. 2.6. DEBT MANAGEMENT IN THE ENERGY SECTOR Debt management B2C in the energy sector refers to the strategies and practices that companies in the energy industry use to manage their debts and financial obligations towards their customers (business-to-consumer, or B2C). Debt management is a critical aspect of credit risk management for utilities and is essential for maintaining financial stability and minimising default risk (Esgalhado, Higginson, Jacques, Matecsa, & Selandari, 2019). The report highlights the importance of effective debt collection practices, regular communication with customers, and the use of advanced technologies to automate and streamline debt management processes. One of the several goals of customer debt management in the energy sector is to provide education and resources to help customers better understand their energy usage and costs. This can include providing information on energy efficiency and conservation on their invoices, as well as assistance with identifying and accessing financial assistance programs. Customer debt management in the energy sector requires also working with customers to develop payment plans or other solutions to manage and reduce their debt. This means negotiating extended payment plans, connecting customers with financial assistance programs, and even providing temporary energy assistance to help clients keep their lights on during difficult financial times. Energy companies may also offer energy efficiency programs, on-bill financing and other solutions to help customers reduce their energy usage and costs. The paper from McKinsey also notes that utilities can benefit from using digital technologies and automation to enhance their debt management practices, including credit scoring, collections, and restructuring. This approach can help reduce operating costs and increase the amount of debt collected. Furthermore, digital technologies can provide significant improvements in customer experience throughout the debt collection process. Some utilities have developed a comprehensive digital platform for delinquent customers, covering debt overview, payment support, renegotiation, and customer support. (Esgalhado, Higginson, Jacques, Matecsa, & Selandari, 2019) Overall, debt management in the energy sector is a complex and dynamic field that requires a comprehensive understanding of financial risk and consumer behavior. Companies must continuously 13 innovate and adapt their debt management strategies to ensure financial stability and minimize default risk. 14 3. METHODOLOGY 3.1. BUSINESS UNDERSTANDING The first step needed is to gather all the important information about the client data available on the EDP database. The way to achieve that success is by gaining an in-depth understanding of the business and its operations. For that, CRISP-DM was the methodology used. It is clear that the team has a few main obstacles to overcome in order to improve the effectiveness of debt recovery: get an insight into who is most likely to become in debt. And why? And after knowing that, how can we improve that? Objective: build a machine learning classification model that identifies patterns that can help predict which customers are most likely to default on their loans. Scope: - Identify the main variables that correlate with a customer being a defaulter of payments - Test different models and their parameters to choose the one with the best accuracy - Learn and assess patterns for each class - Apply the model and help identify and mitigate potential financial risks 3.2. DATA UNDERSTANDING 3.2.1. Data sources It was collect all the important information about the client data available on the EDP database, which means all the variables corresponding to the information of the contract(s) and consumption of the clients. Unfornetlly, as EDP can not have access to information such as purchasing power, annual income or other information that leads us the assume the probability of a person becoming in debt, it was collected as much information available as possible including their demographic information, consumption patterns, billing information, and payment history. The collection of the data was based on SAS tables connected to the database servers of the company and performed on SAS Enterprise Guide. The dataset is composed of all active clients of the company, meaning, the ones that had at least one active contract on electricity or gas. That makes a total of 3M people. The features used were: Column name Meaning NOME_PRIMEIRO Name of the client COD_CAE Type of consumption: Domestic or other COD_CATEGORIA_CLIENTE Customer category: Person or organization COD_TIPO_CLIENTE Client type: Domestic or non-domestic COD_CLASSE_CONTA COD_VALOR_PRESENTE Account Class: Small business or residential Level of promotional campaigns gifts FLG_EDP_ONLINE if it uses the App or not 21 Column Meaning 0-14 number of people in the range of age from 0 to 14 years old 15-24 number of people in the range of age from 15 to 24 years old 25-64 number of people in the range of age from 25 to 64 years old 65 e mais number of people in the range of age 65+ Homens number of men Mulheres number of women Poder de compra per capita Per capita purchasing power Tabela 5- New Demographic Features and meaning 3.3.3. Missing values The best approach to dealing with missing values depends on the specific dataset, the amount of missing data, and the overall goals of the analysis. A small number of missing values were identified, with a maximum of 3% of the total and only on categorical features. To address this issue, the chosen method was to fill these missing values with the mode, which means filling with the most frequent value in the respective feature column. This method was chosen because it is a straightforward way to handle missing values, especially for small amounts of missing data. 3.3.4. Outlier detection Identifying and removing outliers is a crucial step in data preprocessing that should be performed prior to applying any statistical or machine learning techniques to the data. Outliers can have a major impact on the outcome of analyses. Therefore, it is important to handle outliers before proceeding with data analysis to ensure accurate and reliable results. (Enderlein, 1987). After a combination of visualization through box plots, knowledge of the business and the Interquartile Range (IQR), the difference between the 75th and 25th percentile of the data, meaning the observations that are less than Q1 - 1.5 * IQR or greater than Q3 + 1.5 * IQR are considered outliers, 2.63% of the data were considered outliers and eliminated. 3.3.5. Categorical features To represent categorical variables, such as: COD_CAE, COD_CATEGORIA_CLIENTE, COD_TIPO_CLIENTE, COD_CLASSE_CONTA, COD_VALOR_PRESENTE, FLG_EDP_ONLINE, MEAN_of_FLG_TARIFA_SOCIAL, Flg_Tel, Flg_Email, Distrito, MEAN_of_FLG_FATURA_ELETRONICA, MEAN_of_FLG_DEB_DIRETO, Tipo Contratos, Multibanco, PONTOS DÍVIDA, gen, it was used the common technique of dummy variables. This will help improve the performance of the model, as they capture the relationship between the original categorical variable and the target variable. 3.3.6. Feature scaling Feature scaling is an important preprocessing step in many machine learning algorithms. It refers to the process of transforming the variables or features in the dataset to a common scale. This helps to ensure that each variable or feature contributes equally to the model, avoiding bias and improving the performance of the algorithm. As noted by (Géron, 2019), machine learning algorithms tend to work more effectively or reach optimal results more quickly when the features have been standardized to be on similar scales. Without feature scaling, variables or features with larger values can dominate the distances, leading to suboptimal performance. Therefore, the dataset was normalized using the 22 method of min-max scaling. Min-max scaling, also known as normalization, scales the values to a range between 0 and 1. 3.3.7. Target distribution Analysing the target distribution, it's clear it's an imbalanced target variable, which could impact the accuracy of the predictions. Having an unbalanced dataset can harm the accuracy of the predictive model in several ways. This is because when the target classes are imbalanced, the model will learn to predict the majority class more often, leading to a high accuracy score but with a low precision and recall score. This means that the model will not perform well in identifying the minority class, leading to biased results. Additionally, an unbalanced dataset can lead to overfitting on the majority class, making it difficult for the model to generalize to unseen data. Therefore after considering different techniques to handle this issue, it was decided to stratify the data when splitting it into a training and testing set, that involves distributing the target variable evenly among the two sets, so that the proportion of target categories in both sets is similar to the proportion of target categories in the entire dataset. This was done to ensure that the training set and testing set are representatives of the entire dataset and that there is a balance of the target categories in both sets. Another technique considered was undersampling. It is a technique that involves reducing the size of the majority class to balance the target variable. Although it is an effective way to handle imbalanced datasets, it can also lead to a loss of important information and may result in a biased model. This was the case since it was found that undersampling resulted in a significant reduction in the size of the dataset, which in turn impacted the performance of the predictive model. Therefore, it was decided not to use undersampling and instead use stratified sampling, as discussed earlier, to ensure a balanced distribution of target variables in the training and testing sets. This approach helped to prevent the over-representation or under-representation of any particular target category, which could have resulted in biased models or inaccurate model performance evaluation. 3.3.8. Dealing with correlated features Correlation analysis is a valuable technique in the process of selecting relevant features for a target variable, as it can help identify predictors that may have a strong relationship with the target. (Kelleher, Mac, Aoife, & Arcy, 2015). In the context of data analysis, correlation analysis helps identify features that are highly correlated between themselves and the target variable. This information can then be used to make informed decisions about which features to include or exclude from a predictive model. The correlation was calculated using various methods, including Pearson's correlation coefficient and Spearman's rank correlation coefficient. These methods measure the linear relationship between two variables, with values ranging from -1 (strong negative correlation) to 1 (strong positive correlation). Features that are highly correlated with each other (multicollinearity) or with the target (high correlation) - correlation coefficient of more than 0.8 with each other and more than 0.7 with the targetwere removed during correlation analysis to avoid unstable and irrelevant solutions in the model since high correlations between the features and target can result in overfitting or redundant information. 23 3.3.9. Feature Selection Preparing data for training models often involves feature selection, which is crucial for improving model performance and reducing computational time, especially when dealing with large datasets. By reducing the dimensionality of the data, feature selection helps to identify the relevant predictors and avoid the problem of having too many potential predictors, which can make the modeling process more difficult and time-consuming (Guyon & Elisseeff, 2003). Therefore, using predictive models for feature selection can help in identifying the most important features that have a strong impact on the target variable. This leads to a more efficient and effective model, as well as increased interpretability. The algorithms experimented to select the features for the model were: • Embedded methods such as Decision trees, ridge classifier and lasso classifier. • Filter-Based Methods such as Correlation • Wrapper methods such as RFE (recursive feature elimination), were used for the features selected by the methods above. 3.4. MODEL SELECTION AND EVALUATION After the data is fully prepared and explored, it is ready for model selection. The first step made was to split the data into train and test, with the train representing 70% and the remaining 30% the test part. To ensure all classes are being represented while the data is being trained by the model, it was applied 10-fold cross validation as well. Since we are dealing with a multiclassification problem, a high number of features, and the presence of both categorical and numerical features, the following models were considered for training: Random Forest Classifier, Decision Trees Classifier, Neural Networks and XGBoost. Given this research is facing a very large size dataset, which contains millions of observations and numerous features, I need a model that could handle such large and complex data while still producing accurate predictions. The main obstacle here in the selection and implementation of the model is computational resources. Considering that, and the balance between the weaknesses and strengths of the model, I chose to use XGBoost primarily because of its efficiency and scalability with computational resources. Strengths: Weaknesses: High predictive accuracy Computationally intensive, especially when dealing with large datasets or complex models. Flexibility: can be used for a wide range of tasks, including feature selection, missing value imputation, and anomaly detection. Sensitivity to hyperparameters, and tuning these hyperparameters can be time-consuming and computationally expensive. Scalability: highly scalable and can handle large datasets with millions of features and millions of samples. Interpretability: XGBoost models can be difficult to interpret Parallel processing, which can speed up training times. Potential for overfitting Regularization, which can help prevent overfitting and improve generalization performance. Tabela 6- Strengths and Weaknesses of XGBoost 24 When dealing with imbalanced datasets, accuracy may not be a reliable metric as it only measures the proportion of correct predictions. Instead, it is essential to use an evaluation metric that considers both precision and recall to assess the model's overall performance in a balanced manner. This approach is necessary because traditional metrics may not account for the false positive and false negative rates, which can significantly impact the effectiveness of the model. The F1 score is a popular metric used in classification tasks to measure the balance between precision and recall. It is particularly useful when the dataset is imbalanced, meaning that one class has a much larger number of samples than the others, which is the case. Precision and recall are two important metrics in classification. Precision measures how many of the predicted positive samples are actually positive, while recall measures how many of the actual positive samples are correctly predicted. In other words, precision focuses on the accuracy of positive predictions, while recall focuses on the ability to find all positive samples. The F1 score is the harmonic mean of precision and recall. It is calculated as follows: 𝐹1=2 𝑝𝑟𝑒𝑐𝑖𝑠𝑖𝑜𝑛×𝑟𝑒𝑐𝑎𝑙𝑙 𝑝𝑟𝑒𝑐𝑖𝑠𝑖𝑜𝑛+𝑟𝑒𝑐𝑎𝑙𝑙 The F1 score ranges from 0 to 1, with 1 being the best possible score. A high F1 score indicates good performance in both precision and recall. By choosing the F1 score, I am able to evaluate the tradeoff between precision and recall and get a single metric that summarizes the overall performance of my model. This is particularly important when the cost of false positives and false negatives is not equal, as it allows me to optimize the model for the particular application at hand. 25 4. RESULTS AND DISCUSSION This chapter presents the results of applying the model and discusses the implications of the findings. It starts by providing an overview of the selected model followed by the hyperparameter tuning process. Then, it reports the final performance of the model with the selected evaluation metrics and compared it to baseline models. Finally, the limitations are discussed and the potential future directions of this study are mentioned. 4.1. EVALUATING FIRST RESULTS The model was first applied with the default parameters, using different sets of variables constructed during feature selection. It generated the following results: F1 Score Features Train Test Decision Trees 0.7836 0.7800 Correlations 0.7804 0.7772 Ridge Regression 0.7816 0.7788 Lasso Regression 0.7611 0.7590 RFE 0.7873 0.7839 Tabela 7- F1 Score results The results show that different feature selection methods can have a significant impact on the performance of the XGBoost model. In this case, the RFE (Recursive Feature Elimination) method resulted in the highest F1 scores on both the training and testing datasets. This indicates that the selected features by this method were the most relevant and informative for the classification task. These features were the following: Contratos Ativos, Contrato ativo mais Antigo, MEAN_of_QTD_CONSUMO_ANUAL_ESP, Contratos Encerrados, Antiguidade Cliente, MEAN_of_Pack01, Variedade Serviços, Tempo até pagamento, avg_score_clienteant, COD_CAE_other, COD_CATEGORIA_CLIENTE_2, COD_VALOR_PRESENTE_A, COD_VALOR_PRESENTE_B, COD_VALOR_PRESENTE_M, COD_VALOR_PRESENTE_MA, COD_VALOR_PRESENTE_MB, MEAN_of_FLG_TARIFA_SOCIAL_1, Flg_Tel_1, Flg_Email_1, Distrito_BEJA, Distrito_COIMBRA, Distrito_SANTAREM, Distrito_VISEU, MEAN_of_FLG_DEB_DIRETO_1, Tipo Contratos_D, Multibanco_1. On the other hand, the Decision Trees and Correlations methods produced F1 scores that were lower than RFE, but still relatively high. This suggests that the features selected by these methods also have some predictive power, but may not be as informative as those selected by RFE. The Ridge and Lasso Regression methods produced the lowest F1 scores, indicating that the selected features may not be as relevant or informative for the classification task as those selected by the other methods. 4.2. HYPERPARAMETER TUNING The choice of hyperparameters can significantly affect the performance of a model, and hyperparameter tuning is the process of finding the best combination of hyperparameters that results in the best model performance and possibly less overfitting. 26 Finding the best hyperparameters is crucial for creating an accurate machine learning algorithm. However, there is no universal rule for selecting hyperparameters, as different values can have a significant impact on the model's predictive ability. Using cross-validation, we can estimate the test error for different hyperparameter values, and select the best one. Yet, with a large number of possible values for each hyperparameter, finding the best set of hyperparameters can be a daunting task. To address this, techniques like grid search, randomized search, and Bayesian optimization can be used to navigate the vast hyperparameter space and find the best combination of values. (James, Witten, Hastie, & Tibshirani, 2021) Since the most well-performed set of features were the RFE, it is the one that is going to be used for hyperparameter tuning. The first step made to adjust parameters was to analyse the learning rate and the number of estimators of the model and how affects its performance. To prevent overfitting, it is used the learning rate, also called shrinkage, which reduces the weights of each feature during boosting iterations proportionally to their current weights. This helps achieve better generalization performance, but it may take longer to converge. A smaller learning rate is usually paired with a higher number of trees to compensate for the slower convergence. (XGBoost Documentation — xgboost 1.7.4 documentation) This means that a smaller learning rate may result in longer training times since the model takes smaller steps to optimize the objective function. On the other hand, a larger learning rate may result in faster training times, but the model may converge to a suboptimal solution and may require additional steps to improve the performance, and clearly, that is shown in the figure. Therefore, the choice of the learning rate should be balanced between the success rate and performance time based on the available computing resources, meaning the main focus of looking at the figure is to find the optimal trade-off. Figura 9 - F1 Score vs Learning rate 27 The number of estimators is a hyperparameter in the XGBoost algorithm that refers to the number of decision trees to be used in the model. We can see in the figure that increasing the number of estimators can improve the performance of the model, but can also significantly increase the training time and memory requirements. In general, increasing the number of estimators beyond a certain point may lead to diminishing returns in performance improvement, while significantly increasing the time and computational resources required to train the model. While choosing the method to use to explore the hyperparameters, it was considered grid search and randomized search. Given the large dataset, the big set of different parameters to explore, and the limited computational resources, it may not be feasible to use grid search, which exhaustively searches over all possible combinations of hyperparameters, as it may take a very long time to complete. Therefore, alternative methods such as randomized search, which randomly samples a subset of hyperparameters, may be more practical and efficient in this scenario. According to (Bergstra, Ca, & Ca, 2012), they found that random search can achieve the same level of performance for hyperparameter tuning as grid search, but with fewer attempts and less time spent on computation. This is because the search space for hyperparameters is complex and includes both continuous and discrete parameters, making the grid too coarse to capture all the details. The study also found that although random search may produce performance estimates with high variance, increasing the number of attempts can compensate for this without significantly increasing computational costs compared to grid search. Therefore, it was decided to use randomized search instead of grid search to tune the hyperparameters of the model. After running 100 iterations for the search, it was found a set of parameters that were able to reduce the overfitting of the model, even though the score was not improved. That leaves us with the final result of 0.7850 on the training set and 0.7835 on the test set. Figura 10 - F1 Score vs Number of estimators 28 4.3. DISCUSS FINAL RESULTS This chapter is dedicated to interpreting the results and the predictions of the model. In the case of a classification model, it is important to evaluate the performance of the model in a meaningful way, taking into account the specific requirements of the task at hand. To do this, I have generated a classification report that presents precision, recall, f1-score, and support for each class in the dataset. This provides a detailed overview of the model's performance in each class, allowing us to evaluate its strengths and weaknesses. By considering these metrics, we can gain insights into how well the model is able to identify different types of instances and we can make informed decisions about how to improve its performance. Precision Recall F1-Score Support 0 0,84 0,94 0,89 651070 [1-3] 0,65 0,46 0,54 218689 [4-6] 0,64 0,32 0,43 34352 [7-9] 0,57 0,09 0,15 2828 accuracy 0,8 906939 macro avg 0,47 0,45 0,5 906939 weighted avg 0,78 0,8 0,78 906939 Tabela 8 - Classification report Looking at the results, we can see that the model achieved high precision (0.84) and recall (0.94) for class 0, showing that it performed well in identifying instances of this class. However, for classes 1-3 and 4-6, the precision and recall are lower, indicating that the model did not perform as well to correctly identify these classes. Class 7-9 has the lowest precision, recall, and F1-score, indicating that the model struggles the most in identifying instances of this class. The macro-averaged F1-score is 0.50, indicating that the performance of the model is moderate, however, the macro-average F1 score treats all classes equally and calculates the F1 score for each class separately, and then takes the unweighted average of those scores. This means that the contribution of each class to the final score is the same, regardless of the number of samples in that class. Therefore, it is more appropriate to use metrics that consider the class distribution, such as the weighted average or micro-average F1 score. The weighted average F1 score calculates the average F1 score, weighted by the number of samples in each class, giving more weight to the performance of the classes with more samples. As seen before we can observe the weighted average F1-score is 0.78, indicating the overall performance of the model is good but suggesting that the model performed better on the larger Figura 11 - Confusion Matrix of Test set 29 classes and struggled with the smaller ones. To further analyse the strengths and weaknesses of the model it was constructed a confusion matrix. After constructing and analyzing the confusion matrix, the main observations that were drawn are: As seen before it is clear that class 0 has a bigger sample and it is correct to assume that the model performed better in this class by looking at the classification report. We can further confirm this by looking at the confusion matrix as well since it has the highest number of true positives and the lowest number of false positives and false negatives. We can also see that the class most mistaken by class 0 is class 1-3. The same happens for class 1-3 in the sense that is most mistaken by class 0. Class 1-3 has a large number of false positives, which means that many samples are incorrectly predicted to belong to class 1-3 when they actually belong to another class. On the other hand, class 4-6 has a large number of false negatives, which means that many samples that belong to class 4-6 are incorrectly predicted to belong to another class. In class 7-9 we can also conclude that is often mistaken by class 4-6. Also from class 7-9, we can see that has the lowest number of true positives, indicating that it is the most difficult class to predict accurately. Overall, we can observe from the confusion matrix that it is common for a class to be misclassified as its neighbouring class. This pattern can be expected, as there may not be a significant difference in the features between these neighbouring classes. Therefore, a classifier may have a higher chance of making false positive or false negative errors when distinguishing between these classes. 30 5. CONCLUSION This report was based on the main project developed during the internship and it explored the use of machine learning algorithms for predicting the risk of clients in terms of debt score at EDP Comercial. The project addresses the urgent need for effective debt management in a competitive and growing market, where data-driven techniques can significantly improve debt recovery. To achieve that demand it was created a predictive model that is able to identify patterns in clients based on their scorecard, which measures the quality of a client based on their infringement history. The data set was constituted of client contracts information, services required, payment history and information on the places of consumption. Before applying the model, the data preparation and feature engineering process were crucial to the performance of the model, including adding features to help the model succeed. After training the model using XGBoost classifier, was conducted hyperparameter tuning to help reduce the overfitting of the model and the model ended up achieving an overall performance of 0.78. It was concluded that one of its main weaknesses is correctly identifying the lower classes, but it has good performance in predicting the bigger classes. Although more work is needed to optimize the model's performance and expand the sample size of the data set and add more information on the client's financial profile, this project shows promising results and provides a foundation for future work on debt recovery management. By being proposed this project the majority of this internship gave me exposure to the practical application of data-driven techniques, specifically the theoretical and practical knowledge acquired during the Master's program. This was achieved by applying data analysis, process mining, and machine learning to customer data and therefore it was possible to develop a predictive model that can identify at-risk accounts before they fall behind on payments, allowing the company to respond preventively and proactively. The collection of the data was made using SAS Guide but all the rest was continued on Jupyter Notebook, the main system used during the master in several courses. During the internship, I also had the opportunity to gain a wealth of new knowledge and insights, particularly in the areas of business operations and management of a large portfolio of clients in the energy industry. Through this experience, I was able to explore new algorithms and software tools, which helped me to better understand and apply the concepts learned during my Master's program. Overall, the internship provided a valuable and relevant experience that enhanced my understanding of the energy industry and solidified my knowledge of the subjects already studied in the master’s program. 37 Figura 14- Pearson's correlation matrix 38 Figura 15 - Spearman's rank correlation matrix 39 Figura 16 - Feature Selection Decision Trees: Gini and Entropy 40 Figura 17- Feature Selection using Ridge Classifier 41 Figura 18- Feature Selection using Lasso Classifier 1