scieee AI-readable full text Open interactive document viewer

Human-aware application of data science techniques

Coma Puig, Bernat

Abstract

In recent years there has been an increase in the use of artificial intelligence and other data-based techniques to automate decision-making in companies, and discover new knowledge in research. In many cases, all this has been performed using very complex algorithms (so-called black-box algorithms), which are capable of detecting very complex patterns, but unfortunately remain nearly uninterpretable. Recently, many researchers and regulatory institutions have begun to raise awareness of their use. On the one hand, the subjects who depend on these decisions are increasingly questioning their use, as they may be victims of biases or erroneous predictions. On the other hand, companies and institutions that use these algorithms want to understand what their algorithm does, extract new knowledge, and prevent errors and improve their predictions in general. All this has meant that researchers have started to focus on the interpretability of their algorithms (for example, through explainable algorithms), and regulatory institutions have started to regulate the use of the data to ensure ethical aspects such as accountability or fairness. This thesis brings together three data science projects in which black-box predictive machine learning has been implemented to make predictions: - The development of an NTL detection system for an international utility company from Spain (Naturgy). We combine a black-box algorithm and an explanatory algorithm to guarantee our system's accuracy, transparency, and robustness. Moreover, we focus our efforts on empowering the stakeholder to play an active role in the model training process. - A collaboration with the University of Padova to provide explainability to a Deep Learning-based KPI system currently implemented by the MyInvenio company. - A collaboration between the author of the thesis and the Universitat de Barcelona to implement an AI solution (a black-box algorithm combined with an explanatory algorithm) to a social science problem. The unique characteristics of each project allow us to offer in this thesis a comprehensive analysis of the challenges and problems that exist in order to achieve a fair, transparent, unbiased and generalizable use of data in a data science project. With the feedback arising from the research carried out to provide satisfactory solutions to these three projects, we aim to: - Understand the reasons why a prediction model can be regarded as unfair or untruthful, making the model not generalisable, and the consequences from a technical point of view in terms of low accuracy of the model, but also how this can affect us as a society. - Determine and correct (or at least mitigate) the situations that cause the problems in terms of robustness and fairness of our data. - Assess the difference between the interpretable algorithms and black-box algorithms. Also, evaluate how well the explanatory algorithms can explain the predictions made by the predictive algorithms. - Highlight what the stakeholder's role in guaranteeing a robust model is and how to convert a data-driven approach to solve a predictive problem into a data-informed approach, where the data patterns and the human knowledge are combined to maximize profit.

Full text

HUMAN-AWARE APPLICATION OF DATA SCIENCE TECHNIQUES Bernat Coma-Puig Supervisor: Josep Carmona Barcelona, January 2022 Acknowledgment First of all, I would like to give special thanks to my supervisor Josep Carmona. I will always be grateful to him for his guidance and accompaniment during my PhD. I am aware that I have been fortunate to have him as a supervisor. I would also like to express my gratitude to Ricard Gavald`a, who shared his expertise in the field of machine learning and data mining with me. I also thank all the researchers with whom I have worked: Massimiliano de Leoni, Riccardo Galanti, Nicol`o Navarin, Luz Mu˜noz, Noem´ı Oru´e, Albert Calvo and Alexandra Yamaui. I would also like to express my gratitude to Naturgy, especially to Santiago Alcoverro, Manuel Cirugeda and Enric Argelich. And finally, I would like to mention Ernesto Diaz-Avil´es, who introduced me to the world of data research. Without that experience I would probably not have ended up doing my PhD. En primer lloc, m’agradaria donar un agra¨ıment especial al meu supervisor en Josep Carmona. Sempre li estar´e agra¨ıt per la seva orientaci´o i acompanyament durant el meu doctorat. S´oc conscient que he tingut la sort de tenir-lo com a supervisor. Tamb´e vull expressar el meu agra¨ıment a en Ricard Gavald`a, que ha compartit amb mi el seu alt coneixement en l’`ambit de l’aprenentatge autom`atic i la mineria de dades. Tamb´e agraeixo a tots els investigadors amb qui he treballat: en Massimiliano de Leoni, en Riccardo Galanti, en Nicol`o Navarin, la Luz Mu˜noz, la Noem´ı Oru´e, la Marta Arias, l’Albert Calvo i l’Alexandra Yamaui. Tamb´e voldria expressar el meu agra¨ıment a Naturgy, i especialment a en Santiago Alcoverro, en Manuel Cirugeda i l’Enrich Argelich. I finalment, m’agradaria esmentar l’Ernesto Diaz-Avil´es, que em va introduir en el m´on de la recerca de dades. Sense aquella experi`encia probablement no hauria acabat fent el meu doctorat. Abstract In recent years there has been an increase in the use of artificial intelligence and other data-based techniques to automate decision-making in companies, and discover new knowledge in research. In many cases, all this has been performed using very complex algorithms (so-called blackbox algorithms), which are capable of detecting very complex patterns, but unfortunately remain nearly uninterpretable. Recently, many researchers and regulatory institutions have begun to raise awareness of their use. On the one hand, the subjects who depend on these decisions are increasingly questioning their use, as they may be victims of biases or erroneous predictions. On the other hand, companies and institutions that use these algorithms want to understand what their algorithm does, extract new knowledge, and prevent errors and improve their predictions in general. All this has meant that researchers have started to focus on the interpretability of their algorithms (for example, through explainable algorithms), and regulatory institutions have started to regulate the use of the data to ensure ethical aspects such as accountability or fairness. This thesis brings together three data science projects in which blackbox predictive machine learning has been implemented to make predictions. In each case, we contextualize the problem and explain the use of the explanatory algorithms to guarantee the robustness and quality of the model built. Non-Technical Losses Detection System Our first case study explains the development of an NTL detection system for the international utility company from Spain Naturgy. Despite the good results achieved detecting NTL cases (especially in certain cases in which previous approaches had very poor accuracy), we suffered many of the problems regarding the quality of the data. These problems hindered our system from achieving consistent and robust results. Once we made clear the existence of these data problems, we shifted our effort from trying to make a more complex method (to detect more complex patterns) to achieving a more interpretable method, allowing both the scientists and the stakeholders to understand the patterns learnt (and therefore the detection of biases and undesired patterns). These data-related problems are partially explained in the literature but are not tackled in any other example of the literature. Explainable Predictive Process Monitoring This thesis also explains our collaboration with the University of Padova to provide explainability to a KPI system currently implemented by the MyInvenio company. In this case, we show that using explanatory black-box algorithms can provide robust explanations in line with the company’s analysts, with less human effort. The predictive process management and the explanatory algorithms are breaking new ground, and the resulting work is a pioneer in bringing them together in the literature of business process management. Explainable Black-Box Algorithms in Social Science The classical dichotomy of interpretable algorithms vs black-box algorithms has not existed in Social Science literature since it is mandatory to understand the relation between variables. In this thesis, we analyze, using as a reference a collaboration between the author of the thesis and the Universitat de Barcelona, if the combination of black-box algorithms with explanatory methods can provide better results (e.g., a deeper understanding of the interaction between features, or more flexibility) in Social Science projects than the classical approach of using the interpretable Regression or Decision Tree models. The unique characteristics of each project allow us to offer in this thesis a comprehensive analysis of the challenges and problems that exist in order to achieve a fair, transparent, unbiased and generalizable use of data in a data science project. With the feedback arising from the research carried out to provide satisfactory solutions to these three projects, we aim to: •Understand the reasons why a prediction model can be regarded as unfair or untruthful, making the model not generalizable, and the consequences from a technical point of view in terms of low accuracy of the model, but also how this can affect us as a society. •Determine and correct (or at least mitigate) the situations that cause the problems in terms of robustness and fairness of our data. •Assess the difference between the interpretable algorithms and blackbox algorithms. Also, evaluate how well the explanatory algorithms can explain the predictions made by the predictive algorithms. •Highlight what the stakeholder’s role in guaranteeing a robust model is and how to convert a data-driven approach to solve a predictive problem into a data-informed approach, where the data patterns and the human knowledge are combined to maximize profit. Resum En els darrers anys s’ha incrementat l’´us de la intel·lig`encia artificial i altres t`ecniques basades en dades per automatitzar la presa de decisions a les empreses, aix´ı com per descobrir nous coneixements en recerca. En molts casos, tot aix`o s’ha realitzat mitjan¸cant algorismes molt complexos (els anomenats algorismes de caixa negra), que s´on capa¸cos de detectar patrons molt complexos, per`o malauradament segueixen sent gaireb´e ininterpretables. Recentment, molts investigadors i institucions reguladores han comen¸cat a conscienciar sobre el seu ´us. D’una banda, els subjectes que depenen d’aquestes decisions q¨uestionen cada cop m´es el seu ´us, ja que poden ser v´ıctimes de biaixos o prediccions err`onies. D’altra banda, les empreses i institucions que utilitzen aquests algorismes volen entendre qu`e fa el seu algorisme, extreure nous coneixements, aix´ı com prevenir errors i millorar les seves prediccions en general. Tot aix`o ha fet que els investigadors hagin comen¸cat a centrar-se en la interpretabilitat dels seus algorismes (per exemple mitjan¸cant algorismes d’explicabilitat), i les institucions reguladores hagin comen¸cat a regular l’´us de les dades per garantir aspectes `etics com la rendici´o de comptes o l’equitat. Aquesta tesi reuneix tres projectes de ci`encia de dades en els quals s’ha implementat l’aprenentatge autom`atic predictiu de caixa negra per fer prediccions. En cada cas, contextualitzem el problema, i expliquem l’´us dels algorismes explicatius per garantir la robustesa i la qualitat del model constru¨ıt. Sistema de detecci´o de p`erdues no t`ecniques El nostre primer cas pr`actic explica el desenvolupament d’un sistema de detecci´o de NTL (p`erdues no t`ecniques) per a la companyia internacional del sector de l’energia d’Espanya Naturgy. Malgrat els bons resultats obtinguts en la detecci´o de casos de NTL (sobretot en alguns casos en qu`e els enfocaments anteriors tenien una precisi´o molt escassa), vam patir molts dels problemes de qualitat de les dades. Aquests problemes van impedir que el nostre sistema aconsegu´ıs resultats consistents i s`olids. Un cop vam ser clarament conscients de l’exist`encia d’aquests problemes de dades, vam canviar el nostre esfor¸c d’intentar fer un m`etode m´es complex (amb l’objectiu de detectar patrons m´es complexos) a aconseguir un m`etode m´es interpretable, que permet´es tant als cient´ıfics com als stakeholders (els treballadors de l’empresa) entendre els patrons apresos (i, per tant, la detecci´o de biaixos i patrons no desitjats). Aquests problemes relacionats amb les dades s’expliquen parcialment a la literatura, per`o no s’aborden en cap altre exemple de la literatura. Monitoritzaci´o de processos predictius explicables Aquesta tesi tamb´e explica la nostra col·laboraci´o amb la Universitat de P`adua per donar explicabilitat a un sistema KPI (Key Performance Indicator) implementat actualment per l’empresa MyInvenio. En aquest cas mostrem que l’´us d’algoritmes explicatius de caixa negra pot proporcionar explicacions s`olides en l´ınia amb els analistes de l’empresa, amb menys esfor¸c hum`a. Tant la gesti´o de processos predictius com els algorismes explicatius estan obrint nous camins, i el treball resultant ´es pioner a reunir-los en la literatura de gesti´o de processos empresarials. Algorismes de caixa negra explicables en ci`encies socials La dicotomia cl`assica d’algorismes interpretables vs. algorisme de caixa negra no ha existit a la literatura de ci`encies socials, ja que ´es obligatori entendre la relaci´o entre variables. En aquesta tesi analitzem, utilitzant com a refer`encia una col·laboraci´o entre l’autor de la tesi i la Universitat de Barcelona, si la combinaci´o d’algorismes de caixa negra amb m`etodes explicatius pot donar millors resultats (p. ex., una comprensi´o m´es profunda de la interacci´o entre variables, o m´es flexibilitat) en projectes de ci`encies socials que l’enfocament cl`assic d’utilitzar els models interpretables de regressi´o o arbre de decisions. Les caracter´ıstiques singulars de cada projecte ens permeten oferir en aquesta tesi una an`alisi exhaustiva dels reptes i problemes que existeixen per tal d’aconseguir un ´us just, transparent, imparcial i generalitzable de les dades en un projecte de ci`encia de dades. Amb el feedback derivat de la recerca realitzada per donar solucions satisfact`ories a aquests tres projectes, pretenem: •Comprendre les raons per les quals un model de predicci´o es pot considerar injust o fals, fent que el model no sigui generalitzable, i les conseq¨u`encies des d’un punt de vista t`ecnic en termes de poca precisi´o del model, per`o tamb´e com aix`o ens pot afectar com a societat. •Determinar i corregir (o almenys mitigar) les situacions que causen els problemes en termes de robustesa i equitat de les nostres dades. •Avaluar la difer`encia entre els algorismes interpretables i els algorismes de caixa negra. Tamb´e, avaluar fins a quin punt els algorismes explicatius poden explicar les prediccions fetes pels algorismes predictius. •Destacar quin ´es el paper de les parts interessades (stakeholders) per garantir un model robust i com convertir una aproximaci´o basada nom´es en les dades per resoldre un problema predictiu en una aproximaci´o que faci ´us de les dades per`o que tamb´e es complementi amb altres coneixements, on els patrons de dades i el coneixement hum`a es combinen per maximitzar els beneficis. Contents I Introduction 1 1 Trustworthiness in Data Science and Artificial Intelligence 3 1.1 Towards a Non-Abusive and Human-Aware Use of Data . . 3 1.1.1 Democratisation of Data Science ........... 3 1.1.2 Automated Data Science: Can We Trust it? ..... 5 1.2 Application Areas and Published Work ............ 8 1.2.1 Case of Study ...................... 8 1.2.2 Our Published Work .................. 9 2 Preliminaries 12 2.1 Supervised Predictive Models ................. 12 2.1.1 Data Extraction and Pre-Processing ......... 12 2.1.2 Model Selection, Parameter Tuning and Loss Function 14 2.1.3 Deployment of the System and Post-Analysis . . . . 19 2.1.4 Challenges in Supervised Predictive Models ..... 20 2.2 Model Transparency and Explainability ........... 22 2.2.1 Interpretable Algorithms ................ 23 2.2.2 Black-Box Algorithms ................. 25 2.3 Explainable AI ......................... 28 2.3.1 XAI goals ........................ 29 2.3.2 XAI Approaches .................... 30 2.4 Discussion ............................ 33 II Human-Aware NTL Detection 34 3 Preliminaries in Non-Technical Losses Detection 36 3.1 Context of the Application Area ............... 36 3.2 Related Work .......................... 37 3.3 NTL Detection: Baseline Approach .............. 38 3.3.1 Data Processing .................... 38 3.3.2 Creating a Classification Problem ........... 41 3.3.3 The Process ....................... 46 3.3.4 Learning from Feedback ................ 47 9 Trustworthiness in Data Science and Artificial Intelligence 5 approaches (e.g. [77]) advocate for the use of machine learning techniques to provide a much more complex and accurate prediction. Financial institutions also use data to implement fraud detection algorithms that guarantee the protection of their customers against malicious credit card purchases use. As doing this analysis humanly is not feasible, we already have examples of the use of neural networks in the 1990s (e.g. [60]). Another implementation of smart techniques is algorithmic trading, i.e., algorithms that analyze real-time financial instruments (e.g. stocks or commodity markets) to forecast market opportunities. The advantage over a human trader is both the capacity of analysing large amounts of data with no emotional factors and also the speed in making trading decisions [98]. Justice Unlike the previous examples the application of data science techniques in justice is at a very early stage. The most groundbreaking proposal is the possibility of replacing a court judge using artificial intelligence, an idea that is not new [38]. Although it might be seen as purely science fiction, it is feasible that predictive algorithms could be helpful to complement the point of view of the judge, for instance, to analyze the possibility of re-offending and, therefore, adapt the prison sentence to this evidence-based analysis. From a more administrative point of view, algorithms can help to reduce judges’ workloads, especially in those regions where the courts are overburdened. An example of this is China’s intelligent court system [144] that aims to modernize and automatize different aspects of court activities. These examples from three different fields demonstrate the promise in terms of benefits for society with the use of data science in the big data age, either by discovering new unknown knowledge in the data, or by automating routine processes. 1.1.2 Automated Data Science: Can We Trust it? The fact that more and more data is available has led data science to use more and more supervised algorithms from machine learning, the branch of artificial intelligence that autonomously learns mathematical models from data to automatize processes (and make predictions) with minimal human intervention. However, the strengths of using machine learning to automate processes are accompanied by several technical and ethical concerns that prevent a more extensive use of these algorithms. Here are some examples of these concerns also exemplified in Healthcare, Finances and Justice: Healthcare The use of autonomous techniques in healthcare raises several issues in accountability, transparency, permission and privacy [40]. Trustworthiness in Data Science and Artificial Intelligence 6 If a predictive cancer system (e.g., a system used to detect cancer in image analysis and suggest the optimal treatment) detects cancer and suggests a treatment for this cancer, the patient would like to understand how the algorithm made the prediction, especially if the prediction made by the system is that the disease is incurable and only palliative treatment should be provided. Similarly, the accountability of the algorithm would be complicated if the algorithm made a wrong prediction, and that might make it difficult for the patient to allow an algorithm to decide his or her treatment. A clear example of the difficulties in exploiting large amounts of data in medicine can be seen in IBM’s Watson. As we previously explained in Section 1.1.1, although it looked like a great opportunity for medicine, and IBM had partnerships with many hospitals in the USA, the results have been fair [128], and even in some cases its predictions were incorrect [114]. This is justifiable due to the difficulty of understanding ambiguities, subtleties and nuances from medical texts. These unsuccessful results (especially considering the hopes placed in the system) changed the original idea of IBM Watson replacing professional doctors to a more moderate and realistic purpose of assisting them. Finances According to the Home Mortgage Disclosure Act data from 20171, 7.9% of non-Hispanic white applicants, 10.1% Asian applicants, 13.5% of Hispanics applicants and 19.3% of black applicants for a conventional mortgage were denied. Apart from the fact that there might be a human racial bias in the home mortgage approval, the automation of this process using predictive systems might replicate these biases, leading to a white applicant being more likely to being accepted than a black applicant, even when their characteristics regardless of race (e.g., income) are the same. The problems related to the lack of interpretability are evidenced in [1], a web article from the FICO company (responsible for the FICO’s credit score) that analyses the use of machine learning techniques in their credit score. FICO’s results were fair: they could only increase 2% their predictive lift, while the new approach would have reduced transparency, being hard to explain to consumers and regulators their predictions. The trade-off between the improvement in metrics and the lack of interpretability did not justify using machine learning techniques. Justice In many cases the law is interpretable, and a judge is the one who has to interpret it. That is, the judge not only determines if a crime (or, for instance, a fraud) is committed, but also the punishment, e.g., if 1Available at https://files.consumerfinance.gov/f/documents/bcfp hmda 2017-mortgage- market-activity-trends report.pdf Trustworthiness in Data Science and Artificial Intelligence 7 Figure 1.2: FICO is one of the most important analyst companies in terms of creditworthiness, which evaluates the customer according to the five parameters from the image. According to their webpage [1], they are aware of the bias and data-related problems that can make the prediction unfair and, therefore, they avoid the blind use of machine learning models with no interpretability and the use of conflictive feature such as customer’s race. the accused is guilty, and if they are found guilty if they have to go to prison and the duration of the sentence. An example of this is the GENEQUAL project2from the University of Barcelona that analyses the reasons why a judge approves a restraining order. In general, the proportion of approved restraining orders should be similar throughout Spain (with maybe slight differences between regions due to socioeconomic reasons), but that is not the case. For instance, in Martorell (a city just outside Barcelona) the probability of getting a restraining order is only 22%, while in Sant Feliu de Llobregat (another city adjoining Barcelona) the probability increases to 66%. This research analyses if the judge (or the prosecutor) can influence this result (e.g., if female judges usually accept more restraining order than male judge, or similarly if female prosecutors also increase the likelihood of approval). This example indicates that the law (and its interpretation) is not rigid, and therefore, an autonomous system would be highly different depending on the data used: the existing prejudices, singular interpretations of the law, or political and religious opinions influence their sentences and, therefore, would also influence the autonomous system. If a predictive system is trained with harsh sentences, the resulting system could be biased to long sentences. This would be aggravated in situations where courts are influenced politically in war scenarios or political conflicts. These examples show that the implementation of autonomous models 2SR19-0208 “GENEQUAL-The Political Economy of Gender and Inequality in the Spanish Judiciary”, from “la Caixa” Social Research Call 2019 Trustworthiness in Data Science and Artificial Intelligence 8 to predict is, in certain cases, not feasible or, at least, very challenging. On the one hand, the data available to extract patterns may be biased and therefore might not correctly represent reality. Therefore, the predictive system might reproduce these biases in the prediction. On the other hand, even though the system is robust and accurate, their use would raise issues that discourage their use. 1.2 Application Areas and Published Work 1.2.1 Case of Study This thesis brings together three Data Science projects in which the correct use of data has been a key aspect of their development. Non-Technical Losses Detection System Our first case study (Part II) explains the development of an NTL detection system for the international utility company from Spain (Naturgy). In spite of the good results achieved detecting NTL cases (especially in certain cases in which previous approaches had very poor accuracy), we suffered many of the problems regarding the quality of the data. These problems hindered our system from achieving consistent and robust results. Once we made clear the existence of these data problems, we shifted our effort from trying to make a more complex method (with the aim of detecting more complex patterns) to achieving a more interpretable method, allowing both the scientists and the stakeholders to understand the patterns learnt (and therefore the detection of biases and undesired patterns). These data-related problems are partially explained in [61] but are not tackled in any other example of the literature. Explainable Predictive Process Monitoring In Chapter 7we explain our collaboration with the University of Padova to provide explainability to a KPI system currently implemented by the MyInvenio company. In this case we show that using explanatory black-box algorithms can provide robust explanations in line with the company’s analysts, with less human effort. Both the predictive process management and the explanatory algorithms are breaking new ground, and the resulting work [58] is a pioneer in bringing them together in the literature of business process management. Explainable Black-Box Algorithms in Social Science The classical dichotomy of interpretable algorithms vs black-box algorithm has not existed in Social Science literature since it is mandatory to understand the relation between variables. In Chapter 8we analyze, using as a reference [95], if the combination of black-box algorithms with explanatory methods can provide better results (e.g., a deeper understanding of the interaction Trustworthiness in Data Science and Artificial Intelligence 9 between features, or more flexibility) in Social Science projects than the classical approach of using the interpretable Regression or Decision Tree models. The unique characteristics of each project allow us to offer in this thesis a comprehensive analysis of the challenges and problems that exist in order to achieve a fair, transparent, unbiased and generalizable use of data in a data science project. With the feedback arising from the research carried out to provide satisfactory solutions to these three projects, we aim to: •Understand the reasons why a prediction model can be regarded as unfair or untruthful, making the model not generalizable, and the consequences from a technical point of view in terms of low accuracy of the model, but also how this can affect us as a society. •Determine and correct (or at least mitigate) the situations that cause the problems in terms of robustness and fairness of our data. •Assess the difference between the interpretable algorithms and blackbox algorithms. Also, evaluate how well the explanatory algorithms can explain the predictions made by the predictive algorithms. •Highlight what the stakeholder’s role in guaranteeing a robust model is and how to convert a data-driven approach to solve a predictive problem into a data-informed approach, where the data patterns and the human knowledge are combined to maximize profit. 1.2.2 Our Published Work The papers published from the NTL detection case study are the following: Fraud Detection In Energy Consumption: A supervised Approach 2016 IEEE International Conference on Data Science and Advanced Analytics (DSAA) [36] explains our first approach to building an NTL detection system by implementing a supervised classification system. Most of the information from this paper can be read in 3.1 (which includes information that contextualizes the NTL detection problem, including the related work) and in 3.3 (which describes the classification approach), although the two chapters feature information not included in those publications. A Quality Control Method for Fraud Detection on Utility Customers without an Active Contract Proceedings of the 33rd Annual ACM Symposium on Applied Computing [31] is our first approach of using an explanatory algorithm to provide explainability in our system that Trustworthiness in Data Science and Artificial Intelligence 10 uses a black-box algorithm. Different aspects of this work are reflected in Chapter 5that explains the explanatory methods tested in our system (including the LIME approach). Bridging the Gap between Energy Consumption and Distribution through Non-Technical Loss Detection Energies [32]. Analyses business-related aspects as well as other data-related problems from our NTL approach. Different aspects of this work can be read in Chapters 3.4 and 3.5. Non-Technical Losses Detection in Energy Consumption Focusing on Energy Recovery and Explainability Journal Track from 2021 IEEE International Conference of Data Science and Advanced Analytics, published in Machine Learning Journal [34] fully introduces the Shapley values in our system. As we explain in this work, the use of Shapley values made us understand well the shortcomings and problems of our system, and helped us to correct them by implementing several solutions (e.g. by using a regression approach instead of the classification approach until now). This work is explained in Chapter 4. Explainability in an Industrial Case: Predicting Non-technical Losses in Energy Consumption [30] corresponds to Chapter 5, where we provide an extensive vision of our effort to understand our predictions, ranging from using statistical methods to the use of Shapley values. A Human-in-the-Loop Approach based on Explainability to Improve NTL Detection International Workshop on Intelligence-Augmented Anomaly Analytics (ICDM 2021 Workshop) [33] introduces the possibilities that the combination of human knowledge and explainability offers to the system. A more extensive explanation of this paper is seen in Chapter 6. Knowledge-Based Segmentation to Improve Accuracy and Explainability in Non-Technical Losses Detection Workshop on Arti- Trustworthiness in Data Science and Artificial Intelligence 11 ficial Intelligence in Power and Energy Systems (AIPES), ECAI 2020 [25] analyses the benefits of building specific campaigns for each type of NTL. From our collaboration with the University of Padova, we have the following publication: Explainable Predictive Process Monitoring International Conference on Process Mining [58] describes how we have explained the predictions made by predictive process monitoring. This work is explained in Chapter 7.2. Regarding the collaboration with the Universitat de Barcelona, we have the following work published: The Logic behind NGOs’ Aid Allocation: a Complex Choice based on Past Decisions [95] analyses if an explained LSTM model can provide a better understanding than the interpretable Regression approach where NGOs implement their projects. This work is explained in Chapter 8.2. This paper is still under review process in a journal. Chapter 2 Preliminaries 2.1 Supervised Predictive Models Being Xthe labelled instances {(x1, y1), ..., (xn, yn)}, where xiis the feature vector that represents an instance and yithe value to be predicted, the supervised model aims to learn the function f, Y =f(X) (i.e. to learn patterns so that it can predict for each xithe corresponding yi), wherein a binary classification model Yis either 0 or 1 (or 0 ≤Y≤1 if the model provides probabilities), in a multi-class classification is a label, in a regression model the value to predict is continuous (i.e., Y∈IR), and in a ranking model the value to predict corresponds to a numeric rank label, also Y∈IR. The process of building a supervised model is complex. In general, it can be divided into three stages: the data extraction and pre-processing, the model building, and the deployment of the predictive system. A short description of each process is given hereunder. 2.1.1 Data Extraction and Pre-Processing The initial process consists of extracting the data from the data sources and its preparation to serve as input for the supervised model. In general, data extraction and pre-processing require different tasks [59], briefly explained as follows: Data Extraction, Transformation and Normalization The initial step consists of extracting the information from the data sources. In general, the data is stored in databases (or other data structures such as event logs) with a structure that does not suit the predictive algorithms and, therefore, needs to be processed to facilitate the pattern extraction. Moreover, it is necessary to normalize the information, that is that all the information that expresses the same information is provided with the same unit. Finally, some algorithms need a data normalization (i.e. representing all the features in a similar or even equal scale or range) to guarantee a good 12 Preliminaries 13 Tariff Consumption Town Last Fraud NTL case Customer 1 A 3500 kWh Sabadell No Customer 2 A 300 kWh Madrid 12 Months Yes Customer 3 B 450 kWh Vitoria 6 Months No ... Customer n B 2800 kWh Toledo 38 Months No Learning Algorithm Tariff Consumption Town Last Fraud Customer n+1 B 300 kWh Terrassa 12 Months Customer n+2 A 4000 kWh Zaragoza 9 Months Customer n+3 B 1000 kWh Donostia Customer n+4 B 3650 kWh Almeria ... Customer n+m B 3200 kWh Toledo Value Predicted 0.8 0.2 0.51 0.1 0.3 Supervised Predictive Model Figure 2.1: Visualization of a supervised model. The learning model has a labelled dataset from which builds the Supervised Model. This model is then used to predict non-visited profiles. performance. Some of these algorithms that need data normalization are the statistical learning methods (e.g. Linear Regression) or the K-Nearest Neighbors that predicts based on Euclidean distance between instances. Data Cleaning The process of correcting the quality of the data when the data is extracted from the original data sources, i.e., to remove incorrect or unnecessary data, detect redundancies and inconsistencies, is referred to as data cleaning. This process includes the decision regarding what to do when data is missing. Depending on the characteristics of the missing data and the problem to be solved, the missing data can be imputed (e.g. through other machine learning algorithms such as the K-Nearest Neighbors [13,26]) or removed. A similar analysis is done if there exist noisy data in the system (e.g. outliers related to human errors when obtaining the data), where a correction can be applied when possible, otherwise the data can be removed. Data Reduction Data Reduction encompasses different techniques that reduce the data dimensionality, maintaining the same essential information and integrity. Removing unnecessary information (e.g. by removing correlated features or applying Principal Component Analysis [123]) helps to avoid multicollinearity in linear models, which leads to numerical instability [5]. In addition, it is also recommended to avoid the curse of dimensionality [136], where large amounts of data both hinder the training efficiency in terms of computational cost but also in obtaining high-quality models. In general, Preliminaries 14 data reduction does not include reducing the number of instances (as it is generally considered that the more data one has, the better). However, it can be considered beneficial in specific circumstances (e.g. when there is some over-represented type of instance, or when the quality of certain data is in question). 2.1.2 Model Selection, Parameter Tuning and Loss Function Once the data is prepared, it is necessary to train a model to learn the necessary patterns from the data to make good predictions in unseen instances. In general, the process of building a model follows a recursive feedback structure: a model is built, then its correctness is analyzed (i.e. how well the predictions fits the desired results), to finally update it with improvements and other modifications to building the model again to improve its accuracy. Loss Function and Optimizers Building a machine learning model consists of learning patterns from the data, i.e., extracting patterns that reduces the difference between the current’s algorithm output and the expected output. This process is iterative, wherein each iteration the model measures how well the system predicts, updating and adjusting the model to reduce the said distance (i.e., the learning process). The function that measures the distance between the expected and current output is the Loss Function. Some of the most common metrics referred to in this work are the following: Log Loss Log-Loss measures the performance of a classification models, and it can be can be defined as follows: LogLoss =−1 n n X i=1 [yi·loge( ˆyi) + (1 −yi)·loge(1 −ˆyi)] (2.1) Log Loss error increases as the predicted probability diverges from the label, penalizing confident and wrong predictions. MAE The Mean Average Error is a regression metric that metrics the average of the difference between the values predicted and the real values, defined as follows: MAE =1 nX i=1 |yi−ˆyi|(2.2) Preliminaries 21 specific regions or customers with a normal consumption curve) were not correctly represented in the labelled dataset. This, together with the fact that the data was non-stationary, implies the existence of dataset-shift [105]. In any case, the development and use of data by design do not guarantee its quality since the designer can introduce human biases in the data. For instance, there is no possible nuance in the label of whether an animal is a dog or a cat, but the definition of creditworthiness of a bank customer, what a good worker is in a company or the value of an elite sports player are values that can be nuanced depending on personal opinions. Moreover, the human role in a data modeling system can prejudice or confirm bias. All and all, these data-related problems challenges the correct development of a predictive model. The patterns learned might not generalize well and be biased, a fact that can be aggravated if the system learns from its own predictions, reproducing the well-known feedback loop bias [83]. Model Generalization and Evaluation Assuming that there is no evident bias nor misrepresentation of the case study in the labelled instance, one would expect that the predictive algorithm should be good enough to provide accurate and fair predictions. Nevertheless, in many cases, that is not the case. Returning to the idea of unbiased data, and also considering that we strive to guarantee a good benchmarking of our system (an element that, as explained in [48] is complicated to guarantee), the analysis of the patterns learned by the model should be the keystone to guaranteeing the correctness, fairness and quality of our model: if the model learns causal patterns [100], then our system should be correct. The problem with this approach is that, in many cases, the algorithms learn correlations that have no truly causality in the prediction. An example of this situation is the adversarial examples in machine learning: instances very similar to other instances that the predictive algorithm would properly classify, but with small (and intentional) feature perturbations that trick the machine learning model into making a false prediction. In some cases, the error can be justified (e.g. a spam e-mail that resembles a normal one), but in many cases, the error, from a human point of view, is unjustifiable (see Figure 2.4). To guarantee the causality of the patterns learned, first, it is necessary to determine what patterns the system has learned. This is a very complicated concept since in many cases, it is not possible to determine what a model has learned. There are (broadly speaking) two different types of predictive algorithms: the interpretable algorithms and the blackbox algorithms. The first type of algorithms are considered less accurate and, therefore, scientists tend to use black-box algorithms that can not be interpreted and require explanatory approaches to understand the algorithms. Therefore, if it is very challenging to understand a model, we cannot guarantee that a good model in terms of accuracy is learning good Preliminaries 22 Figure 2.4: Example from [64] where an Artificial Neural Network erroneously classifies a panda as a gibbon after an adversarial modification of the image of the panda. This can be seen as the prove that the deep learning method does not find causal patterns to identify the panda but due to noisy characteristics of the image that are not related to the ground truth causal patterns or if, on the contrary, it is reproducing unethical biases that prevent the model from generalizing correctly. 2.2 Model Transparency and Explainability There exist in the Machine Learning community the belief that the tradeoff between accuracy and explainability should be considered when using a predictive algorithm: the most accurate algorithms are not interpretable, while the most interpretable algorithms might have limitations in terms of accuracy (Figure 2.5). Figure 2.5: Image from [66] that visualize the trade-off between accuracy and explainability and sumarise the idea that the more precise the algorithm is, the more difficult it is to explain. This image has been popularized with the DARPA’s XAI program to create tools to understand and trust the most accurate algorithms. Preliminaries 23 2.2.1 Interpretable Algorithms Some predictive models are considered interpretable, i.e., one can understand the patterns learned by the model from the training dataset, how these patterns influence the predictions, and even predict how a change in a feature would affect the prediction. The most popular interpretable algorithms are the linear and non-linear Regression models (where the coefficients indicate how each feature influences the output model), the Decision Trees [20] (where one can follow a path in the tree to understand how the model scored an instance), the Decision Rules [69,29] (where the predictive models are a set of if-else statements that can be easy to understand), the Naive Bayes [89] (where the model is interpretable due to the independence assumption of the features as a conditional probability) or the k-Nearest Neighbors [6,67] (where the label of the neighbors of an instance explain the prediction of the model). Below we provide a better explanation of the linear and logistic regression model, and the Decision Tree. Both algorithms appear in the case studies of this thesis. Linear and Generalized Regression A linear regression model is a statistical method that models the relationship between a dependent variable (i.e. Y) and the independent variables (i.e. X) as a weighted sum. As indicated by the name, the relation between the variables are linear, defined as follows: y=β0+β1x1+. . . +βpxp+(2.8) where βcorresponds to the coefficients of each independent variable, being β0the intercept term (a constant value) and the error. Linear Regression is usually used in medicine [63], economics [45] or sociology, fields that quantitative research needs a straightforward interpretation to validate or discard hypothesis; different libraries in R and Python has built-in summary functions that facilitate their interpretation. The linear regression algorithm finds a correct model if the following assumptions are met in the data: Linearity: The prediction in a linear model is a weighted linear combination of features. In a way, this is the reason why the linear regression are fully interpretable. Homoscedasticity: The theory says that in a linear regression model the residuals should equal across the regression line, i.e., the variance of the errors are constant over the feature space. In reality, this is difficult to achieve since the variance of error is higher for higher values to be predicted (e.g. when predicting the price of a house or a car, where there exist a high difference in value between cheap and expensive instances). However, it is intended that the errors are not excessively different proportionally throughout the prediction. Preliminaries 24 Independence: Observations are independent of each other. Normality The target outcome should follow a normal distribution. If this assumption is not met, then the confidence intervals of the coefficient weights are not valid. No Multicollinearity: The independent variables are not highly correlated with each other. The existence of very correlated information hinders the proper assignation of weights in those features. When these assumptions are not met, the linear models are not a good approach. In some cases, it is possible to bypass these problems by implementing feature engineering (e.g. by removing correlated features). In other cases, it is not possible to fit the problem in a linear regression model as is, e.g., when the value to predict is binary. In these cases, the generalized linear models (GLM) might be an optimal solution. The GLM are an extension of the classical linear models in which the prediction of a linear model is transformed using a nonlinear function to achieve the non-normal output. The most popular generalized model is the logistic regression that adapts the linear regression to fit the output between 0 and 1, used for classification problems. The logistic function is defined as: P(y(i)= 1) = 1 1 + exp(−(β0+β1x(i) 1+. . . +βpx(i) p)) (2.9) The interpretation for the logistic regression is not as straightforward than the linear regression, since the logistic regression model is a linear model for the log odds: log P(y= 1) 1−P(y= 1)=log P(y= 1) P(y= 0)=β0+β1x1+. . . +βpxp(2.10) Decision Tree Decision Tree is another well-known interpretable algorithm from machine learning in which the relationship between the features and the value to predict is, in contrast with the regression model, not linear. The Decision Tree is built by recursively splitting the source labelled instances into subsets until the subset can not be partitioned anymore, i.e., if all instances from the set have the same label or if the configuration established determines that it should not be divided anymore. The process of division is used by dividing the set depending on the value of a feature, maximizing the benefit of the split (i.e. reducing the Gain Impurity, Increasing the Information Gain, or reducing the variance of the set). Another difference between the Decision Tree and the Linear Models is that the Decision Tree offers both instance and modular explanations. At instance level, the interpretation of the Decision Tree consists of following the path the instance goes in the splitting process. In Figure 2.6 there Preliminaries 25 is an example of a Decision Tree trained with the well-known Iris dataset [53]. To obtain a modular explanation (i.e., the feature importance), it is necessary to compute for each split the benefit (e.g., the increase in terms of Information Gain) after splitting through that feature. Figure 2.6: Example from Scikit-Learn of a Decision Tree that classify the Iris Dataset. If a Decision Tree is plot, it is easy to follow the feature splitting process to determine the prediction of a non-labelled instance. The main benefit of using Decision Tree models is its simplicity, but it has several problems. For instance, Decision Tree do not generalize well (i.e. overfits the training dataset) and can be unstable. 2.2.2 Black-Box Algorithms As seen in previous Section 2.2.1, the interpretable algorithms consist of algorithms that are interpretable due to their simplicity, in many cases thanks to several assumptions that need to be met to guarantee good predictions. In contrast, the black-box algorithms are non-interpretable algorithms. A priori, these algorithms offer better prediction capacity due to their complexity but at the cost of the aforementioned lack of transparency. The most paradigmatic black-box algorithms are the Gradient Boosting Ensemble Tree algorithm (and all the ensemble methods) and the deep learning algorithms. Both algorithms are used in this thesis. The Gradient Boosting Ensemble Tree Algorithm There exist in the literature different approaches to combining shallow trees to increase the performance, reducing bias and variance. The bagging Ensemble Trees (that consist of training a bunch of individual models in Preliminaries 26 a parallel way, where each model is trained by a random subset of the instances, and predict as an average of each tree [17]) or the Random Forest (that can be defined as a bagging process where, for each tree, only a subset of features are used [19]) are two well-known examples in the literature, used for many different predictive problems. In [56] there is the explanation of a different ensemble approach called Boosting, i.e., the AdaBoost. This approach combines different tree algorithms as follows: 1. An initial tree model is trained. 2. A new tree model is trained. In this case, the weights of the misclassified instances of the previous tree are increased to focus on their correct prediction. This process is done iteratively N times. 3. The final prediction corresponds to a weighted average of the predictions of each tree, with greater weight given to those trees with higher accuracy. The Gradient Boosting Tree is a different approach to combining weak learners. In contrast to the AdaBoost approach that builds independent Decision Tree Model and combines them, the Gradient Boosting Ensemble builds a boosted method where the tree at the n+1 stage aims to minimize the errors stochastically from the nstage (see Figure 2.7). That is: 1. An initial Tree is trained to minimize the function loss, e.g. the LogLoss function for a classification model or the Mean Average error for a regression model. 2. A new tree is trained to correct the error of the previous tree, i.e. the residuals. This process is performed iteratively until the residuals are zero or the configuration of its hyperparameters so indicates. 3. The final model corresponds to the prediction done from the first decision tree until the last tree, i.e. there is no combination of different predictions but one unique prediction. The boosting of trees has low interpretability: for the first (or few first tree) it is possible to follow the splitting process of the trees, but in general the ensemble has several hundred or thousand trees that make manual interpretation unfeasible. Some state-of-the-art implementations in python are the XGBoost [28], the LightGBM [73] and CatBoost [103], methods that introduce several improvements (e.g. better regularization to avoid overfitting) to the classical Gradient Boosting approach. Preliminaries 27 Figure 2.7: Example extracted from [145] to explain the Gradient Boosting Tree model: In each iteration, the new tree nreduce the errors of the model. The Deep Learning Algorithm Artificial neural networks (ANN) (Figure 2.8) is a predictive model consisting of consecutive layers of neurons, i.e., computing units, in which each neuron receives different weighted input values and produces an output. In the classical Neural Network (with forward propagation), the input layer receives the input instances, the layers (and their neurons) process the instances, and finally predict the output in the last layer. The error is then back-propagated and the weights of the neurons are updated (via the optimizer) to reduce the error done by the predictive model. There exist different methods of connecting the layers in a neural networks, and also different activations of the neurons (i.e. different ways of generating an output with the same input). Initially, artificial neural network were shallow, i.e., had only one or very few layers. Over the last 20 years, in conjunction with the increase in computer power, we have seen artificial neural network become deeper and more complex: these more complex models correspond to deep learning. Preliminaries 28 Figure 2.8: Image from [68]: there is an input layer, an output layer, and different hidden layers. The classical neural network is the feedforward backpropagated neural network, where the data only moves from input to output without loops and cycles. The recurrent neural network is an evolution of the feedforward neural network, where loops and cycles are included to maintain historical information. It is used specially in image and speech processing, but has the problem of gradient vanishing and exploding: in recurrent neural networks (or in very deep learning models), there is the stability issue where in certain scenarios (e.g., a neuron with a large input and a sigmoid activation of a deep neural network learned using backpropagation) the derivative becomes too small to learn (gradient vanishing) or too large (gradient exploting). This is solve by using other activation functions (e.g. Relu) or other deep learning structures (e.g. the LSTM that introduces memory units to store information in an undefined time with no degradation). The deep learning algorithms are considered the less interpretable predictive algorithms. 2.3 Explainable AI Explainable AI (XAI) is a new term popularized by DARPA’s XAI program [66] that refers to techniques, methods and algorithms that explain the predictions made by the black-box algorithms and arises as a response to the technical, social and legal concerns of the increasing use of artificial intelligence techniques (especially these black-box algorithms) in our lives, as we introduced in the Introduction (Section 1.1). Explaining a prediction is a general term that encompasses different techniques and approaches depending on the objective to be achieved (i.e., the reason why we want to understand our algorithm) but also the algorithm to be explained, and can include approaches that present textual, numerical or visual information that allows the human to understand the predictions. Preliminaries 29 2.3.1 XAI goals The XAI community has highlighted many different goals around the need to explain an algorithm. Nevertheless, all of them can be categorized as either a technical goal (i.e., whether the system is trusted) or an ethic goal (i.e., whether the model is unfair). How Reliable are the Predictions? Technical Analysis In [110], trust of a prediction is defined as ”whether a user trusts an individual prediction sufficiently to take some action based on it” and model trust as ”whether the user trusts a model to behave in reasonable ways if deployed”. Both definitions of trustworthiness are intrinsically related to the patterns learned by the model: if the model learns causal patterns, then it can be trusted, since it correctly infers the causal relationship between the features and the target. However, as broadly analyzed in the literature [99,100], the predictive algorithms can not understand the quality of the patterns learned (i.e., whether the pattern corresponds to a causal relationship, to a logical but non-causal correlation, or whether the pattern corresponds to a mere coincidence that should be avoided) and therefore a human validation of the model with high knowledge of the automated process is necessary. For this reason, much literature emphasizes that XAI must also guarantee model transparency, i.e., the model must be highly informative of the learned patterns to facilitate the detection of undesired behaviors of the predictive algorithms. Moreover, this transparency should not only focus on the validation of the trained model, but also on the acquisition of new knowledge (e.g. acknowledgment of trustful patterns previously unknown) and also facilitate the implementation of different machine learning techniques (e.g. transfer learning). Once a reliable and transparent model that systematically learns robust and reliable patterns is achieved, the model’s users will have confidence in its use. Confidence in the model is key to relying on data to make decisions in the industry (often referred to as data-driven solutions). How Fair is the Model? Legal and Ethic Concerns From a social perspective, explainable AI is the solution to control and audit machine learning methods that automatize processes in which citizens are affected. The aim of this control is to detect biases and other data problems that would reproduce and entrench historical prejudices against citizen communities, and thus ensure fairness in automated predictions. To ensure this control by regulatory institutions or even the ordinary citizen, it is necessary to guarantee the accessibility of these algorithms, i.e., that nontechnical users affected by these decisions should be able to access the prediction made by an algorithm and the patterns learned. Preliminaries 30 2.3.2 XAI Approaches Explaining a predictive black-box model is dependent on human judgment and is therefore difficult to uniquely mathematize. There are two operational definitions of explainability: model-level and instance-level. Model-Level Explainability If Mis a trained predictive model that receives instances x= (v1, . . . , vn) to predict, a model-level or global explanation of Mis a vector (w1, . . . , wn) that describes how each feature xi globally influences the predictions made by M, typically computed on the training instances used to build M. Instance Level Explainability An instance-level or local prediction provides such a vector for a specific instance x, therefore how Mis influenced by each feature to produce its specific prediction M(x). In the following we explain the explanatory methods used in this thesis, as well as a brief summary of other explanatory approaches in the literature. Feature Importance In tree models (i.e.,a decision tree, or an ensemble of trees) it is common to analyse the importance of each feature by computing the Feature Importance, providing a model-level explanation. Depending on how it is computed, the importance of a feature can be divided into prediction and occurrence methods: •Prediction methods: they analyze the influence of feature values in the predictions made by the model. This naive definition includes, for instance, the Random Forest from Scikit-learn [101] (that evaluates the Gini impurity of the samples of the nodes decrease after a split using that feature), or the LossFunctionChange from Catboost [103] that evaluates how the prediction changes if that feature is removed. •Occurrence methods: Measure the importance of the feature by analyzing its occurrences in the training process, i.e. how many times the feature has been used in the splitting process, usually referred to as weight or frequency, or the number of instances in the node split by that feature, usually referred to as coverage. Local Surrogate Models Local surrogate models are simple interpretable models that aim to replicate the prediction made by complex black-box models for one specific prediction, i.e. provide an instance-level explanation: Let Mbe a predictive model that the surrogate model aims to explain, xbe the instance to explain, and Lnbe an interpretable model (e.g., a linear Regression) trained Preliminaries in Non-Technical Losses Detection 37 campaign design is all about the classical precision-recall trade-off. Traditionally, campaigns are based on simple sets of rules indicating fraud (e.g., abrupt decrease of consumption, or no consumption during a long period of time). These rules can be used to detect the fraudulent/irregular customers, but achieve a low success rate, not much higher than selecting customers for the campaign at random. This can be explained by many other reasons besides fraud (e.g., a customer spends a long convalescence in hospital, or the house is a second residence that does not follow the consumption patterns of an all-year primary home). With the booming of artificial intelligence in industries, the utility companies have seen the possibility of exploiting the large amount of data available from their customers, especially since the installation of smart electricity meters. Naturgy is a utility company distributing both electricity and gas in Spain and 26 countries on 5 continents. Their classical approach of detecting NTL was based on simple rules with only fair results. In mid 2013, the company approached UPC researchers looking to improve the fraud and anomaly detection rate of their current campaigns. The first dataset received from the company was to be used to generate a static campaign (no software system). It came from a medium-size city with a few thousand electricity customers and another few thousand gas customers, and contained contract information (e.g., the tariff or the age of the meter) and about two years of consumption information. After this initial dataset, we received four more datasets with similar characteristics (i.e., cities with thousands of customers), either of gas or electricity or both. From the sixth dataset onwards, and in view of the good results of the initial campaigns, we were given access to data on a national scale, with information of several million customers in gas and another several million electricity customers; around a million customers are customers of both utilities; the project gradually evolved from the original goal of “mining” one specific dataset to create a one-off campaign to the development of a software system that connects to the company’s operational system to generate both routine campaigns and on-demand parameterized campaigns, implementing data mining techniques to manage feedback, and investigate the usefulness of new features, among other functionalities. 3.2 Related Work There exist in the literature several techniques to detect NTL based on customer data. A very common approach to detect NTL is to implement a supervised system. In [23], a similar approach to ours was presented (it uses Gradient Boosting models and is implemented in Spain); in [90] an approach that uses Support Vector Machines is reported, and in [91] an update of the previous work in which the addition of Fuzzy Rules improves the detection system; in [37,102,55,52,142] five examples of using neural networks to detect NTL are described, and in [107,108] two interesting Preliminaries in Non-Technical Losses Detection 38 approaches that differ slightly from the classical supervised algorithms that use the Optimal-Path Forest Classifier [96]. In contrast to the aforementioned supervised techniques, there are also other different unsupervised approaches to detect NTL in the literature. The typical technique is the clustering method, seen in [12] or [10], but we can see other approaches such as [24] that uses unsupervised neural networks (Self-Organizing Maps). A different technique is seen in [127] or [80], which are two examples of using statistical process control method in the detection of anomalies from a more industrial process control point of view. Despite the fact that the more classical machine learning approaches use supervised and unsupervised methods, other alternatives exist in the literature. For instance, in [27] there is an example of an expert system; also, [71] presents an approach for analyzing the load flow, and in [143] a method based on the sensors of the system is proposed. In [62] there is a technical survey that analyses the challenges seen in different papers such as the dataset shift, the features built and scalability, and in [86] there is a more classical survey that summarizes the approaches seen in the literature. 3.3 NTL Detection: Baseline Approach Our work published in [36] explains our Non-Technical Losses Detection system based on a classification model at the time of the publication of the paper. We use that paper as a reference to explain our first approach in this case study, and update the information when necessary with the updates introduced in [32]. 3.3.1 Data Processing The sources of data used to build our NTL detection system include consumption and profile data, historical fraud cases, and some external information. Consumption data This is the data reflecting the energy used by the customers. It includes meter readings as well as billing statements - the invoices the company charges to the customer based on the meter readings or, when not available, an estimate by the company based on historical information1. The consumption reading corresponding to the difference between consecutive meter readings of the customer is our main source to extract the consumption data; Figure 3.3 is an example. Note that from this information one cannot detect the fraud cases in which someone 1This is true before the installation of smart meters of around 2016 onwards Preliminaries in Non-Technical Losses Detection 39 18% 36% 46% Readings from smart meters Unique old-meter readings Repeated old-meter readings 32% 36% 32% customers <12 smart readings customers 12-24 smart readings customers >24 smart readings Figure 3.1: Information from the quality of the information available in [36]: Half the customers for electricity had smart meters. From all the readings we had, 18% came from smart meters, 36% were unique readings from old meters and 46% were repeated. Of the customers that had smart meters, around 32% had less than 12 smart-meter readings, 36% had between 12 and 24 readings and the rest had more than 24 readings. 42% 58% Unique gas readings Repeated gas readings Figure 3.2: 42% of the readings from gas are unique, and 58% are repeated. In gas, the absence of smart meters makes the information available less reliable. connects directly to the grid rather than e.g., manipulating the meter; this type of fraud can only be detected further upstream. The origin and reliability of consumption data for our first approach was varied. In electricity, about half the customers had smart meters that send customer consumption to the utility company monthly and reliably. The other customers had old meters that required manual readings: customers were expected to use any one of a number of options to send in the reading (calling the company, sending the reading via mail or a mobile app, or writing it down on a shit or form available in the building). In gas there were (and there are still) no smart meters, so all the information is sent manually. When there were no smart meters and the customer had not provided the reading, the company needed to estimate the consumption of the customer using reference values from similar historical periods. Customer-generated readings were notoriously unreliable and error-prone, and many customers simply did not send any for many months in a row. Eventually a technician would be sent to read the meter, but only after sev- Preliminaries in Non-Technical Losses Detection 40 Figure 3.3: Example customer consumption record. In light gray, useful information (new readings and monthly consumption). In dark gray, non-useful information (i.e., erroneous information is crossed out, in italics repeated readings, with a dash months without readings). Non-smart meters give less accurate monthly consumptions; in this case, the first October reading is obviously wrong, so apportioned consumption because we have new readings every two months. Since the second July, consumption readings are reliable because a smart meter was installed. eral months of estimated readings. Fortunately, each consumption record was labelled as company verified, customer provided or estimated, so we could assign them different reliabilities. Erroneous, absurd or missing readings for non-smart meters, the coexistence of two metering systems with different reading periodicity (1 vs. 2 months between readings), and the fact that some customers changed from one system to another in the process (a small proportion of clients had more than two years of smart-readings in 2016) were complications that we had to deal with when reading, parsing and standardizing consumption data. Static Profile Data Within this concept we include information related to the customer’s contract with the company (e.g., the tariff), customer information (e.g., their address) and characteristics of the equipment (e.g., the age and model of the meter, whether it is inside or outside the house). This information can be used to categorize the customer; for example, the tariff indicates whether it is a home, a shop or a restaurant, and whether a gas cooker or central heating is present. Historical Fraud Cases For the first campaign, we were also provided with a list of customers who had committed fraud and were discovered in baseline campaigns carried out by the company in the last few years. The list included several tens of thousands of verified fraud cases which could be merged with their consumption data to investigate fraud patterns. No “negative cases” (i.e., clients that were known to not commit fraud) were received. Preliminaries in Non-Technical Losses Detection 41 FEATURE DEFINITION Abrupt decrease in consumption A reduction of x% in consumption during nmonths in comparison to the previous nmonths. Abrupt decrease in equivalent consumption A reduction of x% in consumption during nmonths in comparison to the same months from the previous year. Long period of low consumption A reduction of x% in consumption during nmonths in comparison to the average. Consumption discrepancy High/medium/low discrepancy between a consumption in comparison to the average. Decrease in consumption (correlation) A consumption reduction during nmonths using Pearson correlation. Consumption peak Consumption in a month x% times higher/lower than the previous and the following month. Billing/consumption similarity Similarity between the consumption computed and the billing (only in gas). Unknown consumption Number of consecutive estimated readings, consecutive 0 consumption (in the present and historically), Difference between years Highest difference between the consumption of two consecutive years, or if the customer has been consuming less year after year (only in gas). Gas consumption without electricity Gas consumption without electricity. Difference of consumption High/medium/low difference between the higher and the lower consumption of the customer. Ratio difference of consumption High/medium/low difference between the average consumption of the customer and the average consumption. Negative Consumption Whether the customer has a negative consumption (e.g., count was reset at the installation of a new meter). Reading correction Whether the consumption obtained required a correction. Table 3.1: Types of features extracted from the data available. In some cases, several versions of the feature are included in the system (e.g., abrupt decrease in consumption, where different x% and nlead to different features, or using Spanish and regional averages to compute different features). External Information We also used the Koppen climate classification data [4,3] of the different regions under study, as climate obviously affects energy consumption patterns, as well as census data about the socioeconomic classification of cities and regions. 3.3.2 Creating a Classification Problem Below there are the three main issues we had to tackle when transforming the data into a classification problem. Unreliability in Consumption Data As discussed before, consumption data as given by the readings was not an exact picture of the customer consumption but an approximation, because of the heterogeneous channels used to obtain the readings. For instance, in Figure 3.3 it can be seen that the reading in February is wrong, according to the readings in January and March. A small number of heuristics were designed to correct or discard Preliminaries in Non-Technical Losses Detection 42 FEATURE DEFINITION Tariff Tariff of the customer. Location of the meter Location of the meter (e.g., inside/outside the house) Contracted power Contracted power (only in electricity). Electric tension Electric tension (only in electricity). Abnormal contractual status The client has abnormal contractual status (e.g., has canceled the contract with the company). Regional income Whether the customer lives in a region with an average income above, similar or below the Spanish average. Climatology K¨oppen climatology classification of the region where the customer lives. Reading periodicity Reading periodicity (1 or 2 months, only in electricity). Number of readings High/medium/low number of different readings from the customer. Province The province where the customer lives. Capital province Whether the customer lives in a province capital. Date information Age of the meter, date of installation and contract. Smart meters Whether the customer has a smart meter. Old fraud Whether the customer was detected as fraudulent by the company in gas or electricity in the past. Table 3.2: Types of features extracted from the data available. In some cases, several versions of the feature are included in the system (e.g. abrupt decrease in consumption, where different x% and nlead to different features, or using Spanish and regional averages to compute different features). suspicious or inconsistent data, both in gas and electricity (e.g., discard a reading smaller than the previous and the following reading, or discard an absurdly high reading for a month, replacing them with interpolations). Billing information was also used, but as a secondary source compared to actual or estimated readings. Statistical Evaluation of the Features The main metric used to evaluate the features was the odds ratio (the odds that an outcome will occur given a particular case, in comparison to the odds that the outcome will occur otherwise), from now on denoted as OR. For each feature, we analyzed the OR between the results from the feedback (e.g., the OR between fraudulent and non-fraudulent customers), denoted as ORPN, as well as the OR between the fraudulent clients against all the clients not included in any campaign, denoted as ORPG. Table 3.5 shows the odds ratios of some features used. Feature Construction Consumption, profile, and external information were combined to create a number of features. These features are the result of an evolution of the initial rules used by the company for their baseline campaigns (e.g., the detection of customers with a long period of time with no consumption). Yet, each rule used in the baseline campaigns used one or at most two of the features, while we expected machine-learning-based algorithms to be more accurate by taking into account hundreds of features as well as their combinations. Preliminaries in Non-Technical Losses Detection 43 Some features focused on the behavior of the customers in comparison to themselves: an abrupt or gradual decrease in their consumption exemplified in Figure 3.4, a repeated lack of reported readings, a substantially different pattern from previous years, consumption peaks (as seen in Figure 3.5), the difference between the minimum and the maximum consumption of the customer, etc. Figure 3.4: Example variable: consumption drop. Figure 3.5: Example variable: consumption peaks. We can see that the customer has both a positive peak (4th month) and a negative peak (11th consumption) in its consumption curve. Other variables measured the inconsistencies of customer consumption in comparison to other similar customers. For example, long periods of time where the customer consumes much less than the average of the customers with the same tariff (exemplified in Figure 3.6), high discrepancy between the consumption curve of the customer and the typical consumption curve of the customers with the same tariff (a flat consumption line showing no seasonality pattern may indicate that the metering has been tampered with so as not to exceed a certain metering speed, as seen in 3.7), nominal difference between the consumption of the customer and the Preliminaries in Non-Technical Losses Detection 44 average consumption of the clients with the same tariff, etc. Figure 3.6: Example variable: long period of low consumption. As we can see, we have a period of time (from months 4 to 9) where the customer consumes much less than the average. Figure 3.7: Example variable: consumption discrepancy. Customer 1 has a similar consumption curve to the average consumption. On the other hand, both customers 2 and 3 have an abnormal curve that might be an indicator of fraud. It is worth mentioning the features that combined information from gas and electricity consumption (e.g. the behaviour comparison between the gas and electricity consumption, or the consumption of gas without electricity consumption, exemplified in 3.8). These features, tested statistically, were only included in the most recent campaigns, which are the more successful ones. From the static data we also extracted some features; the province where the customer lives as well as its climatology, the location of the meter, the date of installation of the meter, etc. Table 3.2 contains a list with the feature types included in our system. These variables were all binarized, for uniformity and simplicity; in particular, this avoided problems with algorithms that are too sensitive to Preliminaries in Non-Technical Losses Detection 45 Figure 3.8: Example variable: Gas Consumption without electricity consumption. Gas heater needs electricity to work. outliers or extreme values. For example, one binary variable was introduced for each tariff type that a customer may have. In some cases, several variants of the same variable were introduced, corresponding to different horizons or thresholds; for example, whether there has been a reduction of x% in the last nmonths generates many variables for varying xand n. For each candidate variable, the ORPG was checked, and those variables with values near 1 that were not useful (e.g., did not have profiling information) were removed. All in all, the number of variables included in our first approach reached 250 features in the electricity campaign and 150 features in the gas campaign. At the end of this process, a customer is represented (with the information available at the time of generating a campaign) as a vector of binary variables, which we call the customer profile. Imbalanced Classification Problem We created a classification problem by labelling each customer profile in a potential training dataset either with the positive class (P), representing fraudulent behaviors, or the negative class (N) representing non-fraudulent behavior. For populating P, we considered customers from the historical fraud cases and those detected as fraud in previous campaigns. Populating N was a problem in the initial campaign, as we did not have certified non-fraud cases; we simply took a random sample of all customers, which should be approximately correct under the assumption that fraud prevalence is low enough. As we started receiving feedback from the first campaigns, we did have certified negatives. The prediction desired from the system could be a P/N value. In this case the campaign is simply an unordered set of suspicious customers (predicted to be P). The company, however, preferred to have a fraud scoring, or probability of being fraud, for each customer, which makes the campaign an ordered list; this allowed us to detect in-place that a campaign had entered a point of diminishing returns. Preliminaries in Non-Technical Losses Detection 46 3.3.3 The Process Our NTL detection system could be explained as follows (see Figure 3.9): 1. From the data sources we extracted all the necessary data to create the variables. 2. We created a profile of each user, a vector of variable values that defined their behavior up to a certain date. 3. Based on feedback from older campaigns, we ran a number of supervised algorithms in a number of configurations to determine which one could be best for this campaign. 4. We used the chosen model to compute a fraud score (a prediction or probability) for every customer in the target area for a new campaign. We excluded customers that had already been checked in recent campaigns. 5. We created a campaign of a desired size Nby selecting the Ncustomers with highest fraud scores. 6. When the campaign results returned from the field, the feedback (verified fraud and non-fraud cases) was added to the system automatically2. Campaign configuration Data extraction Data source User profiling Training learning Campaign generation Feedback manipulation Classification Figure 3.9: The Process of NTL Detection. This methodology allows iterative learning from the feedback from previous campaigns, as well as the addition of new algorithms and variables. A detailed description of the procedure is given below. 2The company centralizes all the campaigns results introduced manually by each technician in a database, and our system reads this information automatically to update the feedback. Preliminaries in Non-Technical Losses Detection 53 Plabeled(x) denote the real population and labeled (train) fraud distributions, it often happens that Plabeled(x)6=Ppopulation(x), since Plabeled = Ppopulation(x|s= 1), where sis the binary condition of visit (i.e., if the customer was visited)) in some segments: the company’s labeled instances (i.e., the results of the campaigns from the last two years) do not reflect faithfully the distribution from the company’s customers, since this strongly depends on the historical success of the campaigns conducted before in that particular segment. This imbalanced training dataset generates biased models (see for instance Figure 3.13). For this specific case of imbalance, we created specific campaigns, insulating these customers that are over/under-represented. That is: •Over-representation campaigns: The over-representation of a type of customer can absorb all the classification capabilities (i.e., that the system only learns to classify that type of customers). A consequence of this is that only the over-represented type of customer receives a high score. To avoid this, isolating these customers and generating a tailored campaign for them avoids the imbalance. •Under-representation campaigns: There are cases where the information from a type of customer is not good enough to detect fraud (e.g., there are no positively labeled cases) and therefore that type remains unconsidered. Generating specific campaigns for this type of customer, even though the labeled information is not extensive, forces the system to detect NTL patterns for this under-representation. Figure 3.13: Real example of the dataset-shift problem between the proportions of the real domain (customers from Spain with no contract in November 2018) and the labelled instances of the customers with no contract (feedback available from the same type of customer since October 2016); in the region of Madrid the company has more cases of NTL than in any other region, and this led our system to over-estimate the score assigned to the customers in that region. This was solved through a segmentation, generating two different campaigns (Madrid and the rest of Spain). Preliminaries in Non-Technical Losses Detection 54 Figure 3.14: Our system can be fully configured. The contract status, the region and the tariff of the customer can be set before starting the process, allowing dozens of different configurations, generating successful tailored campaigns. 3.4.3 New Features The evolution of our NTL detection system made us evolve and adapted the features to flexibilize them and facilitate the optimal profile of different types of customers. These are the main changes in comparison to the features explained in Table 3.1: •Contract Status: To represent customer behavior in accordance with the contract status (active contract or not), we included more consumptionrelated features for the customers with contract. For the customers without an active contract, as they do not have a recent consumption record, we only included a reduced number of consumption features that focused on their consumption behavior just before they cancelled the contract (with the aim of detecting abnormal behaviors). •Flexible Features: Instead of delimiting the features to a closed meaning e.g., considering that the abrupt decrease of consumption (the abrupt decrease in consumption are a family of features that aims to detect consumption drops in consecutive months.) feature consists of a binary value indicating a reduction of X%, we opted to include as much raw information as possible, e.g., in the previous example, including the raw value of the ratio between the consumption of the last two consecutive months (i.e., representing this behavior with a continuous value). This would give the algorithm more flexibility than using static binary features, guaranteeing that: –The continuous value provides a richer representation of the ratio of consumptions in comparison to a binary feature and, therefore, the partition process from the Decision Tree would be better. –A richer representation of the reality also provides the system with other information that simple binary features cannot. For instance, it could be true that in certain segmentations, a high Preliminaries in Non-Technical Losses Detection 55 increase of consumption in two consecutive periods of time would be an abnormal behavior too. The continuous feature can provide this information to the system. –The flexibility would help the system to be successful over time, even though the consumption patterns from the customer change. This can be exemplified with what we regard as low consumption; in the future, apartments will be more energy efficient, thus what we consider now a low consumption in the future could be the average consumption and, for this reason, including raw information of the consumption instead of binary information (e.g., the customer has consumed less than 2000 KWh in the last 12 months) will make the system more future-proof. In Figure 3.15 there is a visual example that explains the flexibility desired in our system. •Different versions: to boost the information given to the algorithm, different versions of the same concept are provided to the algorithm. This will allow more flexibility for deciding which feature can give the maximum information during the training (e.g., there are several abrupt decreases in consumption features, with different nuances; depending on when that consumption drop happened, how many months are considered in the consumption decrease, etc.). •We also reduced the number of features used in the system to avoid overfitting. •Categorical Features: we exploited the categorical information available from the company’s database. Preliminaries in Non-Technical Losses Detection 56 Figure 3.15: Providing to the system the ratio between the consumption of two consecutive periods of time (i.e., 0.07 for customer 1, 0.023 for customer 2 and 1.3 for customer 3) instead of a binary feature such as ”during the second period the customer consumes lower than 10% of the consumption in the previous period” gives more information and flexibility to the system. The system can determine the proper split in the training stage, and moreover we provide extra information (e.g., that customer 3 is consuming more in the second period, something that would require an extra feature if we used the binary feature). Despite these changes, the basis of the variables is the same: to generate a set of consumption variables that can represent the anomalous consumption typical of fraud, and a set of complementary variables (the static, visiting and sociological variables) that complement and contextualize the consumption variables. Figure 3.16: Some examples of different consumption behaviors. The features need to provide enough information to extract as much information as possible from these profiles: Long periods of low consumption (customer 2), abrupt decrease of consumption (customer 1), similar consumption behavior to the expected consumption curve (Normal customer) or an abnormal consumption curve (Customer 3). Preliminaries in Non-Technical Losses Detection 57 3.4.4 Algorithm and Metrics To simplify our system, we went from combining different algorithms at the same time to using only a Gradient Boosting Decision Tree (GBDT) model. This decision was multifactorial, being the optimal decision if we analyzed the situation in terms of accuracy, simplicity, flexibility, transparency, execution time and available resources. In terms of accuracy, GBDT algorithms are the state-of-the-art solutions when working with tabular data. Moreover, these good results can be achieved efficiently: modern GBDT implementations require less computational resources than other solutions, scale well, and do not require deep preprocessing to obtain optimal results (e.g., XGBoost allows empty values, as well as LightGBM and Catboost allow categorical values). All of this simplified the automatic generation of campaigns, making it easier for us to generate campaigns quickly in various domains. Moreover, as we analyze in further chapters, there exist fast and accurate methods to achieve robust explanations in tree models. The alternatives considered were the Support Vector Machine and Neural Networks. The former was rapidly discarded because of computation time rations (it is much slower than GBDT, especially if a non-linear kernel is used in the SVM). The latter was also considered (especially due to its popularity) but discarded for many reason. First, deep learning is also slower than GBDT (and the lack of GPU capabilities in the company’s servers made this slowness insurmountable). This is especially true considering that deep learning does not provide high performance out-of-the-box, requiring deep parameterization (i.e., unique configuration of layers, connection and activation of neurons per campaign generated). Furthermore, the theoretical superiority of deep learning in terms of accuracy in text and image classification problems is not seen in tabular data, where GBDT models achieve (at least) on par accuracy, with much less effort. This is analyzed in this recent paper [126]. Regarding the metrics used to evaluate our system, we started using the f-score, but then we considered the use of the ROC-AUC score to avoid the use of thresholds, since the company usually considered the order of the customer instead of the score itself to build the campaign (i.e., the company included the top-k customers in a campaign instead of including the customers with scores higher than a threshold). Finally, we used the PR-AUC instead of the ROC-AUC score since it provides more robust results with an imbalanced dataset, as explained in Section 2.1.2. 3.4.5 More Results The modifications explained in this section helped us to generalize the use of the system, making it flexible to detect NTL cases for different customers. We exemplify this success with two specific campaigns, the 36% of accuracy in customers with no consumption and the campaigns Preliminaries in Non-Technical Losses Detection 58 generated to detect NTL cases in customers with no contract. Customers with no Consumption After several years of generating campaigns, the company shared with us their concerns about the customers with no consumption. After the installation of smart meters, they considered that many of the customers with no consumption (i.e., with no difference according to the difference between meter readings) would decrease. However, it was increasing month after month. To solve this problem, they started to create rule-based campaigns to control this type of customer. For instance, to visit those customers that according to the company had both electricity and gas, but the consumption of gas did not match the electricity consumption. In general, we considered the approach taken by the company to be excellent, visiting those customers with very abnormal behavior, but the results were bad. In part, the poor results could be explained by the centralizing power that Madrid has for the inhabitants of the Castilian territories: many people are compelled to live in Madrid and therefore there are many cities and towns in Castilla la Mancha and Castilla y Leon with descending populations and, therefore, the number of empty houses and apartments is increasing in these regions. For this reason, they asked us to fit our system to detect NTL cases in this specific type of customers. The campaign generated was trained by using as labelled instances those customers that would be defined as customers with long periods of no consumption, i.e., customers that had 0 or close to 0 (up to 10kWh) in at least the last 7 months. The campaign was conducted in 4 regions, where the best campaign achieved up to 36% of precision, and the least accurate achieved a precision close to 10%. Customers with no Contract The company used to generate fairly successful rule-based campaigns for the customers with no contract, especially those that were recidivist, i.e., power supply points with constant fraud (e.g., houses occupied by sqatters). In spite of the good results, we adapted the NTL detection system to generate campaigns for the customers with no contract. Our system has achieved several times campaigns with a precision higher than 50%. Moreover, we generated campaigns to detect NTL cases for large customers (e.g., industries), recovering a large amount of energy. 3.5 Overall Analysis of the Classification Supervised Approach The supervised approach to solve the NTL detection problem was successful in general, but had different problems that needed to be tackled. Below we set out these problems, all of them related to each other. Preliminaries in Non-Technical Losses Detection 59 Lack of Robustness Our system achieved high prediction in NTL cases, but lacked in robustness. For instance, in many cases the results in distinct but very similar campaigns were very different (e.g. precision of 20% and 2%). In part, this could be exemplified in table 3.3, where we analyze the results of the system in a test dataset using 4 different metrics: the precision, the F1-Score, the AUC-ROC score and the Average Precision Score in one dataset. As we can see, if we focus on the results in precision, the results are excellent. However, benchmarking only provide a biased vision of our system: The results in F1-Score, and Average Precision determine that our system might not generalize as desired. DOMAIN ACCURACY F1-SCORE PRECISION Domain DAN 0.98 0.58 0.64 Table 3.3: Results from a test in a labelled dataset, with an 80% training - 10% validation - 10% test distribution. The results in the table, which correspond to the results in the test, indicate a priori a good benchmarking (especially in terms of precision), but the low performance in terms of F1- Score and Average Precision indicate that our system is not robust enough. Our efforts to increase the robustness by increasing the regularization to reduce the overfitting or the introduction of new labelled instances to improve the representativity of the labelled instances did not improve the overall robustness. Amount of Energy Recovered In table 4.1 and Figure 3.17 we show another side of our system’s lack of robustness: the system learn patterns to detect NTL cases with low energy recovered. In general, patterns that might be good to achieve good results in training/validation tests do not properly generalize in real scenarios. DOMAINDAN energy528 energy211 energy106 energy42 Reference 1112625 798198.3 582480.8 366088.1 Classification 434531 196407 97659 37838 DOMAIN DAN NDCG NDCG528 NDCG211 NDCG106 NDCG42 Classification 0.52 0.25 0.16 0.11 0.07 DOMAIN DAN median528 median211 median106 median42 Reference 1324 2704 4131.5 6884 Classification 692 782.5 735 610 Table 3.4: A comparison between a perfect model and the classification model in terms of energyn(i.e., amount of kWh recovered in each threshold n). As we can see in the results, we recover a low amount of energy, an indicator that we might not be learning the optimal patterns that represent the NTL. Preliminaries in Non-Technical Losses Detection 60 0 100 200 300 400 500 600 Position 0 2000 4000 6000 8000 10000 12000 14000 16000 Energy Recovered Energy Distribution (top 600 customers, classification model) >3500kHw recovered >2000kHw recovered >500kHw recovered >0kHw recovered no NTL Figure 3.17: Results from a test in a labelled dataset, with an 80% training - 10% validation - 10% test distribution. The model correctly predicts the NTL cases, but as exemplified in table 4.1, we are detecting NTL cases with a low amount of energy to recover. Interpretability and Bias Detection Our approach to validate the features built in our system was, in the first place, to analyze the odd-ratio of the features (see Table 3.5 from [30]). VARIABLES ORPG ORPN Abrupt decrease of consumption 18.6 3.4 Long period of low consumption 6.2 3.0 High consumption discrepancy 10.4 2.4 High range higher lower consumption 12.2 2.0 Gas consumption without electricity 11 2.9 Table 3.5: Significant odds-ratio of some features from the electricity campaigns. Both the odds-ratio between the fraudulent and non-fraudulent customers (ORPN) and the odds-ratio between the fraudulent customers and the customers not part of any campaign (ORPG) are included. However, this approach is poor, since it only analyzes the values of the features (helping to detect, for instance, biases in the labelled instances), but does not analyze their influence on the system. Therefore, it is difficult to understand the lack of robustness and energy recovered problems when the patterns learnt by the model are not easily intepretable. 3.6 Discussion This chapter explains our first approach to the NTL detection problem using data science techniques, being the basis for the future chapters of Preliminaries in Non-Technical Losses Detection 61 this part of the thesis. The proposal is very similar to others existing approaches in the literature (i.e., a supervised classification method that predicts using a black-box algorithm), achieving good results. However, in contrast with other works, we offer a critical analysis of our work. In Section 3.5 we explain the existing problems of our system: the lack of robustness, the low amount of energy recovered per NTL detected, and the lack of interpretability. These challenges are analysed and mitigated in the following chapter. Chapter 4 A Regression Approach to NTL Detection 4.1 System Goals and Challenges The system explained in pevious Chapter 3has been successful as an NTL detection system. Nevertheless, several problems were detected, as we discussed at the end of the Chapter (Section 3.5). Here we provide a more extensive and ordered explanation of the existing challenges. Technical Challenges In general, our system has achieved good results, especially considering that it is implemented in a European region with a very low ratio of NTL cases. However, the robustness of our system campaigns varied depending on the type of campaign. For instance, our system is accurate in certain types of campaigns where the type of customer was predefined (e.g. customers with no current contract1, or customers with long periods of no consumption2). However, in more generic campaigns (i.e. campaigns that included hundreds of thousands of customers) the system underperforms in robustness, i.e. the system cannot consistently provide good results. According to our experience and knowledge, two fronts explain these problems: the existing biases in the labelled instances available from the company and the difficulty of properly benchmarking a model using a validation dataset. 1Customers with no contract refers to the customers that had a contract in the past, but the contract is currently cancelled. In many cases, these customers maintain the wire and meter installation and, therefore, can commit fraud. Our system has achieved many campaigns of around 50% of precision. 2As people in Spain move to cities, many villages become empty. This is a problem for the company as they do not know how to differentiate a house without consumption because it is a second home with punctual consumption or a fraudulent client. Our system was able to detect NTL cases for these types of customers with a precision of up to 36%. 62 A Regression Approach to NTL Detection 69 for houses and apartments in Spain, and tariff 2, an equivalent tariff to 1 but with hour price discrimination. The regions are anonymous to protect the privacy of the data. 6). The customers must have less than 10kwh of Contracted Power to be on these tariffs. The domain DA1(i.e. the customers from region Aand tariff 1) has more than 1000000 customers, and domain DB2has less than 50000 customers. The other two datasets fall between these two datasets in terms of population. The proportion of the NTL cases in each domain is lower than 5%. We have around 300000 labelled instances for the DA1domain, several thousand cases for DA2and DB1, and several hundred cases for DB2. Model For the classification and the regression predictions, we have trained two different CatBoost models. Each model is trained using the same 80% of the positive instances and 80% of the negative instances. We split in half 20% of instances left, keeping the positive/negative ratio, to build the validation dataset (i.e. the data used to tune the model), and the test dataset (i.e., the training, the validation and the test dataset are stratified). The random partition is chosen over considering the timestamp (e.g. the last 10% of NTL cases as the test dataset) to guarantee diversity and reduce the differences between the datasets due to company decisions. To avoid overfitting, the metric used for early stopping to establish the optimal number of trees is the Average Precision Score for the classification model and the RMSE for the regression model. Both models use the same customer profile, with the only difference that for the classification approach we use a binary target (NTL/non-NTL), while in the regression approach we use the amount of energy to recover (information that is provided by the technician when an NTL is detected). Benchmarking A good benchmarking metric to use if we aim at recovering more energy in our campaigns is the Normalized Discounted Cumulative Gain (NCDGn) [70]. It is a measure of ranking quality that evaluates our output’s correctness with a value between 0 and 1 (1 being the perfect order of the NTL cases, and 0 otherwise). This metric allows us a global vision of the correctness of the predictions made, without considering one specific threshold (i.e. the top 100 customers): in many cases, the number of customers to be included in a campaign is unknown when the campaign is being built. The NCDGnis defined as NDCGn=DCGn IDCGn 6A tariff with price discrimination involves charging a different price for the electricity depending on when the electricity is consumed. More specifically, electricity would be cheaper at night but more expensive during the day. The potential customer of this tariff is the customer that has an electric car and charges it at night. A Regression Approach to NTL Detection 70 where DCGnis defined as DCGn= n P i=1 Reli−1 log2(i+ 1) Relibeing the relevance (i.e. the score in the ranking, in our case the amount of energy recovered), and IDCGn, i.e. the ideal DCG, corresponds to a perfect ordered DCG for the top nelements of the list. In addition to the NDCGnmetric, we use the amount of energy recovered from the top nscored customers to compare approaches. In both cases we provide four different results (i.e. four different nthreshold values): n= (NTL cases in test)/2, n= (NTL cases in test)/5, n= (NTL cases in test)/10 and n= (NTL cases in test)/25; each threshold aims to represent different types of campaigns: from very small campaigns where just a few customers are visited to big campaigns where hundreds of customers are included in the campaign. Benchmarking Results In Table 4.1 we report the comparison, in terms of energy recovered and NDCG metrics, for the regression and classification approach in the four datasets (for each nthreshold). In terms of NDCG, the regression models always score better than the classification models, meaning that the regression approach is able to order better the test customers according to its consumption. Therefore, we recover more energy at the very top of the list, confirming in terms of benchmarking its superiority over the classification approach. This superiority is especially true for small campaigns,where the NDCG value for the classification approach is extremely low. In terms of energy recovered, the regression approach is superior to the classification approach; the amount of energy recovered in our results is usually higher than the energy recovered with the classification models, especially for small-sized campaigns. Recovering more energy is the desired outcome: accumulating very high NTL cases at the very top of the list would allow the company to generate more fruitful campaigns. With large or medium-sized campaigns, the benefits in terms of NDCG and energy recovered of the regression approach is not as clear as in smallsized campaigns, as we can see in Figure 4.3: the regression model ranks higher the high-NTL cases (i.e. the NTL cases in which more energy can be recovered, in purple and in red) in comparison to the classification model, but then this advantage fades slightly, and the energy recovered by both approaches becomes more similar. A Regression Approach to NTL Detection 71 Energy recovered from an n-sized campaign (kWh) Domain DAN n= 528 n= 211 n= 106 n= 42 Reference 1112625 798198.3 582480.8 366088.1 Classification 434531 196407 97659 37838 Regression 468496 (+7%) 267121 (+36%) 164814 (+69%) 73092 (+93%) Domain DAD n= 186 n= 74 n= 37 n= 15 Reference 362877.4 273622.2 204201.6 139045.6 Classification 164509 68391 39941 8704 Regression 151844 (-8%) 96520 (+41%) 70022 (+75%) 54988 (+532%) Domain DBN n= 79 n= 31 n= 16 n= 6 Reference 146245.7 102029.7 75141.3 46690.3 Classification 50596 22164 10079 3542 Regression 67163.9 (+33%) 25764.2 (+16%) 15148.2 (+50%) 12595.2 (+256%) Domain DBD n= 19 n= 7 n= 4 n= 1 Reference 46482.3 31957.3 22607.3 7555 Classification 16799 7472 5975 2691 Regression 14036 (-16%) 11370 (+52%) 8679 (+45%) 5484 (+104%) Ranking quality from an n-sized campaign (NDCG) Domain DAN NDCG NDCG528 NDCG211 NDCG106 NDCG42 Classification 0.52 0.25 0.16 0.11 0.07 Regression 0.57 0.32 0.26 0.23 0.18 Domain DAD NDCG NDCG186 NDCG74 NDCG37 NDCG15 Classification 0.43 0.25 0.15 0.11 0.05 Regression 0.65 0.46 0.44 0.45 0.49 Domain DBN NDCG NDCG79 NDCG31 NDCG16 NDCG6 Classification 0.45 0.22 0.15 0.11 0.08 Regression 0.47 0.29 0.19 0.16 0.17 Domain DBD NDCG NDCG19 NDCG7NDCG4NDCG1 Classification 0.47 0.30 0.24 0.25 0.36 Regression 0.59 0.39 0.43 0.46 0.73 Table 4.1: The table at the top compares classification and regression in terms of energy recovered (i.e. the kWh recovered in each threshold n). As we can see in the results, the regression approach can recover more energy than classification in most cases. In several cases, the amount of energy recovered is significantly greater, especially when the nthreshold is small. This means more efficient campaigns in economic terms. The table at the bottom provides a similar analysis, comparing the campaigns in terms of NDCGn. In this analysis, the regression results always outperform classification results in ranking performance (i.e. sorting the customers according to their NTL). 4.3 Analysing NTL Detection Beyond Benchmarking A Regression Approach to NTL Detection 72 0 100 200 300 400 500 600 Score Position 0 2000 4000 6000 8000 10000 12000 14000 16000 Energy Recovered (kWh) Energy Recovered (top 600 customers, classification model) >3500kHw recovered >2000kHw recovered >500kHw recovered >0kHw recovered no NTL 0 100 200 300 400 500 600 Score Position 0 2000 4000 6000 8000 10000 12000 14000 16000 Energy Recovered (kWh) Energy Recovered (top 600 customers, regression model) >3500kHw recovered >2000kHw recovered >500kHw recovered >0kHw recovered no NTL Figure 4.3: The results obtained in Table 4.1 are confirmed in these images: the regression model recovers more energy at the very top of the test prediction list. More specifically, we can see how the purple cases (NTL cases with more than 3500kWh, the average customer’s energy consumption per year) in the regression model are recovered at the very top of the rank. 4.3.1 Classification vs. Regression in Terms of Explainability The results from Section 4.2.2 suggest that the regression models recover more energy than classification. However, as explained in Section 4.1, we are not confident with only benchmarking our models: increasing the accuracy in validation sets that are subsamples of biased labelled instances does not guarantee that the system is fair (i.e. the system is unbiased against a particular type of customers, e.g. customers from poorer regions), A Regression Approach to NTL Detection 73 and robust (the system will perform as expected in reality, learning causal patterns, with no data leakage [72] nor dataset-shift [105]). The regression approach should be humanly validated as a better method (e.g. learn better patterns) than the classification approach. The purpose of this section is to illustrate this through explanatory algorithms. The first explanatory algorithm tested in our system was the Feature Importance method. This approach was useful for us to detect biases (e.g. by detecting features that were not indicators of NTL but were too important in the model), but only provided a global vision of the model, with no possibility of analyzing the importance of the features on specific customers with a high score. For this reason we explored the use of LIME to explain our predictions at instance level. As we explain in [31], we were able to implement a rule-based double-checking method in campaigns to discard customers for whom, despite a high score, the explanation obtained from LIME was undesired (e.g. the patterns explained by the local model would not be validated by a human expert). Despite the good results we did not implement LIME as our explanatory algorithm due to the wellknown problems of robustness (e.g. [7]) because of the random component of the algorithm but also the difficulty of having an optimal configuration. After these two initial unsatisfactory approaches, we started to use SHAP (more specifically, the tree SHAP implementation [81] to obtain the Shapley values from Tree Models). According to our experience, the tree SHAP was the optimal approach to obtain an explanation from a Tree Model because of the following advantages summarized below: •Consistent global and local explanations: SHAP provides like LIME local explanations but also a consistent global explanation like Feature Importance, since the Shapley values of each instance are the ”atomic unit” of the global interpretations. Moreover, it maintains the feature dependence from the model trained. •Robustness: SHAP always provides the same explanation for the same Tree Model, in contrast with LIME that includes randomness that makes the whole approach look unreliable. •Reliability: The explanations obtained using SHAP are based on a solid theory and distribute the effects fairly based on the analysis of the original model trained. On the other hand, LIME surrogates the original model and, therefore, it can use features in the local interpretable model not used in the original model. •Informativeness: The explanation from SHAP provides a very extensive explanation of how the model learnt, allowing the stakeholder and the scientist to be properly informed to support their decisions. •Low computational cost: Although the computational cost of the A Regression Approach to NTL Detection 74 Shapley values are very high7, the computational cost for the tree SHAP is low (i.e., O(TLD2), T being the number of trees of the ensemble model, L the maximum number of leaves in any tree and D the maximal depth of any tree). In the next section we will analyze both classification and regression from the Shapley values’ perspective for the case of NTL detection. In the following Chapter 5we offer a more in-depth analysis of each of the explanatory approaches used in this thesis. 4.3.2 Experiments: Classification vs. Regression Explainability in Real Data Preliminaries Data, Classification and Regression Algorithms For the experiments of this section, we use the classification and regression model from subsection 4.2.2 for the DA1domain. Similar conclusions can be drawn for the rest of the domains. Shapley Values and Interpretability To analyze the goodness of our model, we use the summary plot method from SHAP. This method provides two plots for our type of problem (i.e., tabular data): a bar chart that represents the mean of each Shapley value of each feature, and a more complex plot that indicates how each value influenced (i.e., increased or decreased the prediction made from the base value). Both plots can be seen in Figure 4.4, applied on the classification approach. Regarding the second plot, in red there are the higher values of the features and, in blue, the lower values. When the feature is categorical there is no color scale and all the dots are gray. For example, in Figure 4.4 we can see that, on average, Current Reading Absences is the variable that contributes the most to the prediction, increasing the prediction when the value is high (i.e. the customer has had reading absences). In contrast, when there is no reading absences (i.e. Current Reading Absences = 0, in blue), the Shapley value is 0 or negative. It is necessary to remark that when Shapley values correspond to the regression model, they can be read directly as the apportion to the standard output. In contrast, in the binary classification the Shapley value corresponds to the log odds ratio8. Moreover, it is necessary to clarify that the red/blue feature value representation is not valid for categorical features. In these cases, SHAP plots the dots in grey. Hence, Shapley 7The Kernel SHAP cost is O(T L2M) in tree models, being Mthe number of features, T the number of trees and L the maximum number of leaves. 8That is, xbeing the sum of the base value and the Shapley values from an instance, we would obtain the probability between 0 and 1 by doing 1/(1+exp(-x)). A Regression Approach to NTL Detection 75 values on regression have the additional characteristic of being simpler to interpret. Considerations Regarding Subjectivity in the Analysis As it is widely analyzed in the literature, the supervised methods only detect correlations, hence human supervision is necessary to validate them as reliable causal patterns (or, at least, reliable correlation in the company’s context). For this reason, the following model comparison from Section 4.3.2 requires a human analysis of the Shapley values and therefore includes subjective considerations. In general, a reliable pattern would consist of a correlation between a feature value xiand the prediction ˆythat a stakeholder would trust. For instance, the stakeholders could easily validate patterns indicating that the customer is consuming less than expected based on their previous consumption or in comparison to other similar customers. A doubtful or questionable pattern would consist of those patterns that either cannot be easily validated by the stakeholders or whose interpretation is counter-intuitive (e.g. a correlation between a long period of average consumption and a high NTL score). All these considerations are properly explained, in the following analysis, based on our experience in campaigns. In any case, we provide a fairly generic analysis that fits in most domains similar to the one used in this experiment. We try to avoid very complex analyses that could require information from the company (e.g. the historical NTL cases in specific towns) that cannot be disclosed. Features Referenced in the Experiments The features referred to in this section are described in Table 4.2. For each model, we analyze in depth 8 features to ensure the readability of the document. However, we also provide a more generic description of the model that includes more information beyond the 8 features at the end of the analysis. Evaluation Analysis through Explainability According to Figure 4.4 and our interaction with the company’s technicians, we cannot trust the classification model since there is only one consumption-related feature in the top eight most important features (the Min/Max bill last 12 Months, a feature that refers to the ratio between the minimum and maximum consumption bill in the last year). Instead, many of the features are visit related (features that, as exemplified in Figure 4.2, can be useful but can also produce bias and other learning problems). For a deeper analysis we can analyze the effect of each value on the output with the bottom plot from Figure 4.4: •Reliable patterns: In the classification model, several patterns can be easily confirmed as true indicators of NTL: A Regression Approach to NTL Detection 76 FEATURE DEFINITION Current Reading Absences After the installation of smart meters the company can remotely communicate with the meters. The absence of the meter readings can indicate either an incident in the meter (e.g. that it stopped working) or fraudulent manipulation. This feature indicates how many months have passed since the last meter reading. Last Visit: Correct/Fraud Categorical information that indicates if the last visit done to that customer has been correct or an NTL has been detected. If the customer has not received any visit, the feature’s value is empty. Town The town where the customer lives. # Meters in Property How many meters the customer has in property. In general, the meter is owned by the company, and is rented/handed over to the customer. Date Last Reading How many months have passed since the last meter reading. Last ’No Fraud’ Visit How many months have passed since the last time the customer was visited with a visit whose aim was not to detect fraud, i.e. the installation might not actually be checked during the installation. Min/Max Bill Last 12 Months The ratio between the minimum and maximum bill during the last 12 months. Contracted Power The contracted power by the customer. In general, it is expected that a customer with a high consumption needs a higher contracted power. Cons. Zone/Cons. Last Year Ratio between the consumption of the customer and the average in the zone from the same type of customers. A zone is an internal reference that refers to a group of customers that receive the electricity from the same point of supply. Therefore all the customers in the zone are very similar and have similar energy needs. Last Bill Last Bill in kWh. Diff Consumption 6 Months The difference in terms of kWh between two equivalent periods of time (i.e. the same six consecutive months) in consecutive years. A higher value indicates that the customer has had a consumption reduction. # Months with No Consumption Consecutive months with no consumption until the present. Consumption Penultimate Year Consumption of the customer in the penultimate year (i.e. from 24 to 12 months ago). Table 4.2: Features referred to in the experiments with their descriptions. 1. Current Reading Absences: This feature is the most important feature for the model (according to SHAP). This is a very reliable pattern learnt because the company expects to have, after the introduction of smart meters, information from the meter on an ongoing basis, including meter readings. The lack of meter readings is for sure a very suspicious behaviour since it may indicate meter manipulation. 2. Contracted Power: According to the Shapley values there is a correlation between a higher contracted power and a higher probability of committing NTL. This pattern can be a bias since the company usually tends to include customers with higher Contracted Power in the campaigns. However, the company A Regression Approach to NTL Detection 77 0.00 0.05 0.10 0.15 0.20 0.25 0.30 mean(|SHAP value|) Contracted Power Min/Max Bill Last 12 Months Last 'No Fraud' Visit Date Last Reading # Meters in Property Town Last Visit: Correct/Fraud Current Reading Absences Classification Model (NTL/non-NTL) 012345 SHAP value Contracted Power Min/Max Bill Last 12 Months Last 'No Fraud' Visit Date Last Reading # Meters in Property Town Last Visit: Correct/Fraud Current Reading Absences Classification Model (NTL/non-NTL) Low High Feature value Figure 4.4: SHAP explanation of the classification approach: there is only one consumption-related feature on the top 8 most important features. Moreover, how each feature influenced in the score assignation is not easy to interpret: only the Current Reading Absences can be fully trusted as a good pattern and, for this reason, we cannot validate the model as a good and robust model. validated this pattern based on their experience. 3. Min/Max Bill Last 12 Months: We can see that, in general, the model considers a lower value more related to NTL behaviour. We consider this pattern valid because, in general, we expect that monthly consumption will not vary in a very marked way A Regression Approach to NTL Detection 78 during the year. If this occurs, it may be a consequence of meter tampering. •Categorical information Two categorical features (with no colour scale in Fig. 4.4 bottom) are very relevant in our system, as we explain as follows: 1. Last Visit: Correct/Fraud: This information is valuable since the patterns learnt should be contextualised to the visits carried out by the company. That is, a customer that committed Fraud in the past is, according to the company, very likely to commit fraud in the future. 2. Town: The town where the customer lives can be a good indicator for the NTL detection system. Statistically, there are towns in which the company has always detected more NTL cases than in other towns. •Unknown interpretability The interpretation of how a feature value influences the output can be hard to understand for the classification approach. Several examples are given below: 1. # Meters in Property: When a customer owns a meter, it is more likely to be in an inaccessible location. Therefore, it would be easier for the customer to manipulate it. Moreover, having more than one meter increases the possibilities of having an NTL. Therefore, one would expect that a high feature value would correspond to a high Shapley value. However, a high value in this feature influences unevenly on the output. With this information the stakeholder might not draw conclusions about the feature role in the prediction or its correctness. 2. Last ’No Fraud’ Visit Several interpretations can be expected for this feature. For instance, a recent visit combined with a high electricity consumption can confirm that a customer is not committing NTL, but also a recent visit to a customer that is consuming less than expected can be suspicious. The lack of context harness the interpretation of the feature by the stakeholder. •Questionable pattern Finally, there is a pattern learnt from a feature that the stakeholder cannot validate: 1. Date Last Reading According to the SHAP value, low values (i.e. the last meter reading is recent) is more related to the NTL behavior. At first glance, this pattern is unintuitive since we would expect a similar pattern to the one learnt from the Current Reading Absences: a recent reading would indicate that the meter is working as expected. A possible explanation for this Chapter 5 Introducing the Human Perspective 5.1 What is my System Learning? Our first approach to building the NTL detection system (Chapter 3) achieved good results, but lacked robustness and transparency. For this reason, we started to analyse in depth what our model was learning through statistical methods such as explanatory algorithms. The initial result of this analysis can be seen in Chapter 4, where through Shapley values we were able to better understand what our model was learning at a modular and local level, and we were able to propose key improvements in our system, such as the use of recovered energy as a variable to be predicted instead of using the binary information NTL/non-TNL. However, we do not provide details regarding why we use Shapley values instead of other existing alternatives in the literature. This chapter details our experience of providing the desired transparency in our NTL detection system. We explain how we started to use simple statistical analysis (i.e., odds-ratio, Pearson Correlation and Feature Distribution), then how we used the feature importance implementation from the ensemble tree methods, to finally using state-of-the-art explainability methods like LIME (for tabular data) and SHAP (tree explainer). Finally, we compare each approach in our context1, concluding that we consider Shapley values the best approach in our context and, in many cases, the best approach seen in the literature to provide explainability in an industrial project. The analysis and tests carried out in this chapter include several conclusions already referred to previously in Chapters 3and 4. For instance, 1The labelled information used in this analysis corresponds to the dataset used in [30], a rich dataset with almost three hundred three thousand labelled instances, containing 3.3% of NTL cases. The model Mused to make the predictions is a CatBoost regression model tuned through a training-validation process. 85 Introducing the Human Perspective 86 the models used to compare the explanations from the explanatory algorithms are regressive, since as we explained in Chapter 4the regression approach gives us better results than the classification one. Features Definition Last Impossible 2 Indicates the number of months since the last time the company could not perform a visit. The suffix 2 indicates that the original purpose of the visit was not to detect an NTL case, but to implement another technical visit. # Impossible 2 Number of times the company could not perform a visit to the labelled customer. The purpose of the visit was not to detect NTL. # Correct 2 Number of “no Fraud” visits to the customer with result of “no NTL detected”. Last Impossible Number of elapsed months since the last time the company could not perform a visit. We compute both the visits to detect NTL cases but also the other visits (referred in this analysis, as explained before, with the suffix 2). Current Reading Absences Number of months since the last meter reading. Power Contracted The power contracted by the customer. Town Town where the customer lives. # Visits 2 Number of “no Fraud” visits made to customer. We do not consider the results of the visit, but if the customer has been historically ”controlled” by the company. SCC12MP Similarity (consumption curve, 12 months) between the customer and similar customers. We compute the average consumption per month of the customers from the same province and Tariff, normalize the consumption curve, and compute how similar this normalized consumption curve is to the normalized consumption curve of the customer. A low value would indicate that the consumption is similar to the expected consumption curve, while a very high value indicates that there is no similarity (i.e., an indicator of NTL). SCC12M Similarity (consumption curve, 12 months) between the customer and similar customers. This variable is computed as explained in SCC12MP, but the comparison is done with all the customers included in the campaign. Con.Penultimate Year Consumption of the customer during the penultimate year. This information might not provide meaningful data, but it is useful to understand the historical consumption behaviour of the customer and, therefore, can nuance the meaning of consumption behaviours at the present time. Last Bill Amount of energy billed to the customer in the last bill. Last Fraud 2 Number of months since the last time the company performed a “no Fraud” visit with an NTL result. Con.Drop 24-6M Abs Absolute consumption difference (i.e., kWh) between two consecutive 6 month periods. It is checked for the last 24 months. Last Threat Number of months since the last time the customer threatened a technician from the company preventing the meter’s technical service. #Threat Number of times the customer threatened a technician from the company preventing the meter’s technical service. Energy Cut Number of times the company cut the energy supply to the customer. Fraud Building 1Y Number of times an NTL has been found in the customer’s building during the last year. This information is interesting since neighbors can share information about how to commit fraud. #Gas Fraud Number of times the customer has had NTL cases in gas. Con.Last Year/- CLY Zone Ratio between the customer’s consumption and the average consumption in the region (last 12 months). This information is straightforward, i.e., a much lower consumption should be an indicator of NTL. Con.Low 24-6M. Ratio between the customer’s consumption and the average consumption of similar customers (i.e., customers from the same region and Tariff). The period of time considered is the last 24 months, and the consumption window is 6 months. Con. Customer/- Con. Cust. 24M Ratio between the customer’s consumption and the average consumption in the region (last 24 months). Median Bill 12M Median Bill of the customer for the last 12 months. Table 5.1: Brief description of the features referred to in this chapter. Introducing the Human Perspective 87 5.2 Our Experience Using Explanatory Algorithms 5.2.1 The Starting Point: Statistical Analysis Our first approach to understanding our predictive models was to analyse the training dataset statistically. The statistics measures referred to in this work are the following: Feature Distribution The distribution of the values of each feature in different domains and segments might indicate patterns and other interesting characteristics to analyse. For instance, this simple analysis might provide a small intuition on why, in certain regions, the company has been more successful in detecting NTL cases. Pearson Correlation A measure of the linear correlation between two features, where 1 indicates a perfect positive correlation (i.e., for every increase in one feature, there is a positive increase of a fixed proportion in the other feature), and -1 indicates a perfect negative correlation (i.e., for every increase in one feature, there is a decrease of a fixed proportion in the other feature), where 0 indicates no linear relationship. The coefficient (r) is defined as the ratio between the covariance Cov of the values of two features divided by the product of their standard deviation S, i.e.: −1≤rXY =Cov(X, Y ) SXSY ≤1 (5.1) There exist in the literature examples of using the Pearson Correlation Coefficient to detect NTL. For instance, in [88], the Pearson Correlation coefficient is used to detect an abrupt and gradual but constant decrease of consumption in customers, hence suspicious of NTL. Thus, the Pearson Correlation can be used to detect patterns in our data useful in understanding NTL behaviors. Odds-Ratio The Odds-Ratio OR statistic is usually used in medical reports (as explained in [16]). It quantifies the influence of a binary value on an outcome. In an NTL detection context, let Fxi=1 be the number of NTL instances xwith feature xi= 1, Fxi=0 be the NTL instances xwith feature xi= 0, Cxi=1 be the non-NTL instances xwith feature xi= 1, and Cxi=0 be the non-NTL instances xwith feature xi= 0; then the OR is: OR =Fxi=1/Cxi=1 Fxi=0/Cxi=0 =Fxi=1/Fxi=0 Cxi=1/Cxi=0 .(5.2) Odds-Ratio values far from 1 indicate that customers with xi= 1 and customers with xi= 0 have a different proportion of NTL. These statistical metrics are not often considered explanation methods, but help understand the data used to train the model and, in some cases, are sufficient to detect biases or undesired prediction rules. In part, Introducing the Human Perspective 88 many of the problems explained in Chapter 3were detected using these statistical metrics (for instance, the over-representation of the recidivist customers explained in Chapter 4. Nevertheless, the statistical analysis could not provide satisfactory explanations for how our black-box model made predictions. For this reason, we started to introduce different explanatory approaches in our system to better understand the role of each feature in the prediction process. 5.2.2 Feature Importance The Feature Importance method, as explained in Section 2.3.2, provides a simple modular explanation of how important each feature has been during the training process. In this case, we will analyse the feature importance method in Catboost, more specifically the PredictionV aluesChange method that evaluates how much the prediction changes on average if the value of that feature is changed2. The result of the method is a ranking of features by importance, where importance values are normalized so that their sum equals 100. Figure 5.1 shows the top 10 features3of our Mreference model. This information provides a global picture of the learnt model, since the most important features to detect NTL cases are consumption features (and, to a lesser extent, visit features). Overall, the fact that 8 out of 10 features are related to consumption or visits (and not, for example, to the town where the customer lives) convinces the domain experts that the model focuses on the right information. Hence, using feature importance is helpful as a first sanity check of the model. However, feature importance is insufficient when it comes to analyzing in depth how features influence the prediction. See for instance the most important feature, Last Impossible 2 in Figure 5.1; this feature indicates the last time the company failed to carry out a “No Fraud” visit. A “No Fraud” visit is one whose main aim is not to detect fraud, but some other generic purpose. Yet, the impossibility to perform the visit may hide an abnormal customer behavior (e.g., the customer obstructs the technician’s visit because they know the meter has been tampered with). Although the model has learned this fraudulent pattern, it cannot be confirmed though feature importance, since it only provides a global, fast4explanation of the importance of the features in the model, but does not provide the reason behind a high relevance. Indeed, in the ideal case, a high relevance describes a learned pattern of NTL. But it can also be the result of a bias 2The definition of the P redictionV aluesChange is available in the documentation from Cat- Boost, https://catboost.ai/docs/concepts/fstr.html#fstr regular-feature-importance 3In this section we will only analyze the top n features of each method to facilitate the explanation. 4In our tests with a catboost model with 3056 trees and 605076 instances takes less than 0.05 seconds to compute the Feature Importance. The hardware used in all the tests is an Intel Core i7-8550U CPU, with 16GB of RAM and an SSD disk. Introducing the Human Perspective 89 0 2 4 6 8 10 12 Last Impossible 2 #Correct 2 Last Impossible Curr. Reading Absences Power Contracted Town #Visits 2 SCC12MP Con.Penultimate Year SCC12M Figure 5.1: Top 10 most important features according to the feature importance method from Catboost, i.e., PredictionValuesChange. It evaluates how much the prediction changes if the value of that feature is changed, on average. in the data, or an internal decision of the learning algorithm that is not always justified or understandable by the stakeholder. In this situation, it is necessary to complement the Feature Analysis with, for instance, a statistical analysis. In Table 5.2 we analyze the distribution of the Last Impossible 2 feature. In general, most of the labelled instances are undefined for this feature (i.e., there are no cases of Last Impossible 2), but this proportion is reduced when we focus our analysis on the NTL cases with more than 3500kWh 5recovered (where more than 10% of the cases had a Last Impossible 2), and the ratio is reversed for the very top cases, where 75% of the customers had a value for Last Impossible 2. This pattern should be the one learned by our model. In conclusion, based on our experience, the feature importance methods might not be a proper method to fully understand the patterns learned by the NTL detection model, but can be a good baseline approach to detect clear undesired patterns. 5.2.3 Local Surrogate Models This section discusses an example of the explanations obtained from LIME for tabular data. We fix one particular customer for the remainder of the section 6. This is an NTL case for which a fraud of 3000kWh was 5The consumption of a house or apartment in Spain is, on average, around 3500kWh. Therefore, this figure is informally used in the project as a delimiter of what would be a great NTL case, i.e., an NTL case in which the amount of energy recovered is remarkable. 6The execution time to obtain an instance explanation for LIME is, in our case, around 38 seconds. Introducing the Human Perspective 90 Top Selection Last Impossible 2 undef. Last Impossible 2>=0 3500 to 35000kWh 571 84 >35000kWh 1 3 Customers 295218 7324 Table 5.2: Analysis of the value Last Impossible 2 feature for the NTL labelled customers with recovered energy from 3500kWh to 35000kWh, more than 3500kWh and all the labelled customers. This feature indicates the months passed since the last Last Impossible 2 visit, where the value remains undefined (i.e., the missing values) in case of no visit. The proportion of Last Impossible 2 >= 0 increases for the NTL cases, especially when the energy recovered is high. Figure 5.2: Local Explanation of the NTL case, first run. The top-10 most important features from the LIME explanation of an NTL case with energy recovered of around 3000kWh. The most important features are the Current Reading Absences (i.e., that it has absences in readings) as an indicator of NTL and the Last Impossible 2 feature (i.e., that has a negative value, indicating the absence of Impossible “No Fraud” visits as a non-NTL pattern). reported; our model predicted an amount of energy to recover of around 2100kWh. Note that all features discussed are numerical, since LIME requires re-encoding categorical variables as numerical ones, as explained in the documentation7. This example has been carefully selected because it exemplifies the problems we have had with LIME in our system. Figure 5.2 shows an example of a subset (top-10) of the most important features for that customer according to LIME: the explanation indicates which feature values increase or decrease the specific prediction of 7https://marcotcr.github.io/lime/tutorials/Tutorial%20-%20continuous%20and% 20categorical%20features.html Introducing the Human Perspective 91 Figure 5.3: Local Explanation of the NTL case, second run. The same instance of Figure 5.2 is explained differently by LIME in a second run, due to sampling a different set of neighbours. 2100kWh. The sum of each prediction apportion should be the prediction made by the black-box model in that local region (or at least, a good approximation). However, LIME seems to have a major robustness problem, exemplified in Figures 5.2-5.3. If the LIME algorithm is rerun on the same instance, a different random sample is generated each time to generate the local model, and this leads to different explanations of the same instance. A second issue with LIME, reported elsewhere, is the high sensitivity of the output to the setting of certain parameters, particularly kernel width. For instance, in Figure 5.4 we show the explanation of the same instance of Figure 5.2, but now using a different kernel width value. There is also little theoretical guidance for choosing appropriate values. Finally, there is no guarantee that the explanation that we obtain from the local surrogate model is faithful to what M(x) computes, as shown in Figure 5.3. The #Threats feature indicates if the company’s technician has received threats from the customer when performing an installation or service, and Energy Cut indicates whether energy has been cut off to this user at some point in the past. However, upon closer inspection, these features are not used in M(x) computation. Despite these problems, based on the information provided by LIME, a methodology can be proposed. In [31], we describe an approach for double-checking the predictions made by a model by implementing a rule system. Based on the features that, according to LIME, most influenced the score for each instance, this methodology would determine if the high prediction was trustworthy, discarding as NTL-cases those instances for which, according to human knowledge, a high score is not justified. The accuracy in our tests increased around 13% with this simple heuristic, as Introducing the Human Perspective 92 Figure 5.4: Example of how the kernel width highly influences the explanation process. shown in Table 5.3. Dataset % NTL % Non-NTL % Precision Original Campaign 72 28 72 LIME Campaign 18 3 85 Table 5.3: Results from the tests in [31] where we used LIME as a postprocess method to rule out customers with an unjustifiably high score. 5.2.4 SHAP As explained in subsection 2.1.4, we consider it mandatory to analyze the goodness of a model by analyzing how it has learned to score: if we only focus our analysis by comparing experiment benchmarking in a validation test dataset, we might perceive as good models those that have learned undesired patterns and, therefore, might fail in the real-world scenario. In this work we propose using the SHAP explainer method that, as introduced in Section 4.3, explains how the supervised model predicted ˆ Y. The overall process of how the Shapley values work is explained in Section 2.3.2; here we only include a reminder of how the values are interpreted: 1. The supervised model predicts ˆ Y. 2. Based on these predictions, SHAP extracts the Shapley values, and the base value. •Base Value: The mean of the labelled instances the supervised model used in the training stage. •Shapley Values: Each value of each instance has an associated Shapley value, that corresponds to the influence of said value Introducing the Human Perspective 93 Figure 5.5: Example of the Shapley values for our reference NTL case of 3000kWh. The most important feature for this instance is the Curr. Reading Absences and the Power Contracted. to the final prediction (i.e., if that value pushes the final score, increasing or decreasing it). 3. The final prediction for each instance can be understood as the result of the sum of all the Shapley values of that instance and the Base Value8. We will use the bar chart that represents the median of each Shapley value for each feature and the fuller version of it that indicates how each value influenced (i.e., increased or decreased the prediction made). In this section we analyze the explanations from SHAP for trees (i.e., the Tree Explainer). We use the same reference instance used in the previous section, i.e., the positive NTL customer for which 3000kWh of fraud was reported and for which our model Mpredicted 2100kWh of recoverable energy. Figure 4.4 shows the explanation of SHAP of a subset (top-10) of the most important features for our reference instance. Similar to LIME, SHAP indicates how the feature values increase or decrease the specific prediction of the energy to be recovered. Furthermore, it does not have the robustness problems of LIME since the computation is deterministic and always provides the same explanation for a given model and instance9. In addition, the explanation is consistent with what the model has learned, which was not always the case in LIME as described before with the Energy Cut feature. SHAP for tree-based models [81] is, according to our experience, a very robust and rich method to provide interpretability to our system. To begin with, the fast implementation10 provides local explanations (i.e., instance level, see Figure 5.5) and global explanations (i.e., modular explanations, similar to the feature importance method previously analyzed, see Figure 8It is necessary to remark that SHAP, at least in the XGBoost and Catboost binary models that we have tested, the Shapley values do not correspond to the direct probability but a raw value from the learning process. In our case, to obtain the real probability from the Catboost model, it is necessary to calculate the sigmoid of that value, i.e. 1 1 + exp(−value) 9For the Tree Explainer used in our system. 10 In our case, the system computed the Shapley values in around 260 seconds. We did not use the GPU accelerated version of the Tree Explainer, which for sure would provide an even faster computation but would require an Nvidia GPU. Introducing the Human Perspective 94 0 5 10 15 20 25 mean(|SHAP value|) (average impact on model output magnitude) Avg. Bill 12M Con.Drop 24-6M-2 Abs. Diff Max-Min Bill 12M Con.Drop 24-6M Power Contracted Town Median Bill 12M Last Bill Con.Last Year/CLY Zone Curr. Reading Absences 2000 0 2000 4000 6000 8000 SHAP value (impact on model output) Avg. Bill 12M Con.Drop 24-6M-2 Abs. Diff Max-Min Bill 12M Con.Drop 24-6M Power Contracted Town Median Bill 12M Last Bill Con.Last Year/CLY Zone Curr. Reading Absences Low High Feature value Figure 5.6: Two versions of the summary plot from SHAP: above, a boxplot diagram showing the average of the Shapley values for the most important features (similar to feature importance plots). Below, a distributionlike description (more fine-grained) of the same information. According to SHAP, the most important feature in the model is Curr. Reading Absences. . 5.6). Remarkably, this global explanation is consistent with the local explanations (as explained in [87], ”the Shapley values are the ’atomic unit’ of the global interpretations”), and with the feature dependency of the predictive tree Model. Moreover, the theory of Shapley values [121] guarantees the properties of efficiency (the feature contribution adds up the difference of prediction), symmetry (two features have the same Shapley values if they contributed equally), dummy (a feature that is not used in the prediction model has a Shapley value of 0) and additivity (if the computation of the prediction can be divided into sub-processes, i.e. the boosting process in our model, the Shapley values can be seen as the average of the Shapley Human-in-the-Loop Approach to Improve NTL Detection 101 The NDCG Should not Decrease between Iterations In each iteration, we should not decrease the benchmarking performance on unseen data. Therefore, in each iteration, NDCGn>=NDCGn−11. The Outliers Should be Detected and Processed A Shapley value from a high-scored instance that stands out in comparison to the rest of the Shapley values can be a consequence of an outlier in the prediction labels (more specifically, an NTL case with a much higher value of kWh recovered than the rest of the NTL cases). In this case, the stakeholder should consider transforming the instance that causes the outlier to avoid biases on prediction. The System Should be as Simple as Possible To reduce the complexity of the model to increase generalizability on unseen data but also improve interpretability, we should remove features that have a low impact on the model. Also, we should remove correlated features with similar meanings that contribute similarly according to Shapley values. The correction of bias should have priority over removing a feature: a bias highly influences how a model is learned and, therefore, its correction can cause a feature with no importance in the biased model to gain relevance in the new model. All these considerations are explained in the short example that we provide in the following Section 6.3. 6.3 A case Study with a Real Dataset In this section, we exemplify the human-in-the-loop process and analyze the benefits of implementing it in our NTL system. 6.3.1 Preliminaries The Dataset Used For the case study we use a real dataset2from the utility company with more than 1,000,000 customers3. The labelled instances include around 10,500 NTL cases, and almost 300,000 non-NTL cases and the dataset is split into three sub-datasets: the training (80% of the labelled instances), the validation (10% of the instances) and the test dataset (the remaining 10%). Each partition is stratified. There is no timestamp consideration 1We would accept some margin in this description, i.e. we consider that a model is worse in terms of NDCG when the value is significantly lower (at least 0.1 lower). 2further information like the region and the typology of the customers is anonymized to protect the privacy of the data. 3The customers are apartments/small houses from the same Spanish region. Human-in-the-Loop Approach to Improve NTL Detection 102 (i.e. we do not use the last 10% of NTL cases as the test dataset) to guarantee diversity and reduce the differences between the datasets4. The Algorithm, Loss Function and Metric Used The Gradient Boosting Model trained is a Root Mean Square Error Catboost Regressor, i.e. we consider the problem of detecting NTL as a pointwise ranking problem where we predict the amount of energy to recover for each customer. The methods used to analyze the correctness of our model are the energy200 (to compare the energy recovered before and after the human-in-the-loop process), NDCG on the validation dataset, and Shapley values plots to analyze the patterns learnt by each model. Semantic Grouping of Features and Evaluation To facilitate the explanation and readability of this work, we exemplify the human-in-the-loop approach only on the visit-related features, including plots for the Shapley values in the training and test dataset. A brief description of these features is the following: Types of Visits Most of the visit-related variables represent the visits made to the customers and their three possible results. More specifically, the Fraud features refer to the visits in which the company detected an NTL case. The Correct features refer to the visits where the installation was checked, but no NTL was detected. The Impossible features profile the visits with no conclusive result (in general, because the meter was not accessible). Finally, the Visit features represent all the visits without NTL/Non-NTL distinction. Based on this information, we profile the following features: •Number of Occurrences: Those features that include the # prefix refers to the occurrences of that type of visit (e.g. #Visit refers to the number of visits the company has made to the customer). •Last occurrence: The last occurrence of each type of visit is represented with the features with the last prefix (e.g. LastVisit would refer to how many months have passed since the last visit). When the customer has never been visited, the value of the feature is empty5. •Type of Visit: A visit to a customer is often prompted by suspicion of fraud. In other cases, the visit is related to more generic reasons (e.g. 4If the stakeholder decides to visit recidivist customer in July and August, and in September, we split the data considering the timestamp, in the test dataset we would have an overrepresentation of the recidivist customers. 5That is, there is no value assigned, i.e. a missing value, that the Catboost library is able to process. This solution is applied in all the features to represent the non-existence of a value, e.g. the non-existence of a visit for that customer. Human-in-the-Loop Approach to Improve NTL Detection 103 a generic revision of the meter). Both cases are reflected with suffix 1 and 2, respectively: LastFraud1 refers to how many months have passed since the last fraud was detected in which the reason to visit was a suspicion of fraud (or NTL), LastFraud2 corresponds to how many months have passed since the last fraud in which the reason to visit was not NTL-related. LastFraud (with no suffix) corresponds to the features that groups both types of features. Region-Related Features There are also features related to the density of fraud around the customer. That is, #FraudZone indicates the historical number of NTL cases in a customer’s zone6. Similarly, #FraudStreet is the same information than the #FraudZone but focused specifically on the street where the customer lives, and #FraudInBuilding counts the historical NTL cases in the building where the customer lives. There exist for each feature a derivative (with a suffix 1Year) in which the information is bounded in the last year (e.g. #FraudZone1Year indicates the number of fraud cases in the region during the last 12 months). Threats There is a third group of features (#threats and LastThreat) that refers to the threats of the customer to the technician, i.e. if the customer violently prevents the installation revision from being carried out. Energy Cut Finally, the EnergyCut feature indicates how many months have elapsed since the last energy cut by the company due to non-payment. 6.3.2 Tests In this section we exemplify the process of stakeholder-system interaction by implementing the following: removing a feature due to its irrelevance, removing a correlated feature and correcting an outlier. We compare the baseline model and the resulting model in terms of energy200 to see if, in addition to the improvement in terms of interpretability and bias reduction (that would help to increase the robustness in real campaigns), the resulting model also recovers more energy in the test dataset. First Model (Baseline) •NDCG: 0.44 in the validation dataset. •energy200: 249242.9kWh. •Shapley Values: Figure 6.2 (training+validation model). 6A zone corresponds to a technical term regarding the distribution of the electricity: nearby towns or neighborhoods in a big city share a zone. Human-in-the-Loop Approach to Improve NTL Detection 104 Analysis As we can see in Figure 6.2, our baseline model has Shapley values that are abnormal, because the impact on the output is remarkably higher than all the other values for those features. For instance, if we analyze the LastImpossible2 feature, there is no compelling reason to justify that a feature value increases the output of the model up to 25,000kWh, while the second highest Shapley value increases ten times less. Thus, this is an indicator of an outlier in the labelled information, i.e. an NTL case in which the company recovered a large amount of energy. In this case, the outlier corresponds to an NTL case in which the company recovered 260,000kWh, an extremely abnormal case of NTL due to the large amount of energy recovered7. With this information, the stakeholder would have two options: maintaining the outlier or correcting it. Maintaining an outlier could be useful in some specific cases (for instance, if the company aims to exploit biased patterns learnt8) but, in general, the stakeholder should consider its correction. Next step In this case, an optimal solution would be reducing the weight of this NTL by modifying the label (for instance) four times (i.e. from 260,000 to 66,000kWh). With this change, we still indicate to the system that it is the higher NTL case in the labelled information, but we will avoid biases in the system. Second Model (First Iteration) •NDCG: 0.43 in the validation dataset. •Shapley Values: Figure 6.3 (training+validation model). Analysis First of all, we can see that we achieve a similar NDCG value in the validation dataset, i.e. it seems that the unbiasedness does not reduce the prediction capacity of our model. Then, the Shapley values from Figure 6.3 seem to indicate that the model learnt is better: there are no outliers (the higher Shapley value is reduced from around 30000 to 5000), and therefore it should generalize better on unseen data. So, in summary, a stakeholder would prefer this model over the previous one. Next step For the next iteration we opt to drop the less important feature in the model: #Threats. This should not modify the model trained but would simplify the explanation provided to the stakeholders. 7In the second NTL case in the dataset the company recovered around 50,000kWh. The typical customer consumption is close to 3,500kWh per year. 8In some cases a biased pattern might be in line with business-related decisions. For instance, the stakeholder might consider not removing a pattern in which the customers from a region have higher predictions if the company aims to visit these type of customers more. Human-in-the-Loop Approach to Improve NTL Detection 105 0 5000 10000 15000 20000 25000 30000 SHAP value (impact on model output) #Threats LastThreat #Visits1 #Fraud1 #Correct1 #Fraud2 LastFraud1 LastCorrectFraud LastFraud2 FraudInBuilding1Year FraudInStreet1Year #Impossible1 LastImpossible1 #Impossible2 #FraudZone1Year LastCorrect1 LastFraud FraudInStreet LastVisit1 EnergyCut #Correct2 #FraudZone LastCorrect LastImpossible #Visits2 LastVisit2 LastCorrect2 LastImpossible2 Low High Feature value Figure 6.2: The outliers seen in the image (in yellow) are a consequence of an NTL case in which the amount of energy to recover is higher than 250000kWh. In this situation, the stakeholder in charge of the model building would consider reducing this prediction value to build a more unbiased model. Third Model (Second Iteration) •NDCG: 0.42 in the validation dataset. •Shapley Values: Figures 6.4 (training+validation model) and 6.5 (top-scored customers from the test dataset). Human-in-the-Loop Approach to Improve NTL Detection 106 Analysis Dropping the #threats has not changed much, as expected, what the model has learned (i.e. the plot from Figure 6.3 and the left plot from Figure 6.4 are similar). However, the possibility of dropping features can be fruitful from the company’s perspective. First, it allows to correct undesired patterns learned that, from the human perspective, have no logic but can be seen in a biased dataset. When we introduce a feature in the 0 1000 2000 3000 4000 5000 SHAP value (impact on model output) #Threats LastThreat #Fraud1 #Visits1 #Correct1 #Impossible2 #Fraud2 LastFraud2 LastFraud1 FraudInBuilding1Year LastImpossible1 #Impossible1 FraudInStreet1Year LastCorrectFraud #FraudZone1Year LastFraud #Correct2 EnergyCut FraudInStreet LastCorrect1 #FraudZone LastVisit1 LastCorrect2 LastCorrect LastImpossible #Visits2 LastImpossible2 LastVisit2 Low High Feature value Figure 6.3: The Shapley values for the trained model indicates the nonrelevance of the #Threats feature. Therefore, to facilitate the interpretation of the model by the stakeholders, we drop this feature from the training process. Human-in-the-Loop Approach to Improve NTL Detection 107 0 1000 2000 3000 4000 5000 SHAP value (impact on model output) #Threats LastThreat #Fraud1 #Visits1 #Correct1 #Fraud2 #Impossible2 LastFraud2 FraudInStreet1Year LastFraud1 FraudInBuilding1Year LastImpossible1 #Impossible1 #FraudZone1Year #Correct2 LastFraud #FraudZone FraudInStreet LastCorrect1 LastVisit1 EnergyCut LastCorrect2 LastCorrectFraud #Visits2 LastImpossible LastImpossible2 LastCorrect LastVisit2 Low High Feature value Figure 6.4: The Shapley values highlighted indicate that the model has learned similar patterns from both features with similar meanings. Removing one of the features would increase interpretability and reduce the curse of dimensionality. To decide the best feature to be removed, we can analyze how these patterns translate on unseen data (Figure 6.5). system, we expect that the system will learn some specific patterns. For instance, when we profile with a feature that the customer is consuming much less than the average, we consider that the system should see this as an indicator of NTL. Therefore, if the system learns otherwise in one Human-in-the-Loop Approach to Improve NTL Detection 108 200 0 200 400 600 800 1000 SHAP value (impact on model output) #Threats LastThreat #Fraud1 #Visits1 #Correct1 #Impossible2 #Fraud2 #Impossible1 FraudInStreet LastFraud2 LastImpossible1 LastFraud LastVisit1 FraudInStreet1Year LastCorrect1 #FraudZone1Year LastCorrectFraud FraudInBuilding1Year LastCorrect LastFraud1 LastImpossible #Correct2 LastCorrect2 #FraudZone #Visits2 LastImpossible2 EnergyCut LastVisit2 Low High Feature value Figure 6.5: The Shapley values in the top-scored 200 customers test dataset we see that how #FraudZone1Year influenced the prediction is much clearer than in the #FraudZone feature and, therefore, we would drop the latter feature from the dataset. Human-in-the-Loop Approach to Improve NTL Detection 109 specific domain9, the stakeholder can consider it appropriate to remove it in that specific campaign. Moreover, learning from fewer features with low relevancy helps avoid overfitting and increases the generalizability and interpretability of the model. Next step For this third iteration, we exemplify the process of removing a correlated feature from the model. As shown in Figure 6.4, the features #FraudZone and #FraudZone1Year provide similar information to the learning process globally: a high number of NTL cases in the zone is an indicator of NTL. If we focus on the Shapley values from the top-scored 200 customers, we can see that the patterns learnt from the #FraudZone feature are unclear10 and, for this case, we would opt to remove the #Fraud- Zone feature. Resulting Model The resulting model corresponds to the baseline model + correction of the bias + #threats drop due to its low relevance + #FraudZone drop (correlated with #FraudZone1Year). •NDCG: 0.44 •energy200: 257038.7kWh Analysis The resulting model, in terms of NDCG, is as good as the vanilla model, and in terms of energy200 is slightly better, recovering around 8000kWh more energy. However, in terms of Shapley values the resulting model is more trustworthy from the stakeholder’s point of view, and should generalize better on unseen data. This example is rather naive since we have only slightly modified the system by implementing feature engineering. However, it exemplifies the benefits of the human-in-the-middle approach in which the stakeholder guides the system to learn an optimal model, mitigating the specific biases and other problems regarding the use of observational data. Moreover, the fact that the stakeholder is an active part of the system has positive consequences beyond the ones mentioned above (i.e. the better generalization on unseen data and the better interpretability), as the company can trust the system much more, one of the objectives of explainable AI [11]. 9If this undesired pattern is constantly learned in all the domains, then the feature drop would be definitive. 10 From the stakeholder’s point of view, it is simpler to explain the #FraudZone1Year pattern ”high values is an indicator of NTL” than the patterns from #FraudZone, which are unclear, where sometimes a high value has positive Shapley values, and in other cases, it has negative Shapley values. Human-in-the-Loop Approach to Improve NTL Detection 110 6.4 Discussion One of the things we detected during the development of the system for Naturgy was the lack of ”communication” between the system and the stakeholders: the stakeholders had a passive role in the system, they did not know what the algorithm was doing, nor could they participate in the learning process in an effective way. In this chapter we offer a human-in- the-loop solution that, despite its apparent simplicity, has great benefits for the system. On the one hand, the stakeholders can play a much more active role in guiding the learning system to make correct predictions and, on the other hand, its high transparency means that the company can have much more confidence in the implemented system. Explainable Predictive Process Monitoring 117 currently being processed (referred to as Online Process Monitoring). The former analyzes information from a long period of time (e.g. a full year) to provide a picture of the performance of the process, and is useful to understand the correctness of the process globally. The latter is focused on analyzing current process instances and is used to correct specific problems (e.g. when a customer request remains unanswered). 7.1.3 Predictive Process Monitoring Predictive Process Monitoring is a sub-field of the Process Monitoring process in which the event-logs from the process are used to generate predictions for a specific process, for instance the remaining time of that process (that would correspond to a numeric output), the fulfilment of a certain goal (binary), or a metric that would score the effectiveness of the process. The initial stage of Predictive Process Monitoring consists of encoding the process’ event logs into feature vectors. In general, the information available is massive and, therefore, the encoding process requires feature engineering to extract the most relevant information from four perspectives [43]: control-flow perspective (i.e. the order of the activities performed in the process), the data-flow perspective (i.e. the different attributes attached to the event), the time perspective (i.e. the duration of an activity or the whole process) and the resource perspective (i.e. information regarding the organization that executes the process). These four perspectives differentiate the data processing for process monitoring from the more generic data models (e.g. supervised machine learning). The next stage corresponds to the building of the predictive model. Depending on the approach, the model can be a statistical model (e.g. Hidden Markov Model, [79]), a machine learning approach (e.g. [93]), an annotated transition system (e.g. [120]) or a hybrid of different approaches (e.g. [135]). In the same way, the models can be classified as process-aware models (if there is an explicit representation of the process model, e.g. the annotated transition models) or non-process-aware models (if there is no explicit representation of the process model, i.e. mostly the machine learning models). The validation of the model, similar to what is done in classical machine learning, is evaluated using classical metrics such as precision or accuracy for classification problems, and RMSE or MAE for regression. Finally, the model is used for predicting. In general, predictive process monitoring uses the models for online predictive monitoring (e.g. to predict the remaining time of a process) at a certain point of the process, referred to as checkpoint. Most of these prediction systems cover the following purposes: •Performance indicator: The Process Performance Indicators are metrics that evaluate how well (i.e. how efficient and effective) the process is, providing quality information useful in controlling and improving it. The most common performance metrics aspects evaluated Explainable Predictive Process Monitoring 118 are time-related (e.g. the duration of the activity). •Risk Predictions: Risk predictions encompass all information related to the detection of anomalous process executions, either because an instance of a process is taking too long to execute, or because an activity is running too many times (in a loop). •SLA violation predictions: A Service Level Agreement (SLA) defines a contract between a supplier and a customer, where a breach of any part of the contract may result in financial penalties. Thus, predictive models can be used to identify if an SLA is going to be breached in order to correct it in time. In addition to these cases, there exist other purposes such as the detection of abnormalities (e.g. the abnormal termination of an event) that do not fit previous categories but are common in predictive process monitoring. 7.1.4 Predictive Process Monitoring through Machine Learning Recently, the use of machine learning techniques in predictive monitoring has been increasing dramatically. Their application is a clear example of how machine learning can be implemented in the industry. There are many examples in the literature, ranging from cases where unsupervised and supervised algorithms are used. Some examples of the application of unsupervised algorithms are [44] (that describe a clustering and decision method for the prediction of a violation (or otherwise, the fulfillment) of a determined predicate, or [54], which implements a solution based on clustering to determine a violation of the ongoing instance. In relation to the examples of supervised algorithms, we find examples of both interpretable algorithms (such as [133], in which the framework presented combines different techniques, including Decision Tree models, to predict risk probability), and black-box algorithms that use more complex algorithms that, a priori, should better exploit large amounts of data. Examples of the latter would be the predictive process monitoring systems that are based on Long-Short Term Memory, e.g. [132,93]. As we can see, machine learning offers different solutions for predictive process monitoring, so the choice of algorithm will depend on many factors. As we are analyzing in this thesis, one of the factors to consider is that the use of complex algorithms is, according to the accepted literature, the algorithms that can predict best but are poorly interpretable. This is a problem as we have discussed above in the case of NTL detection in electricity. In the case of BPM the fact of using opaque algorithms is also a problem to be taken into account, since for sure many stakeholders with different roles (that need to understand the predictive systems) will be involved in the process of improving the institution’s processes. Explainable Predictive Process Monitoring 119 7.2 Case Study: Explainable Predictive Process Monitoring In [58] the problem of providing trustworthy explanations to a predictive process monitoring framework is tackled. This work builds a framework based on LSTM models that estimates the corresponding KPI value with an explanation of the features that influenced that prediction. 7.2.1 Preliminaries, Context and Problem Statement The Long-Short Term Memory algorithm is the approach that, according to [97,93,132], provides better results, at the cost of not being transparent. At the time of publication of the paper no relevant work had managed achieved to provide explainability of predictive monitoring models, as explained in [84], which claims that “little attention has been given to [. . .] explaining the prediction values to the users so that they can determine the best way to act upon”, and that “it is necessary to develop tools that help users to query these models in order to get information that is relevant for them”. Existing work attempted to provide explanatory solutions [21,109], but they were simple solutions bounded to simple and specific use cases, difficult to generalize in real case scenarios. In [58] the proposal is to implement explainability with Shapley values to an LSTM-based predictive monitoring framework. The main dataset1 used in the work corresponds to an Italian banking institution, and the process to be monitored is the Bank Account Closure (the process that deals with the closure of customer’s accounts), with 212721 events and 32439 complete traces. From this dataset, 2/3 of the traces would be the training dataset (20% of which has been used for hyperparameter optimization, i.e. used as validation dataset), and 1/3 corresponds to the test dataset. The KPI to be predicted related to this process are the following: Remaining Time The estimation of the remaining time allows the bank to detect those process cases requiring special attention in order not to postpone them much longer. Activity Occurrence There exist several activities2that are linked to contingency actions that should be avoided to reduce inefficiencies in terms of cost, time and resource utilization. Case Cost In this case, the estimation of the case cost would help to detect cases that require special attention. 1The original paper contains other experiments with public datasets. 2Authorization Requested,Pending Request for Acquittance of heirs, and Back-Office Adjustment Requested. Explainable Predictive Process Monitoring 120 The LSTM model provides an optimal structure to represent the sequence of events that constitute a trace. Being ean event (encoded as a feature vector e=< x1, x2, ..., xn>), then a trace tcan be represented as an ordered sequence of events (i.e. t=< e1, e2, ..., em>), that is a matrix NxM of features. Therefore, the Shapley values provide, for each feature, a value indicating its contribution to the predictive output in the same NxM form. Regarding all the Shapley values, in this work the Shapley values considered relevant are the values outside the range I= [µ−δξ, µ +δξ], µ being the average of the Shapley values, ξtheir standard deviation and δ a parameter set by the user. Once the relevant features are computed, two types of explanations are provided, the offline and the online explanations, summarized as follows: Offline Explanations Heatmap that overviews information regarding the frequency in which an explanation has been relevant for the test dataset. Therefore, this offline explanation provides a global explanation of the importance of each feature. Online Explanations The online provides information regarding running instances. In this case, the information is given as a table. 7.2.2 Case Study Analysis Below we provide a summary of the experiments from [58], results that show not only the accuracy of the LSTM models but also the good explanations provided by SHAP. Remaining Time According to the heatmap from Figure 7.2, the most influential feature would be CLOSURE TYPE!=Inheritance, with a negative value of -71598, i.e. it normally reduces the remaining time. This pattern can be humanly validated as when the type of procedure is Inheritance, the process duration is 29 days, versus 14 days when not. Similarly, the LSTM model detects that attributes Role=Back-office and CE UO=BOF (back-office activities) reduce the prediction time, an expected behavior since both activities are performed in the final stage of cases. Regarding the online explanations, in Table 7.2 there is an example of the information provided by the framework. For instance, the last row indicates that the remaining time of that case is just over two and a half hours, with two explanations increasing the prediction, one related to the fact that the previous activity performed was not Service Closure Request with BO Responsibility, and the other related to the resource performing the previous activity with a role not being Back-Office. Explainable Predictive Process Monitoring 121 Figure 7.2: The offline explanation of the remaining time KPI. CASE ID REMAINING TIME EXPLANATIONS FOR INCREASING REMAINING TIME EXPLANATIONS FOR DECREASING TIME 201810011258 5d 6h 7m ACTIVITY=Evaluating Request (NO registered letter) CLOSURE TYPE!=Inheritance 201810000206 5d 2h 12m ROLE=DIRECTOR CLOSURE TYPE=Bank Recess 201811010829 2d 2h 31m ROLE!=BACK-OFFICE (-1) AND ACTIVITY!=Service closure Request with BO responsibility (-1) - ... ... ... ... Table 7.1: Online explanations for Remaining Time for three running cases. When the explanation is followed by (−1), it means that it refers to the value assigned to the attribute by the event that precedes the last of respective case. Explainable Predictive Process Monitoring 122 Table 7.2: Online explanations for Back-Office Adjustment Requested. Values 1 and 0 indicate if the activity is predicted to occur or not. Explanation followed by (−1): attribute value assigned by the event that precedes the last of respective case. CASE ID BACKOFFICE ADJUSTMENT REQUESTED EXPLANATIONS FOR BACK-OFFICE ADJUSTMENT REQUESTED HAPPENING EXPLANATIONS FOR BACK-OFFICE ADJUSTMENT REQUESTED NOT HAPPENING 201810000206 0 ACTIVITY=Service closure Request with network responsibility (-2) AND CE UO=195 (-1) 201811008237 1 CLOSURE TYPE=Porting - 201812005701 1 CLOSURE REASON!=1 - Client lost - ... ... ... ... Finally, the metric used for the LSTM was the Mean Absolute Error (MAE), achieving a MAE on the test dataset of around 4.37 days, which is around 28% of the average case duration (i.e. 15.5 days). Prediction on Activity Occurrence In this work the contingency action analyzed is Back-Office Adjust Requested, an activity related to inefficiency that demands rework. The metrics regarding the LSTM model that predicts this activity achieved an F1-score of 0.65, an AUROC of 0.86, and APR of 0.69. In Figure 7.3 we have the heatmap from the offline analysis, where the Shapley values indicate that the features related to a closure of the bank account influence the most. When the customer makes a request to close all their bank account (i.e. Closure Reason=1 - Client Lost) or only one bank account (i.e. Closure Reason=2 - Keep bank account- Same dip), the adjustment is unlikely: the values of these activities in the heatmap are negative. Negative values are seen in other similar features where the customer decides to close their bank account. On the other hand, when the bank is the one that decide to close the account (e.g. ClOSURE TYPE=Bank Recess), then the activity is more likely to occur. In Table 7.2 we have a small sample of the online explanations. Taking the first case as an example, we can see the rework activity is not expected to happen because two events ago Service Closure Request with Network Responsibility has been performed and because the previous event has been performed by the resource 195. On the contrary, it is predicted to eventually happen for the other two cases in the table, and the explanation is related to the closure type being Porting and the closure reason not being Lost Client. Explainable Predictive Process Monitoring 123 Figure 7.3: Offline explanations for Back-Office Adjustment Requested Case Cost Prediction Finally, for this third KPI the metric adopted is the MAE, achieving an error of 0.95 euros. In this case, this error is very low, since the average cost is 12.86 euros, with a standard deviation of 6.41 euros. Figure 7.4 shows the heatmap of the offline explanation. In this case, the fact that a bank account needs to be closed as requested by the customer (i.e. CLOSURE REASON=1 - Client Lost) increases the cost of the process: according to the paper this is a consequence of the fact that this process is evaluated by the director whose wage is higher than other workers. On the other hand the values in the heatmap are negative when the bank is the one that closes the account (CLOSURE REASON=1 - Client Lost) or the customer only wants to close one of its bank accounts (CLOSURE REASON=2 - Keep bank account. Same dip), expected value considering that the director does not have to carry out any evaluation in these cases. Explainable Predictive Process Monitoring 124 Figure 7.4: Offline explanations for Case cost Explainable Predictive Process Monitoring 125 Closure In predictive monitoring, a lot of work has been done to increase the accuracy of the predictive monitoring system, usually by implementing more complex solutions, such as using black-box algorithms. However, little attention has been paid to making the solutions transparent, facilitating the interpretation of the predictions by the stakerholders, who have to make decisions based on these values. In a way, we find ourselves in a situation similar to the one explained in the project implemented for Naturgy, where automation through artificial intelligence can generate distrust among stakeholders due to its opacity. The lack of interpretability can lead one to discard the use of more complex solutions that, in general, should provide better results, in favor of simpler solutions. Therefore, it is necessary to build trust to guarantee that the system is adopted in practice [94,46]. In this chapter we have analysed the work done in [58], which implements an LSTM framework to predict different KPI. This paper achieves a milestone in Business Process Management in general, and in predictive monitoring in particular, by implementing a fully interpretable system that combines the algorithm that, according to the literature, is the best option to guarantee high accuracy, with the Shapley values that provides reliable explanations, in line with the on obtained from the human analyst from MyInvenio. Our contribution focused on the development of Shapley values explanations of the predictive framework. In Part IV we provide different conclusions regarding the use of this solution in a Business Process Management context, and in Machine Learning in general. Chapter 8 Explainable Black-Box Algorithms in Social Science 8.1 Data in Social Science 8.1.1 Data Modelling in Social Science Social Science is the field in science that studies societies and their individuals, including political structures (i.e., political science), the value of goods and services (i.e., economics), or past human events (i.e., History), among many other research fields. In general, social scientists aim to validate hypotheses through data. That is, the social scientist builds a statistical model with some independent variable (i.e., explanatory variables, that represent different hypotheses) and a dependent variable (i.e., the response). The model reveals relationships between the independent variables and the dependent variable. Based on these variable interactions, the social scientist can validate one hypothesis or another. The quintessential social science model is linear regression (and other generalized versions, e.g., logistic regression) used in Gaussian data and linear, where the coefficients indicate how an independent variable influences the dependent variable. Based on these coefficients, the hypothesis can be validated or otherwise. Thus, the main focus in social science is to validate a hypothesis through statistical analysis. In contrast, predictive machine learning aims to build a model that automatizes a prediction process by learning historically labelled instances to predict unseen new instances. The data distribution is unknown, requiring that both the labelled and unseen instances to be drawn with the same distribution. The fact that in many cases there is no prior assumption of the data distribution means there is no ”correct” modelling algorithm, and therefore it is necessary to analyze how well a model predicts using training-validation split or cross-validation, as explained in 2.1.2. The best model in terms of benchmarking (e.g., the precision result in a validation dataset) is considered the best option to automatize the prediction pro- 126 Explainable Black-Box Algorithms in Social Science 133 in Figure 8.1. 8.2.2 Case Study Analysis Here below we provide a summary of the analysis included in [95]. Previous Analysis Before data modelling, a previous analysis is required to not only understand the characteristics of the data but also to avoid collinearity. In Figure 8.2 the Spearman correlation between variables is analyzed. The Spearman correlation is chosen over the Pearson Correlation due to the characteristics of the data (the assumptions of normal distribution, linear relationship and no homoscedasticity are not met in our data), but also to achieve a comparable correlation metric between two continuous variables, a continuous and a binary variable, and two binary variables1. Three pairwise correlations between the independent variables can be highlighted in Figure 8.2: the negative correlation of -0.65 between the UN LDCs and the GDP per capita variables (that indicates that the UN prioritizes the poorer countries); the correlation between the Delegation and the Budget Previous Year of 0.5, indicating that there is a statistical dependence between the existence of a project in the previous year and the existence of a Delegation; and the Donor Aid Budget and the Colony variable correlation (0.47), indicating that Spain seems to prioritize historical colonies (e.g. Latin American countries) in their donor aid. No correlation seems important enough to implement feature selection due to multicollinearity, as confirmed with Table 8.3 with very low Variance Inflation Factor values between 1 and 2. When analyzing the correlation between each independent variable and the dependent variable we see that the H3 variables have an above-average correlation with the dependent variable. However, there exist no leakage in terms of the chronological order2, and also, the variables are not good enough to fully explain the prediction, as explained in Table 8.4. Therefore, both features are simply considered as good predictors and kept in the model. Logistic Regression Table 8.5 summarizes the logistic regression results, including one model for each hypothesis, and a fourth model that analyses the importance of 1The Spearman correlation measures the monotonic relationship between continuous data and/or ordinal data based on the ranked values instead of their raw value. If it is assumed that the binary data can be seen as ordinal data of two levels, then it is possible to obtain a global vision of the correlations between the variables. 2 Explainable Black-Box Algorithms in Social Science 134 Spearman’s Correlation Heatmaps UN LDCs GDP per capita Public Grant Budget Previous Year Donor Aid Budget Latin America Mission Africa Mission Colony Delegation UN LDCs GDP per capita Public Grant Budget Previous Year Donor Aid Budget Latin America Mission Africa Mission Colony Delegation -0.65 -0.0036 -0.024 -0.0049 -0.074 0.24 0.08 -0.16 0.2 0.31 0 0 0.0081 -0.029 0 0 0 0.0022 -0.054 0 0.18 -0.22 0.2 0.14 0.32 0.47 -0.0031 -0.0032 -0.014 -0.042 0.31 0.5 0.27 -0.039 -0.032 0.25 1.00 0.75 0.50 0.25 0.00 0.25 0.50 0.75 1.00 Project Developed Budget Previous Year Delegation Colony Donor Aid Budget Public Grant UN LDCs Latin America Mission Africa Mission GDP per capita 0.71 0.52 0.32 0.3 0.25 -0.0036 -0.031 -0.057 -0.076 1.00 0.75 0.50 0.25 0.00 0.25 0.50 0.75 1.00 Figure 8.2: Spearman’s Correlation between variables. The plot above provides the strength and direction of monotonic association between the independent variables. Most of the correlation values are low, with some correlation values around ±0.5. The plot below provides the same information between the independent and the dependent variables, showing that the variables from H3 hypothesis are more correlated to the Project Developed variable than the variables from H1 and H2 variables. all variables combined. The coefficients of the variables, as well as the pseudo −R2[85]3, are used to analyze each hypothesis. As we can see in the results from H1, the Donor aid budget and the Public Grant have a positive coefficient, meaning that the Donor Aid (i.e., Spain in this case study) might influence the NGOs in the decision to ahead with a project in a country. However, the low R2indicates that these variables cannot properly explain the variance of the dependent variable and, 3In R, McFadden’s pseudoR2can be computed using the DescTools package. Explainable Black-Box Algorithms in Social Science 135 therefore, this hypothesis cannot be validated. Regarding the constant, it is negative, which is to be expected because it is more likely to not implement a project than otherwise. Finally, it can be seen that Colonial History positively influences the output, a pattern repeated in each of the four models. For H2, the coefficient for the GDP per capita shows a negative trend (i.e., this is the higher the GDP per capita, the less likely it is that a development project will be undertaken) and a highly statistically significant coefficient, as we might expect according to the value principled hypothesis. Regarding the UN LDC priority, the coefficient is negative, meaning that Spanish NGOs do not prioritize these countries (since these are the poorest countries from Africa and Asia, while Spanish NGOs prioritize Spanish-speaking countries). Finally, both the Africa Mission and Latin America Mission have a negative coefficient, an expected variable considering that these regional focused NGOs are smaller than other non-regional focused NGOs (e.g., Cruz Roja or Caritas) and, therefore, they develop fewer projects. Nevertheless, the low R2value of 0.16 still indicates that H2 cannot explain the variance in the dependent variable. Finally, H3 seems to be the hypothesis that explains better the variance in the model, with a R2value higher than 0.5 (and a lower AIC, Akaike Information Criterion, indicating a more parsimonious model). Providing financial aid in the previous year (NGO budget previous year) to one country increases the probability of being prioritized by the organization. In addition, an NGO delegation has a positive coefficient, confirming that past experience in one country is important to understand NGO aid allocation. Finally, the conclusions from H1, H2 and H3 can also be achieved when analyzing the fourth model that includes all the variables: the independent variables from the Back Donor Effect have a positive impact, all the variables regarding the principles and needs of the host have a negative impact, and the path dependence variables have positive impacts and are the most important variables according to their coefficients. In this case, the R2and the AIC are similar to H3, which reaffirms the importance of the NGO’s past choices and experience to determine where the projects are developed. Explainable Black-Box Algorithms in Social Science 136 Variance Inflation Factor of each independent variable VARIABLES VARIANCE INFLATION FACTOR UN LDC 1.75 GDP per capita 1.87 Budget Previous Year 1.03 Delegation 1.04 Donor aid Budget 1.54 Colony 1.84 Latin America Mission 1.02 Africa Mission 1.02 Public Grant 1.06 Table 8.3: The results indicate that there exist no multicollinearity problem in this dataset, with very low VIF values that are never higher than 2. Contingency Table (Budget Previous Year/Delegation, Project Developed) BUDGET PREVIOUS YEAR=0 BUDGET PREVIOUS YEAR>0 Project Developed=0 43439 1365 Project Developed=1 1417 3819 DELEGATION=0 DELEGATION=1 Project Developed=0 44404 400 Project Developed=1 3308 1928 Table 8.4: As indicated by Spearman’s correlation in Figure 8.2, there exists a strong correlation between the variables from H3 and the target variable. However, this correlation is not enough to fully predict if a project is going to be developed in a country and, therefore, it is reason enough to discard the suspicion of data leakage. Explainable Black-Box Algorithms in Social Science 137 Logistic Regression Models for H1, H2, H3 VARIABLES H1: BACK DONOR EFFECT H2: VALUES, PRINCIPLES AND NEEDS OF THE HOST OF THE COUNTRY H3: PATH DEPENDENCE: NGO PAST CHOICES AND EXPERIENCE INCLUDING ALL THE VARIABLES FROM H1, H2 and H3 Constant -2.960497*** [0.022840] 1.78555*** [0.15046] -3.669631*** [0.030106] -0.955250*** [0.216968] log(Donor Aid Budget) 0.053767*** [0.001761] 0.006622* [0.002750] log(Public Grant) 0.177621*** [0.009132] 0.092552*** [0.011865] log(GDP per capita)-0.39960*** [0.01298] -0.235970*** [0.018259] UN LDCs -0.13651** [0.04503] -0.133233* [0.061525] Africa Mission -1.63304 *** [0.14246] -1.440199*** [0.195621] Latin America Mission -0.22153*** [0.04448] -0.206328** [0.063380] log(Budget Previous Year) 0.230539*** [0.002823] 0.220699*** [0.002865] NGO Delegation 2.617064*** [0.082455] 2.355460*** [0.084813] Colonial history (control variable) 1.349853*** [0.037245] 2.46996*** [0.03803] 0.982788*** [0.047921] 1.184480*** [0.064942] R2and AIC Pseudo R20.1712153 0.1595852 0.5017889 0.5144803 AIC 27807 28201 16719 16305 Table 8.5: Logistic Regression Models for H1, H2, H3, and the model that uses all the variables. For each independent variable we include Standard Error [between brackets]. We also include the significance of the variable. *significant at 10%, **significant at 5%, ***significant at 1%. Explainable Black-Box Algorithms in Social Science 138 Explained LSTM model Figure 8.3 includes two charts with the top 10 variables that have the most influence on the dependent variable according to the Shapley values. Indeed, the main conclusions from the regression analysis can be extrapolated in the LSTM model, i.e., the importance of the H3 variables is also shown in the LSTM model. However, the use of the LSTM allowed going further in the analysis, where the information from prior years (e.g., Donor Aid budget 2015 or Delegation 2015) indicates a path-dependence pattern beyond one year. Most important independent variables according to the Shapley values 0.00 0.01 0.02 0.03 0.04 0.05 0.06 average impact on model output magnitude Donor Aid Budget_2015 Delegation_2015 Donor Aid Budget_2016 Budget Previous Year_2012 Colony_2016 Budget Previous Year_2013 Delegation_2016 Budget Previous Year_2014 Budget Previous Year_2015 Budget Previous Year_2016 0.0 0.1 0.2 0.3 0.4 0.5 impact on model output Donor Aid Budget_2015 Delegation_2015 Donor Aid Budget_2016 Budget Previous Year_2012 Colony_2016 Budget Previous Year_2013 Delegation_2016 Budget Previous Year_2014 Budget Previous Year_2015 Budget Previous Year_2016 Low High Feature value Figure 8.3: The most important independent variables according to the Shapley values’ explanation. As indicated by the Regression Model, the Path Dependence variables are the most important independent variables in the model. However, LSTM allows us to include a temporal analysis absent in the Regression model, allowing us to determine historical Path Dependence variables (e.g., Budget Previous Year 2015 and Budget Previous Year 2014 highly influence the decision to develop a project in 2016. Explainable Black-Box Algorithms in Social Science 139 Although it is evident that, at least for Spanish NGOs, the pathdependence hypothesis is confirmed, the paper also analyses the variables of the other two hypotheses (not included in 8.3 due to their low relevance), as can be seen in Figure 8.4. In spite of their negligible impact on model output, these features influence the output as expected. For instance, according to the UN LDCs’ Shapley values, Spanish NGOs do not prioritize the Least Developed Countries, since most of their projects are developed in former Spanish colonies, as previously seen in Figure 8.2. However, we see that a low GDP per capita increases the prediction. If we analyze the variables regarding the mission of the NGOs, we can see that those with a Latin America Mission slightly increase the probability of developing a project, while if we analyze the Africa Mission NGOs, we can see the opposite behavior. Finally, it is clear that the fact that an NGO has a Public Grant to develop a project should increase the model output. Shapley values from other H1 and H2 variables 0.0000 0.0005 0.0010 0.0015 0.0020 0.0025 0.0030 average impact on model output magnitude Africa Mission_2016 Public Grant_2016 Latin America Mission_2016 GDP per capita_2016 UN LDCs_2016 0.04 0.02 0.00 0.02 0.04 0.06 impact on model output Latin America Mission_2016 Public Grant_2016 Donor Aid Budget_2016 GDP per capita_2016 UN LDCs_2016 Low High Feature value Figure 8.4: As we can see in these Figures, H1 and H2 variables are not the most relevant variables for the model, but are worthy of analysis. We would highlight that, according to the UN LDCs values, we can confirm that Spanish NGOs do not prioritize the countries from the UN LDC. If we analyze the variables regarding the mission of the NGOs, we can see that those with a Latin America Mission slightly increase the probability of developing a project, while if we analyze the Africa Mission NGOs we can see the opposite behavior. This is expected since most of the projects from Spanish NGOs are developed in Latin America. Finally, the models consider that the NGOs prioritizes countries with low GDP per capita, an expected behavior. Explainable Black-Box Algorithms in Social Science 140 Closure Within the international aid system, NGOs are key actors, as they are the ones that distribute most of the aid, both from public and private sources. Therefore, NGOs are one of the main focuses of attention when analyzing how such aid is prioritized. The question raised by previous studies is to what extent NGO aid follows a pragmatic or survival logic (developing projects in countries where they can receive donor aid), referred to in this paper as hypothesis 1 (H1) or whether, on the contrary, they move with a logic based on values and principles, more attached to the altruistic idea that surrounds the actions of this type of organization (referred to in this paper as H2). The work carried out in [95] proposes a third option: that NGOs develop projects in those countries where they have roots (referred to in the work as path dependence hypothesis or H3), either because they have developed projects in previous years or because they have a delegation. These three hypotheses are analyzed in this paper using two data methods. The first method consists of developing several logistic regression models, where each model is intended to validate each of the above hypotheses. All the variables are significant, so it is not easy to evaluate which is the clearly determining logic. However, only the models with the path dependence independence variables achieve a high R2, around 0.5 (while the other models had R2 values close to 0.16), i.e. the information related to the existence of a project in the previous year or a Delegation is able to explain the variance of the dependent variable. The second approach consists of fitting a Long-Short Term Memory Neural Network model, an Artificial Intelligence predictive algorithm that has persistence on historical data. This approach allows to determine if the path dependence patterns from H3 exist beyond one year (e.g. if a project developed before 2015 can influence the developing of a project in 2016). The explanation of the model obtained using Shapley values confirms the existence of this relationship, since among the ten most relevant variables to determine whether a project is developed in 2016, five correspond to whether a project existed in previous years (2011-2015)4, and two correspond to the existence of a Delegation in 2016 and 2015. The other three variables are if the country is a former colony of the back donor, and the Donor Aid Budget for that country in 2016 and 2015. This temporal perspective cannot be achieved through the classical regression approach, demonstrating that explained artificial intelligence models can be a great tool in social sciences, with non-restrictive fully interpretable data models. 4As a reminder, the Budget Previous Year from a year X corresponds to the money spent in that country in the previous year, i.e. year X-1. Part IV Conclusions and Further Research 141 142 This work has previously explained three data science projects where the human factor has been a key element in their development, allowing us to understand, explore and apply the most important tools of explainable artificial intelligence. Below we will summarize the contributions of the work carried out. Then, we will draw some general conclusions about the current state of machine learning in general and interpretability tools in particular and analyze what it means to achieve a robust and transparent predictive model.