scieee AI-readable full text Open interactive document viewer

Un-factorize non-food NPS on a food-based retailer

Carvalho, Inês Gonçalves

Abstract

O Net Promoter Score (NPS) é uma métrica muito utilizada para medir o nível de lealdade dos consumidores. Neste sentido, esta dissertação pretende desenvolver um modelo de classificação que permita identificar a classe do NPS dos consumidores, ou seja, classificar o consumidor como Detrator, Passivo ou Promotor, assim como perceber os fatores que têm maior impacto nessa classificação. A informação recolhida permitirá à organização ter uma melhor percepção das áreas a melhorar de forma a elevar a satisfação do consumidor. Para tal, propõe-se uma abordagem de Data Mining para o problema de classificação multiclasse. A abordagem utiliza dados de um inquérito e dados transacionais do cartão de fidelização de um retalhista, que formam o conjunto de dados a partir dos quais se consegue obter informações sobre as pontuações do Net Promoter Score (NPS), o comportamento dos consumidores e informações das lojas. Inicialmente é feita uma análise exploratória dos dados extraídos. Uma vez que as classes são desbalanceadas, várias técnicas de reamostragem são aplicadas para equilibrar as mesmas. São aplicados dois algoritmos de classificação: Árvores de Decisão e Random Forests. Os resultados obtidos revelam um mau desempenho dos modelos. Uma análise de erro é feita ao último modelo, onde se conclui que este tem dificuldade em distinguir os Detratores e os Passivos, mas tem um bom desempenho a prever os Promotores. Numa ótica de negócio, esta metodologia pode ser utilizada para fazer uma distinção entre os Promotores e o resto dos consumidores, uma vez que os Promotores são a segmentação de clientes mais prováveis de beneficiar o mesmo a longo prazo, ajudando a promover a organização e atraíndo novos consumidores.

Full text

Universidade do Minho Escola de Ciências Inês Gonçalves Carvalho Un-factorize Non-food NPS on a foodbased retailer outubro de 2022 Un-factorize Non-food NPS on a food-based retailer Inês Carvalho UMinho | 2022 Universidade do Minho Escola de Ciências outubro de 2022 Inês Gonçalves Carvalho Un-factorize Non-food NPS on a food-based retailer Dissertação de Mestrado Mestrado em Estatística para Ciência de Dados Trabalho efetuado sob a orientação da Prof. Doutora Susana Margarida Ferreira de Sá Faria e de Dr. Ana da Costa Freitas DIREITOS DE AUTOR E CONDIÇÕES DE UTILIZAÇÃO DO TRABALHO POR TERCEIROS Este é um trabalho académico que pode ser utilizado por terceiros desde que respeitadas as regras e boas práticas internacionalmente aceites, no que concerne aos direitos de autor e direitos conexos. Assim, o presente trabalho pode ser utilizado nos termos previstos na licença abaixo indicada. Caso o utilizador necessite de permissão para poder fazer um uso do trabalho em condições não previstas no licenciamento indicado, deverá contactar o autor, através do RepositóriUM da Universidade do Minho. Licença concedida aos utilizadores deste trabalho Atribuição CC BY https://creativecommons.org/licenses/by/4.0/ ii Acknowledgements Firstly, I would like to thank MC Sonae for the opportunity to develop my master thesis, it was truly one of the most amazing experiences. A special thank you to Liliana Bernardino and Ana Freitas, the best mentors I could ever asked for, for welcoming me with open arms and hearts, and teaching me so much. It was incredibly empowering working with you. I also owe my gratitude to my brilliant buddy Francisco Barbosa who guided me from day one, dealt with all my existential crises and taught me the true meaning of the word buddy. I will never forget. To Ana Carvalho for always having the best word of advice and a smile on her face. To Filipe Miranda for all the amazing inputs, motivation and laughing at my jokes. To Nuno Chicória from whom I learned so many great facts and not always about data science. I would also like to thank Vitor Sousa and Alexandre Sousa for always being open to help me. Thank you all for your friendship. I will cherish you always. Another special thank you goes to my dissertation supervisor, Prof. Susana Faria. I am grateful for her guidance, total availability, support, insights and critical look throughout the process of this dissertation. Thank you for showing me that in everything we do we must apply a dose of passion, but also a lot effort and hard work. Last, but definitely not the least, I would like to acknowledge the strong support of my family and friends. To my parents and my siblings for always believing in me. To Rui for his unconditional support, patience and love above anything else. To my good-fairies, Jacinta and Eliana, for cheering me up and guiding me all the way through. To Joana, for being my rock. And to all of my friends for hearing me complain and supporting me through everything. You know who you are. iii iv Resumo Un-factorize Non-food NPS on a food-based retailer O Net Promoter Score (NPS) é uma métrica muito utilizada para medir o nível de lealdade dos consumidores. Neste sentido, esta dissertação pretende desenvolver um modelo de classificação que permita identificar a classe do NPS dos consumidores, ou seja, classificar o consumidor como Detrator, Passivo ou Promotor, assim como perceber os fatores que têm maior impacto nessa classificação. A informação recolhida permitirá à organização ter uma melhor percepção das áreas a melhorar de forma a elevar a satisfação do consumidor. Para tal, propõe-se uma abordagem de Data Mining para o problema de classificação multiclasse. A abordagem utiliza dados de um inquérito e dados transacionais do cartão de fidelização de um retalhista, que formam o conjunto de dados a partir dos quais se consegue obter informações sobre as pontuações do Net Promoter Score (NPS), o comportamento dos consumidores e informações das lojas. Inicialmente é feita uma análise exploratória dos dados extraídos. Uma vez que as classes são desbalanceadas, várias técnicas de reamostragem são aplicadas para equilibrar as mesmas. São aplicados dois algoritmos de classificação: Árvores de Decisão e Random Forests . Os resultados obtidos revelam um mau desempenho dos modelos. Uma análise de erro é feita ao último modelo, onde se conclui que este tem dificuldade em distinguir os Detratores e os Passivos, mas tem um bom desempenho a prever os Promotores. Numa ótica de negócio, esta metodologia pode ser utilizada para fazer uma distinção entre os Promotores e o resto dos consumidores, uma vez que os Promotores são a segmentação de clientes mais prováveis de beneficiar o mesmo a longo prazo, ajudando a promover a organização e atraíndo novos consumidores. Palavras-chaves: Net Promoter Score, Data Mining , Classificação, Árvores de Decisão, Random Forest v Abstract Un-factorize Non-food NPS on a food-based retailer More and more companies realise that understanding their customers can be a way to improve customer satisfaction and, consequently, customer loyalty, which in turn can result in an increase in sales. The NPS has been widely adopted by managers as a measure of customer loyalty and predictor of sales growth. In this regard, this dissertation aims to create a classification model focused not only in identifying the customer’s NPS class, namely, classify the customer as Detractor, Passive or Promoter, but also in understanding which factors have the most impact on the customer’s classification. The goal in doing so is to collect relevant business insights as a way to identify areas that can help to improve customer satisfaction. We propose a Data Mining approach to the NPS multi-class classification problem. Our approach leverages survey data, as well as transactional data collected through a retailer’s loyalty card, building a data set from which we can extract information, such as NPS ratings, customer behaviour and store details. Initially, an exploratory analysis is done on the data. Several resampling techniques are applied to the data set to handle class imbalance. Two different machine learning algorithms are applied: Decision Trees and Random Forests. The results did not show a good model’s performance. An error analysis was then performed in the later model, where it was concluded that the classifier has difficulty distinguishing the classes Detractors and Passives, but has a good performance when predicting the class Promoters. In a business sense, this methodology can be leveraged to distinguish the Promoters from the rest of the consumers, since the Promoters are more likely to provide good value in long term and can benefit the company by spreading the word for attracting new customers. Key-words: Net Promoter Score, Data Mining, Classification, Decision Trees, Random Forest vi ”All models are wrong, but some are useful.” George Box vii List of Acronyms AUC Area Under the ROC Curve CART Classification and Regression Trees CX Customer Experience CM Confusion Matrix CP Complexity Parameter CRISP-DM Cross Industry Standard Process for Data Mining CV Cross-Validation DM Data Mining DOP Direção Operacional DT Decison Trees FN False Negative FP False Positive HEOM Heterogeneous Euclidean-Overlap Metric HVDM Heterogeneous Value Difference Metric ID3 Iterative Dichotomiser 3 IR Imbalance Ratio L12M Last 12 Months xiv L6M Last 6 Months L3M Last 3 Months LM Last Month ML Machine Learning MVP Minimum Viable Product NPS Net Promoter Score OOB Out-of-Bag PDP Partial Dependence Plot PPrecision RF Random Forest ROS Random Oversampling RUS Random Undersampling ROC Receiver Operating Characteristics SSensitivity SMOTE Synthetic Minority Oversampling Technique TN True Negative TP True Positive WOM Word of Mouth xv Chapter 1 Introduction The following chapter will contextualize the dissertation topic within the retail industry and its objectives. Ultimately, an overview of the dissertation structure will be presented. 1.1 Big Data Analytics in Retail The business environment is being challenged by the connected community of customers, mostly due to internet revolution and social networks, where the opinion about a certain product, service or the global image of a company is being spread all over [38]. Word of Mouth (WOM) communication and user reviews about previous experiences have become an important source of information to consumers [17]. As such, depending on the information received, companies can either acquire a new customer or lose one. In that sense, customer loyalty is a key differentiation element across industries as companies recognize its role as a part of their commercial success. A way to monitor it is through market research based on metrics like the Net Promoter Score (NPS) [47]. The Net Promoter Score (NPS) was introduced by [56] as an indicator that measures the level of customer loyalty to a company. This metric is measured primarily through surveys in which the consumers are asked to provide feedback such as the willingness for recommending the company’s product and/or services to others. The description uses a ten-point response scale segmenting customers as Promoters, those who answer nine or ten; Passives, those who answer seven or eight; and Detractors, those who answer between zero and six. Overall, employing analytical models to predict the NPS allows the company to deepen their 1 knowledge across various levels (e.g. stores, type of consumer, etc) without having to assess the entire population. Moreover, it also allows the company to identify which bottlenecks are potentially associated with a lower level of loyalty, which can provide guidelines on how to increase customer satisfaction and, as a consequence, customer loyalty. 1.2 Project Setting The current project was developed at the Advanced Analytics and Insights team at Cartão Continente department on MC Sonae. MC Sonae Sonae is a multinational company managing a diversified portfolio of businesses in different sectors, such as retail, wellness and well being (MC Sonae), financial services (Universo and Bright- Pixel), technology (Worten), real estate (Sierra), telecommunications (NOS), fashion (Zeitreel), sports (ISRG) and plant based ingredients (Sparkfood Sonae). MC Sonae is the leading food retailer in Portugal, with a number of distinct business segments such as Continente (hypermarkets), Continente Modelo (supermarkets) and Continente Bom Dia (convenience supermarkets), Meu Super (franchising proximity store), Bagga (cafeteria), Go Natural (health-oriented supermarkets and restaurants), Make Notes and Note! (bookshop and stationery store), ZU (products and services for pets), Well’s (health, well-being and optics), Dr.Wells (dentistry and cosmetic medicine) and Zippy, Mo (children and adult textile) and Cozinha Continente (restaurant). Loyalty Program Most companies are unable to manage their relationships with their customers as they do not have detailed information on which they can act to make the relationship more valuable [45]. Cartão Continente was launched in 2007 with the aim to have a better understanding on their customer’s behaviour and thus increase the customer loyalty to the brand on acting on a more personal level. It currently has around 4 million active loyalty accounts and more than 80% of the total transactions are done using loyalty cards. 2 The loyalty card is the main source of knowledge about customer behavior and has allowed the company to improve their management and as a consequence their relationship with the customer. Nowadays, the card includes 19 permanent partners (Continente Stores, Meu Super, Note, Wells’s, Zu, Bagga, Mo and Zippy) as well as some external partners like Galp and the Ibersol group (with brands such as Burger King, SOL, KFC, Pizza Hut, etc). 1.3 Project Motivation and Objectives More than ever, forward-looking companies are moving toward the goal of understanding their customers as individuals and using that understanding to relate with the company rather than with competitors, translating into increasing sales. For MC Sonae, building a business around the customer relationship is a primary business issue. In this sense, this project arises with the objective of predicting all Note’s customers NPS class, namely, predict the customer as a Promoter, Passive or Detractor. Moreover, it aims to determine what are the most important variables and thus understand which effects can impact the customer’s classification. The identification of customers and their loyalty behavior will allow to identify store experiences, services and products that lead to pleasant or unpleasant experiences to consumers, and that way identify areas to improve customer satisfaction. The project requires the use of data from surveys and Cartão Continente loyalty card. This last data includes information on transactions from different businesses. Different programming languages were used to extract, merge and analyse data from the surveys and Continente database, such as SQL, R and Python, as well as Excel for data analysis. 1.4 Proposed Approach In order to achieve the objectives proposed earlier, this project will follow the steps of the Cross Industry Standard Process for Data Mining (CRISP-DM) [63]. Proposed in 2000, it is still one of the most common methodologies for data mining, analytics, and data science projects. This framework involves six phases, namely: Business Understanding, Data Understanding, Data Preparation, Modelling, Evaluation, and Deployment (Figure 1.1) 3 Figure 1.1: CRISP-DM reference model phases. Source: [48] • Business Understanding aims to understand the business needs and sets clear goals for the project. • Data Understanding consists on collecting, describing and exploring the data. Basic statistical descriptions provide the analytical foundation for modelling the data, since it provides the context needed to develop the model and interpret its results correctly. • Data Preparation consists of data preprocessing. Usually the raw data collected tends to be incomplete, noisy, and inconsistent, and so it cannot be applied directly into building the model, hence it is paramount to process the data. This process may be repeated several times, depending on the quality of the data and the accuracy of the model obtained. The preprocessing of the data might include data cleaning, data integration, data selection and reduction, and data transformation [26]. • Modeling involves choosing the modelling techniques and algorithms, as well as the tools to create the model. Once the model is chosen and built, the following step consists of evaluating its performance. • Deployment integrates a machine learning model into an existing production environment to make practical business decisions based on data. 4 The CRISP-DM’s longevity, especially in a rapidly changing area stems from a number of characteristics. Firstly, it encourages to focus on business goals, so as to ensure that project outputs provide tangible benefits to the organization. Too often, analysts can lose sight of the ultimate business purpose of their analysis and this approach helps to ensure that the business goals remain at the centre of the project. Secondly, it provides an iterative approach, including frequent opportunities to evaluate the progress of the project against its original objectives, which helps minimize the risk of getting to the end of the project and finding that the business objectives have not really been addressed. It also means that the objectives of the project can be adapted in the light of new findings [66]. 1.5 Dissertation Structure The dissertation is organized as follows. Chapter One presents the role of big data in retail, a brief description of the company and the main goal of the project, as well as the project approach. Chapter Two introduces the Net Promoter Score, as well as different customer related concepts of experience. Chapter Three comprises an extensive literature review on the methodological framework of this project. Chapter Four reports the steps taken in finding the right data and the outcomes of the exploratory analysis performed on it. Chapter Five describes the use of the machine learning methods for modelling and the results obtained, as well as an error analysis. And finally, Chapter Six presents conclusions of the work done and gives suggestions for future work in this area. 1.6 Notation In supervised learning, an algorithm is fed with a data set E={E1, E2, ..., EN}with N observations Ei= (xi, yi)where xi= (xi1, xi2,··· , xiM ). Each observation Eihas an associated label yi(i= 1,··· , N) that defines the class the observation belongs to. Table 1.1 represents a data set with Nobservations (rows) and Mvariables (columns). For classification problems, the class variable Yis a qualitative variable that may assume a set of K classes C={C1, C2,··· , CK}[6]. The notation used throughout this paper is summarized in Table 1.2. 5 Table 1.1: Data set in the attribute-value form. Adapted from [6] . A1A2··· AMY E1x11 x12 ··· x1My1 E2x21 x22 ··· x2My2 . . .. . .. . ..... . .. . . ENxN1xN2··· xNM yN Table 1.2: Commonly used symbols and terms. Symbol Term AmVariable m={1,··· , M}(explanatory variable) EiObservation i={1,··· , N} CkClass k={1,··· , K} KTotal number of classes YClass variable Y={y1,··· , yN}(response variable) yiClass label of observation i NCkNumber of observations in class k NTotal number of observations N=NC1+···+NCk DTraining data set 6 Chapter 2 Measuring Customer Experience This chapter introduces the Net Promoter Score (NPS) metric, the research literature related to it and the different concepts of experiences - customer experience and customer satisfaction. The concepts are well established in business literature, and while they are often used as synonyms there are differences when using such terms in customer related discussions. 2.1 Net Promoter Score (NPS) In recent years, researchers have suggested a number of customer metrics to illustrate the connections between customer behaviour and company growth. Reichheld [55] proposed the concept of Net Promoter Score (NPS) in the Harvard Business Review as one such metric. Nowadays, the NPS is a widely used customer metric across service industries and over other industries across the world. The author claimed that only one question based on the willingness of a customer to make a recommendation to friends or colleagues would determine customer loyalty and consequently the company’s growth. The calculation of the NPS is quite straightforward, the customers are asked the question: ”How likely is that you would recommend company X to a friend or colleague?”, on a scale of 0 to 10, where 0 means “Not at all Likely” and 10 means “Extremely Likely”. The questions are captured and the customers are then grouped into Promoters (9–10 rating), Passives (7–8 rating) and Detractors (0–6 ratings) (Table 2.1). Since it is the Promoters and the Detractors who will influence the company’s reputation, the NPS is calculated by subtracting the percentage of Detractors from the percentage of Promoters (Equation 2.1). 7 Table 2.1: Net Promoter Score (NPS) customer categorization. Ratings NPS Label 9-10 Promoter 7-8 Passive 0-6 Detractor NPS =%Promoters −%Detractors. (2.1) Promoters are thought to be extremely satisfied customers and therefore are the most likely to promote the company, service or product. On the other hand, Detractors are the segment of the customers who are likely to detract the company, service or product and are thought to be associated with negative experiences, which might cloud a recommendation. At a neutral point, Passives are neither satisfied nor disappointed with the company, but they can begin to hint at room for improvement [36]. According to Reichheld [56] the willingness to promote is a strong indicator of loyalty and consequently of the growth of the company because the customers put their reputation at stake when they are recommending and they will only do that when they are intensely loyal. The author defines loyalty as the “willingness of someone – a customer, a friend, an employee, a friend – to make an investment or personal sacrifice in order to strengthen a relationship”. Loyal customers are more likely to make repeat purchases and use services that provides good value in the long term. Word of mouth (WOM) is one of the most effective promotion tools ( [13]), and so loyal customers will also benefit the company by spreading the word for attracting new customers. In that sense the growth of the company would be proportional to the number of Promoters the company is having. More than a numerical score used to measure the company’s performance, the NPS has evolved into a system. According to the authors in [55], to formulate a working system one needs three fundamental elements: systematic data collection process, closed loop learning process and organizational goal to get more Promoters than Detractors. Accordingly, the system can help to transfer companies to become more costumer focused organization. Systematically collecting data and analyzing the NPS enables the information to be communicated through the organization. A closed loop learning regards the learning related to the collected data, and, consequently, the pro- 8 numeric variables. The HEOM distance function uses different distance functions on different types of variables. One approach is to use the Overlap metric for nominal variables and normalized Euclidean distance for linear variables. If either of the variables values is unknown, they are handled by returning a distance of 1, which is equivalent to the maximal distance. The distance between two values xand yof a given variable acan be defined as: da(x, y) =              1,if xor yis unknown, else overlap(x, y),if ais nominal, else rn_diffa(x, y) (3.2) The function overlap and the range normalized difference rn_diff are defined as: overlap(x, y) =      0,if x=y 1,otherwise (3.3) rn_diffa(x, y) = |x−y| rangea (3.4) The value rangeais used to normalize the variables, and can be defined as: rangea=maxa−mina(3.5) where maxaand minaare the maximum and minimum values, respectively, observed in the training set for variable a[75]. The definition for dareturns a value which, typically, ranges between 0 and 1, whether the variable is nominal or linear. The overall distance between two input vectors xand yis given by the HEOM function: HEOM =v u u t M X a=1 da(xa, ya)2(3.6) where Mis the number of variables. The HVDM function is very similar to the HEOM function. It also returns the distance between two input vectors xand y, however it uses Value Difference metric instead of an Overlap metric for nominal values and it normalizes differently. The HVDM can be defined as: 15 HVDM =v u u t M X a=1 d2 a(xa, ya)(3.7) The function da(x, y)returns a distance between the two values xand yfor variable aand uses one of two functions, depending on whether the variable is nominal or linear. It can be defined as: da(x, y) =              1,if xor yis unknown, else normalized_vdma(x, y),if ais nominal, else normalized_diffa(x, y),if ais linear (3.8) The normalized_vdm and normalized_diff functions can be described as followed: normalized_vdma(x, y) = v u u tC∗ K X k=1     Na,x,k Na,x −Na,y,k Na,y     2 (3.9) where •Na,x is the number of observations in the training set (D) that have value xfor variable a; •Na,x,k is the number of observations in Dthat have value xfor variable aand output class k; •Kis the number of output classes in the problem domain. and normalized_diffa(x, y) = |x−y| 4σa (3.10) where σa is the standard deviation of the numeric values of variable a[75]. The SMOTE approach may be especially problematic in the case of highly skewed class distributions where the minority class observations are very sparse, thus resulting in a greater chance of class mixture (Figure 3.2) [10]. Moreover, the opposite can also happen since interpolating minority class observations can expand the minority class clusters, introducing artificial minority class observations too deeply into the majority class space [6]. Several variations and improvements of this method exist, such as SMOTE+Tomek Links, which creates better defined class clusters. 16 Two variables Eiand Ejform a Tomek Link [69] if only they belong to different classes and are each other nearest neighbours [9]. Namely, if d(Ei, Ej)is the distance between (Ei, Ej), then a (Ei, Ej)pair is called a Tomek Link if there is not a variable Elsuch that d(Ei, El)<d(Ei, Ej) or d(Ej, El)<d(Ei, Ej). If two variables form a Tomek link, then either one of these variables of the majority class is eliminated or both variables are eliminated. The SMOTE+Tomek Links approach applies Tomek links to the oversampled training dataset. Thus, instead of removing only the majority class variables that form the Tomek links, variables from both classes are removed [6]. The application of this method is illustrated in Figure 3.3. This method is applicable when the data sets are highly imbalanced or there are a few variables of the minority class [16]. Figure 3.3: SMOTE+ Tomek Links: (a) original data set; (b) oversampled data set with SMOTE; (c) Tomek links identification; (d) Tomek links removed, producing a balanced data set with well defined class clusters. Reprinted from [6]. 3.2 Data Mining Techniques for NPS Classification The data that businesses collect about their customers is one of their greatest assets. Within the vast amount of collected data there is valuable information that can make a difference in the way companies run their businesses, and the way they interact with their current and prospective 17 customer, which can lead them to gain edge on the competitors [2]. Data mining is an important component of analytic in customer relationship management, it can extract hidden predictive information from large databases to predict future trends and behaviours, allowing businesses to make knowledge-driven decisions. In a business perspective, the goal of data mining is to allow a corporation to improve its marketing, sales, and customer support operations through a better understanding of its customers. The result is happy, loyal customers and profitable businesses [41]. Data mining techniques for NPS prediction are divided in two main approaches: supervised and unsupervised methods. Both of these approaches are based on training an algorithm with a record of observations from the past. Supervised methods require that each of those observations used for learning has a label with the class it belongs to. In the context of NPS prediction, this means that for each observation we know if it belongs to the class Promoters, Passives or to the class Detractors. Supervised methods attempt to discover the relationship between independent variables (input variables) and a dependent variable (target variable), and, as a prediction model, they can later be used for predicting the value of the target variable whenever the values of the input variables are known [58]. As an important data mining technique, prediction is a supervised method that predicts values of certain variables in unknown situations from historical data. There are two main prediction models: Classification models and Regression models. The difference between them is that Classification uses categorical or discrete data as the target variable, whereas Regression uses numerical or continuous data [24]. As a highly application-driven domain, data mining has incorporated many techniques from other domains such as statistics and machine learning. Statistics studies the collection, analysis, interpretation, and presentation of data, and it has an inherent connection with data mining. Statistical models are widely used to model data and data classes. For instance, in data mining tasks like classification, statistical models of target classes can be built and, subsequently, be the outcome of a data mining task. Furthermore, statistics is useful for mining various patterns from data as well as for understanding the underlying mechanisms generating and affecting the patterns. Machine Learning (ML) investigates how computers can learn or improve their performance based on data. There are a number of ML techniques available for classification modelling, such as decision trees, random forests, neural networks, among others [26]. 18 Classification is probably the most common data mining activity today, and it can be described as a procedure that given a data set Eand an unclassified observation Eiit assigns a class label yito Ei. Data classification consists of a two-step process. Firstly, there’s a learning step, where a classification model, also known as classifier, is built by analyzing a training dataset (D) made up of database observations (Ei) and their associated class labels (yi). In the second step, the model is used for classification. First, the predictive accuracy of the classifier is estimated using a test dataset. The test dataset is made up of test observations from the original dataset and their associated class labels. Such observations are independent of the training ones, meaning that they were not used to construct the classifier. The test set is used to measure the performance of the classifier, if it is considered acceptable, the classifier is then used to classify future data observations for which the class label is unknown [26]. Figure 3.4: Classification process. Generally, there are three main types of classification tasks: binary, multi-class and multi-label. Binary classification refers to those classification tasks with two class labels. For example, these can be used in churn detection in order to predict whether a given customer is going to churn or not, in email spam detection, cancer detection, etc. Typically, these tasks involve one class that is the normal state, and usually assigned the class label 0, and another class that is the abnormal state, and assigned the class label 1. Multi-class classification tasks have more than two class labels. Unlike binary classification, multi-class classification does not have the notion of normal and abnormal outcomes. Instead, variables are classified as belonging to one among a range of known classes. Examples include plant species classification, face recognition, etc. Multi-label classification refers to those classification tasks that have two or more class labels, 19 where one or more class labels may be predicted for each variable, unlike binary and multi-class classification where a single class label is predicted for each variable. Considering an example of photo classification, a given photo may have multiple objects in the scene and a model may predict the presence of multiple known objects in the photo, such as a bicycle, apple, person, etc [12]. In NPS classification, the customers are segmented into Promoters, Passives or Detractors, therefore it sets our problem into a 3-class classification problem. There is not a method that single-handedly works best for every data set. Hence it is an important task to decide for any given set of data which method produces the best results. Selecting the best approach can be one of the most challenging parts of performing statistical learning in practice. Two important concepts that arise in selecting a statistical learning procedure for a specific data set are the train and test error rate. Let it be represented ˆ f(x)as the prediction that ˆ fgives for the ith observation (Ei). The training error rate is the proportion of mistakes that are made if we apply ˆ fto the training observations: 1 N N X i=1 I(yi6= ˆyi)(3.11) Here ˆyiis the predicted class label for Eiusing ˆ f. And I(yi6= ˆyi)is an indicator variable that equals 1 if yi6= ˆyiand zero if yi= ˆyi. If I(yi6= ˆyi)= 0 then Eiwas classified correctly by our classification method; otherwise it was misclassified. Equation 3.11 refers to the training error rate because it is computed based on the data that was used to train the classifier. The test error rate associated with a set of test observations of the form (x0, y0)is given by: Ave(I(y06= ˆy0)) (3.12) where ˆy0is the predicted class label that results from applying the classifier to the test observation with predictor x0. A good classifier is one for which the test error 3.12 is smallest [35]. There are many classification techniques, the most common include decision trees, neural networks, logistic regression, discriminant analysis and emerging tools such as rough sets and support vector machines, among others [62]. In [51], the authors provide an academic database of literature, published between 2000 and 2006, and propose a classification scheme to classify the articles. Their aim was to give a research summary on the application of data mining and 20 determine which techniques are most often used in the customer relationship management domain. With respect to the research findings, they have concluded that classification models, in particular neural networks and decision trees are the most commonly applied algorithms for predicting future customer behaviour. 3.2.1 Decision Tree Decison Trees (DT) are one of the most popular supervised learning algorithms in data mining, and its main objective is to construct a training model that can be used to predict the class or value of target variables through learning decision rules inferred from the training data. Their popularity is mostly due to their simplicity and transparency, since they are easier to interpret than other techniques [58]. The decision tree algorithm creates a hierarchical partitioning of the data that can be summarized in a tree. The basic structure of a DT consists of nodes that form a rooted tree, meaning it is a directed tree with a node called root that has no incoming edges (or branches), whilst all other nodes have exactly one incoming edge. A node with outgoing edges is called an internal node. All other nodes are called leaves. Moreover, a node that gets divided into sub-nodes is also known as parent node, and these sub-nodes are known as child nodes (Figure 3.5). Variables are classified by navigating them from the root of the tree down to a leaf, according to the outcome of the tests along the path, and then assigned to one class representing the most appropriate target value [65] The overall approach is to try to recursively split the data so as to maximize the discrimination among the different classes over different nodes [1]. Basically all decision tree algorithms require splitting criteria for splitting a node to form a tree, where the main aim is to reduce the impurity of a node. A partition is pure if all the observations in it belong to the same class. There are many criteria by which node impurity is minimized in a classification problem. Some commonly used metrics include: Classification error rate, Entropy, Gini index, Information Gain and Gain ratio [26]. Classification error rate is simply the proportion of observations misclassified over the whole set of observations, which in DT corresponds to the proportion of observations that do not belong to the most common class. However, it turns out that classification error is not sufficiently sensitive for tree-growing, and in practice other measures are preferable. 21 Figure 3.5: Decision Tree structure. Entropy is the measure of impurity of a node. It can be written as: Entropy =− K X k=1 ˆpnk log ˆpnk.(3.13) Here ˆpnk represents the proportion of training observations in the nth node that are from the kth class. Since 0 ≤ˆpnk ≤1, it follows that −ˆpnk log ˆpnk ≥0. The value of this metric lies between 0 and 1, and the closer its value to 0 the better [35]. The Gini index is another impurity-based metric that measures the total variance across the K classes (Equation 3.14) GiniIndex = K X k=1 ˆpnk (1 −ˆpnk)(3.14) This metric takes on a small value if all of the ˆpnk’s are close to zero or one. For this reason in the Gini index, like entropy, a small value indicates that a node contains predominantly observations from a single class [35]. Information gain uses the entropy measure as the impurity measure, and it is defined as the difference between the entropy of the node before splitting (parent node) and after splitting (child node) [37]. 22 Info Gain(5) = entropy (parent node)−entropy (child node)(3.15) The impurity-based criterions described above can be biased towards Variables that have large number of distinct values. Namely, they prefer input Variables with many values over those with less values. For that reason, sometimes it is useful to “normalize” the impurity-based measures [35]. The Gain Ratio normalizes the information gain, and is determined as: Gain Ratio =Information Gain(5) Entropy (3.16) Usually, either entropy or the Gini index are typically used to evaluate the quality of a particular split, since these two approaches are more sensitive then others. The Gini Index may encounter problems when the domain of the target variable is relatively wide [65]. In such cases it is possible to employ a binary criterion called Twoing criteria. This criteria is designed for multiclass problems and favors separation between classes. Every multiclass split is treated as a binary problem. Splits that keep related classes together are favored. The approach offers the advantage of revealing similarities between classes [49]. There are many DT algorithms available in Data Mining, the most common are Classification and Regression Trees (CART) [11], Iterative Dichotomiser 3 (ID3) [53] and C4.5 [54] which use different splitting criteria for splitting the node at each level to form a homogeneous node. For instance, CART uses the Gini index, whereas ID3 uses information gain (entropy) and C4.5 the Gain Ratio. When building a classification tree, the splitting phase continues until a stopping criterion is triggered. Some common stopping rules conditions are listed below [65]: 1. All variables in the training set belong to a single value of Y. 2. The maximum tree depth has been reached. 3. The number of observations in the terminal node is less than the minimum number of observations for parent nodes. 4. The best splitting criteria is not greater than a certain threshold. A tree can be grown to be quite large, almost to the point where it fits the training data perfectly, resulting in overfitting. The model that overfits predicts very well the training data but poorly on 23 independent test sets, resulting in poor predictions. One way to prevent overfitting is to limit tree growth by setting some rules at the beginning, before overfitting occurs [1]. A preferred approach is to grow an overly large tree until some minimum node size is reached, and then prune the tree back to an optimal size. Optimal size can be determined using an independent test set or crossvalidation [49]. Although some research papers state that pruning might be helpful with imbalanced data sets in some circumstances [14], other papers conclude that it should be avoided. Most pruning schemes, including the one used by C4.5, attempt to minimize the overall error rate. And so they can be detrimental to the minority class, since reducing the error rate in the majority class, which stands for most of the observations, would result in a greater impact over the overall error rate. On the contrary, it still seems to be unclear if pruning can lead to a performance improvement for decision trees grown over artificially balanced data sets [6]. Decision trees are effective forms to represent and evaluate the performance of algorithms due to its simplicity, comprehensibility, no parameters, and being able to handle mixed-type data [65]. But despite its popularity, this technique also presents some disadvantages: the optimal decisionmaking mechanism can be deterred and incorrect decisions can follow; it needs a large dataset to construct a good performance classifier; the possibility of overfitting which results in high variance; and they’re also relatively expensive, from a computational perspective, as they need to identify splits for multiple variables [37]. The basic characteristics of the three algorithms mentioned earlier, CART, ID3 and C4.5, are explained in Table 3.1. Among all the available learning algorithms of DT, the CART strategy is known to be one of the most successful techniques [23]. Thereby this study will employ the CART algorithm. Classification and Regression Trees (CART) CART is a nonparametric procedure that stands for Classification and Regression Trees [11]. It is characterized by the fact that it develops binary trees, namely the parent nodes are always split into two child nodes, and the process is repeated by treating each child node as a parent node. This is called binary recursive partitioning. This process is repeated until further partitioning is impossible or is limited by some criterion. Once the first terminal node has been created, the algorithm repeats the procedure for each set of observations until all observations are categorized 24 (where K≥2), an entry, Ck,j indicates the number of observations of class kthat are labeled by the classifier as class j. For a classifier to have good accuracy, ideally most of the observations would be represented along the diagonal of the CM, from entry C1,1to entry CK,K with the rest of the entries being zero or close to zero. As for the measure itself, the accuracy of a classifier determines the number of correctly predicted class labels in relation to the total number of predictions (Equation 3.18). The accuracy for each class k is determined as: [ ACC(k) = TN +T P FP +T N +F N +T P (3.18) Conventionally, multi-class accuracy is the average of the different classes’ accuracy. [ ACC =1 K K X k=1 [ ACC(k)(3.19) Overall, this is an important measure for evaluating the quality of a model, but it’s insufficient, especially in cases where there’s an imbalanced distribution of the class. In these situations, accuracy can be misleading since the dataset contains significantly more majority class instances than minorities. [58]. For instance, a classifier would be able to achieve an accuracy of 90% in a dataset where there is a 90/10 distribution of the target variable simply by predicting all values as of the majority class, and such a classifier would not be useful [43]. Sensitivity and Precision Sensitivity (S), also known as recall, measures the true positive recognition rate, i.e. , the proportion of positive values that are correctly identified (Equation 3.20). S=TP TP +F N (3.20) For multi-class problems, applying the macro method, sensitivity can be determined as: MacroS=1 K K X k=1 TP(k) TP(k)+F N(k) (3.21) where Kis the total number of classes. A perfect sensitivity score of 1 for a given class kmeans that every item from that class was labeled as such, however it does not give any information on how many observations were incorrectly 31 labeled as belonging to Ck. Overall, sensitivity should be optimized if the aim is to decrease the number of false negatives [26]. Precision (P) is the proportion of observations labeled as positive that are actually such (Equation 3.22). P=TP TP +F P (3.22) Identical to sensitivity, applying the macro method for multi-class, precision can be determined as: MacroP=1 K K X k=1 TP(k) TP(k)+F P(k) (3.23) A perfect precision score of 1 for a class kmeans that every observation that the classifier labeled as belonging to class kdoes indeed belong to that class. However, it does not give any information about the number of class kobservations that the classifier mislabeled. In general, the model for precision should be optimized when the goal is to decrease the number of false positives [26]. F1-Measure Usually, there is a trade off between the precision and sensitivity measures. Trying to improve one measure often results in a deterioration of the other measure. The F1-measure represents the harmonic mean between sensitivity and precision values, as it gives equal weight to both measures [32]. F1=2×P×S P+S=2×TP 2×TP +F P +F N (3.24) This metric ranges between 0 to 1, where the value of 1 indicates perfect precision and sensitivity. When one of the metrics assume values close to 0, the final F score suffers a huge drop, since the harmonic mean tends to give more weight to lower values [25]. The macro averaged F1-measure is determined by calculating the F1-measure of every class and then average them. MacroF1=PK k=1 F1k K(3.25) 32 In summary, the accuracy measure works better when the data classes are fairly evenly distributed. The other measures, such as sensitivity, precision, and F1-measure are better suited upon an imbalanced class problem, where the main class of interest is rare [26]. ROC and AUC A ROC graph is a technique for visualizing, organizing and selecting classifiers based on their performance. ROC graphs are two-dimensional graphs in which, for a given classifier, the TP rate, also known as sensitivity ( T P T P +F N ), is plotted on the Y axis and the FP rate ( F P F P +T N ) is plotted on the X axis. A ROC graph depicts relative tradeoffs between benefits (TP) and costs (FP) [20]. Many binary classifiers, such as decision trees, are designed to produce only a class decision, i.e. , a Yes or No on each variable. They are designated as discrete classifiers. When such classifiers are applied to a test data set, they yield a CM, which in return corresponds to one ROC point. Thus, a discrete classifier produces only a single point in ROC space. The point (0, 1) represents perfect classification (Figure 3.8). Informally, one point in ROC space is better than another if it is to the northwest (TP rate is higher, FP rate is lower, or both) of the first. The lower left point (0, 0) represents the strategy of never issuing a positive classification; such a classifier commits no FP errors but also gains no TP. Moreover, the upper right point (1, 1), unconditionally issues positive classifications [20]. In turn, some classifiers, such as a Naive Bayes classifier, naturally yield an instance probability that represents the degree to which an instance is a member of a class. As such, TP and FP can vary as the threshold on the output varies between its extremes (0 and 1). The resulting curve is called the ROC curve [33]. In case of multi-class problems, they can be handled by producing one ROC for each class. To compare classifiers, a common method is to calculate the Area Under the ROC Curve (AUC), which is the surface between the ROC curve and the horizontal axis. This method is a good measure to reflect quality as ROC curves that are more to the northwest are better and have a bigger surface. AUC values are often used as a single evaluation metric in imbalanced classification problems [1]. The AUC ranges between 0 and 1. When the AUC is approximately 0.5 (called a random classifier), the model has no discrimination capacity to distinguish between positive class and negative class, so no realistic classifier should have an AUC less than 0.5. One approach to calculating multi-class AUC is described in [64] as: 33 Figure 3.8: ROC curve of three classifiers: A, B and random. Reprinted from [10]. AUCtotal =X ck∈K AUC(ck)·prev(ck)(3.26) where Kis the total number of classes, AUC(ck)denotes the AUC for class reference, and prev(ck)the prevalence of ckin the data, which can be calculated as prev(ck) = ck/Nwhere ckis the number of positive labels and Nthe total number of observations. The AUC has a known statistical meaning: it is equivalent to the Wilconxon test of ranks, and is equivalent to several other statistical measures for evaluating classification and ranking models [6]. In [27], the authors point out that Gini + 1 = 2 ×AUC [20]. Brier Score The Brier Score is a calibration metric that measures how close the predictions (ˆp) are to the true classification (p) of an event. This score ranges between 0 and 1. Let Cj∈Cbe the class j and Cthe set of all possible classes, for binary classification problems the score is defined as [64]: ˆ Brier(Cj) = 1 N N X i=1 (pi j−ˆpi j)2(3.27) 34 where pi jand ˆpi jdenote the actual Cjoutcome (0 or 1) for observation iand respective prediction. Following the multi-class AUC metric in 3.26, the multi-class Brier score approach is defined as Briertotal =X ck∈K Brier(ck)·prev(ck)(3.28) The lower the value of the score, the better is the calibration and so the better the model. The perfect model presents a Brier score of 0. 35 Chapter 4 Data Understanding and Preparation The NPS is used to measure, understand, and track customer experience. In that sense, the more data we collect and analyse alongside the NPS score, the more we will be able to understand what is driving the customer experience, allowing to prioritise improvements that have the biggest impact on the customers. The following chapter will detail the procedures of understanding, preparing and analysing the collected data. These procedures were conducted using SQL, R and Python programming languages to extract and merge data from the surveys and Cartão Continente database, followed by data analysis performed through R and Excel. 4.1 Data Set in Study The data set in study is a combination of both survey data and loyalty card data. Our analysis takes advantage of an individual-level match of Cartão Continente loyalty card transactions using a customer identifier. Observing first-party data from both domains is an unique opportunity to obtain more knowledge about the customer and their purchasing habits. 4.1.1 Data Collection To build the data set, we decided that the main unit to analyse would be each individual answer of the survey. With that in mind, the objective at this stage was to build a dataframe where each row would correspond to one answer from a customer and each column would represent different 36 Figure 4.1: Distribution of answered surveys by year. variables regarding the customer itself. Survey data The survey data was collected from September 2019 to December 2021, by an external company. The survey was conducted by calling customers that had recently visited a Note store and asking ”To what extent are you willing to recommend a Note store to a friend or family? On a zero - would absolutely not recommend -, to a ten - would absolutely recommend - scale.”. Through the survey answers, a data set was built with 44 variables, which can be categorized as: (i) Demographic data, (ii) Store data; (iii) Dates of the inquiry and the customer’s last visit to the store; (iv) NPS rating score; and (v) Customer experience. The resulting data set refers to 25 months with approximately 562 observations each (Figure 4.1). Due to Covid lockdown and consequently stores closing up, there are no observations from August to October of 2020. Each score was converted into a NPS label (see Table 2.1), and a comparison of the NPS trend (Figure 4.2) shows that the stores maintained their NPS levels throughout the years. It is important to note that the surveys were not structured in an adequate form to reproduce a cohesive analysis since not all questions were included in all years. Thus, the variables that did not have information during the entire period of the survey were removed to proceed with the study. Other variables considered non interesting to the study were also eliminated. After guaranteeing that each customer answered the survey no more than once a month, the survey data set collects 37 Figure 4.2: NPS trend in relation to time. 13367 eligible observations within 10 variables. A brief description of each variable is presented in Table 4.1. Table 4.1: Initial data set description. Total Number of Observations 13367 Initial Variables Variable Description id_cliente Customer’s account number cod_loja Store’s location code as the most recent/previous store visited by the customer data The date of the customer’s last visit data_inq Date of the inquiry DOP Operacional Direction - Regional area where the store is located (north, south, Porto, Lisbon, etc) Concept Store antiquity concept (old, intermediate, new) Gender Gender (M/F) Age Age q2 NPS rating score (0-10) NPS NPS classification label (Detractors, Passives and Promoters) 38 Loyalty card data The Cartão Continente loyalty card tracks the customer’s purchases. The data records timestamp, item code, item hierarchy information, quantity purchased, price listed, price paid, a customer identifier, a transaction identifier, a store identifier, among many other things. We were given access to all the data related to transactions, stores and products in the database of Cartão Continente. However, this data was not organised in one single data set, and so it must be mined for relevant information. An important aspect of Cartão Continente’s loyalty card is that two or more people, usually from the same household, can link their loyalty cards to the same account number. In that sense a card can be considered to be representative of a household and not just of an individual. The choice of the variables to include in the model depended both on business knowledge, which allowed the selection of the variables that are expected to be more relevant, as well as the availability of information. The chosen variables are categorized as: Customer Profile, Purchase Behaviour and Store Profile. All these variables are related to the Last 12 Months (L12M) before the survey. Customer Profile (Table 4.2) gathers variables regarding the customer. At this point an issue arose concerning the customer’s gender, because, even though customers indicated their gender whilst answering the survey, this information might not be coherent with the information on the customer’s account. We know that at the limit, an account can have both genders. In this sense, and based on the customer’s transactions, the initial survey-gathered gender variable was replaced by two dichotomous variables, GenderF (1=yes, 0=no) and GenderM (1=yes, 0= no). So, if an account has a purchase history of female-oriented products then GenderF will have the value 1, and, consequently, GenderM will have the value 0, and vice-versa. In a case when an account has a purchase history of female and male-oriented products then both variables will have the value 1. Additionally, information on the customer segments was extracted. The different segmentations profile the customers by providing a holistic view of the customer and their behaviour at Sonae MC. • The Lifestyle Segmentation ( Slifestyle ), based on the customer’s transactions, typifies the customer’s motivations and choices - why they choose a store or certain products. There are seven established groups. Groups 1 - Os Saudáveis Exigentes and 2 - Os Urbanos Sofisticados, are more focused on quality and healthy products, groups 3 - Os Pais Práticos, 39 4 - Os Generalistas Disciplinados, 5 - Os Tradicionais Frequentes, are more focused on family, groups 6 - Os Económicos Focados and 7 - Os Promocionais Atentos, drive their options based on price and promotions. • Continente Value Segmentation ( Svcontinente ) determines the value of the customer to Continente, taking into account customer loyalty and spending. There are 7 segments: 1 - Loyal Small, 2 - Loyal Medium, 3 - Loyal Large, 4 - Frequent Small, 5 - Frequent Medium, 6 - Occasional Small and 7 - Occasional Medium. • Note Value Segmentation ( Svnote ), like Continente Value Segmentation, determines the value of the customer to Note. This segmentation has 8 segments: 1 - Loyal Medium, 2 - Frequent Large, 3 - Occasional Large, 4 - Frequent Medium, 5 - Loyal Small, 6 - Occasional Medium, 7 - Occasional Small and 8 - Infrequent. . • The Lifestage Segmentation ( Slifestage ) combines socio-demographic information to infer about the customer life stage. This segmentation considers the age of the customers and whether they have dependents or not in their aggregate. There are five segments: 1 - Active Adults, 2 - Senior, 3 - Family with kids, 4 - Family with young adults and 5 - Family Supporters. Studies [47] indicate that Promoters are more loyal and more likely to purchase products than Detractors. Therefore, it is essential to collect data on the respondents’ purchases to understand their habits and economic value as customers. The Purchase Behaviour variables (Table 4.2) combine transactional and product data. These variables help us understand how and what the customer buys, which from previous business knowledge, we know these tend to be the core variables when predicting the NPS. Besides information about the customer and its purchasing habits it is imperative to have information about the company under analysis, Note’s stores. Accordingly, Store Profile (Table 4.2) integrates variables related to the customer preferential Note store, i.e., the store the customer visits the most. It is to be noted that the variables in Store Traffic and in Transactions Distribution are measured through five periods of the day. These periods are divided as follows: (1) morning, (2) lunch, (3) early afternoon, (4) afternoon, and (5) evening. So in the data set, each of these variables is represented five times, for instance, Store Traffic 1 represents the store traffic on the customer’s preferential store in the morning period. 40 Table 4.3: Summary statistics for quantitative variables. Min Median Mean Max SD CV Age D 18.00 45.00 47.15 78.00 12.48 0.26 N 18.00 44.00 45.76 79.00 12.48 0.27 P 18.00 43.00 44.40 79.00 12.39 0.28 Account Longetivity D 251.00 4329.00 3772.00 5466.00 1415.82 0.38 N 3.00 4538.00 3815.00 5467.00 1455.28 0.38 P 17.00 4406.00 3730.00 5467.00 1520.24 0.41 Gross Amount D 0.00 54.85 174.88 3469.93 352.19 2.01 N 0.00 63.06 176.58 6264.20 376.83 2.13 P 0.00 87.38 227.98 13526.45 499.15 2.19 Basket D 0.00 16.57 24.85 317.00 32.31 1.30 N 0.00 18.07 25.68 353.78 29.49 1.15 P 0.00 20.34 28.63 945.72 29.49 1.03 Quantity D 0.00 12.00 181.10 37181.00 1806.06 9.97 N 0.00 15.00 70.47 7146.00 278.46 3.95 P 0.00 21.00 93.00 25534.00 435.07 4.68 SKU D 0.00 5.00 16.59 689.00 50.53 3.05 N 0.00 6.00 14.64 896.00 30.03 2.05 P 0.00 8.00 18.73 750.00 35.17 1.88 Categories D 0.00 3.00 9.92 346.00 30.84 3.11 N 0.00 4.00 8.54 855.00 23.31 2.73 P 0.00 5.00 10.65 391.00 23.76 2.23 Transactions D 0.00 2.00 8.52 336.00 29.57 3.47 N 0.00 3.00 6.87 853.00 21.81 3.17 P 0.00 4.00 8.43 368.00 21.45 2.54 App Transactions D 0.00 0.00 0.63 32.00 2.74 4.36 N 0.00 0.00 0.64 31.00 2.04 3.21 P 0.00 0.00 1.02 189.00 4.35 4.27 Recency D 0.00 9.00 8.65 37.00 5.31 0.61 N 0.00 8.00 9.25 772.00 17.93 1.94 P 0.00 8.00 8.34 552.00 7.97 0.96 47 Figure 4.7: Histograms with density curve for the core variables - Part I. 48 Figure 4.8: Histograms with density curve for the core variables - Part II. 49 Figure 4.9: Spearman correlation matrix for the core variables. 50 To have a better understanding of the influence of the different periods of the day on the data, we studied the variables in Store Traffic and Transactions Distribution , which hold the distribution of the customer’s preferential store traffic and the distribution of the customer’s transactions for each period of the day, during the week and on weekends, respectively. For reference, the periods are divided as follows: (1) morning, (2) lunch, (3) early afternoon, (4) afternoon, and (5) evening. Figure 4.10: Distribution of store traffic for each period of the day, during the week (left) and on weekends (right). Figure 4.11: Distribution of customers transactions for each period of the day, during the week (left) and on weekends (right). These two groups of variables, Store Traffic and Transactions Distribution , are deeply interrelated since the store traffic at a given time is a consequence of the number of customers shopping at that specific time. In Figure 4.10 (left), we can notice that there are two peaks in the chart, one more prominent on the third period of the day, early afternoon, and another one on the fourth period, in the afternoon, 51 meaning these are the periods with more traffic on the stores during the week. These go in conformity with Figure 4.11 (left), which tells us that the customers tend to buy more in those periods. The same can be observed on weekends. Figure 4.10 (right) tells us the stores have more traffic in the first and third periods of the day, which matches the periods when customers make more transactions (Figure 4.10 (right)). We can conclude that the great majority of transactions during the week are made after lunch and prior to the evening and on weekends during the morning until the afternoon. As a consequence these are also the periods with more store traffic. 4.1.3 Data Preparation and Transformation The exploratory analysis presented in the previous chapter gives a first insight regarding the relevance and behaviour of each variable when predicting the NPS. In this chapter we show how to prepare and transform the data set to include in the machine learning algorithms. Handling missing values The first step in data preparation is to treat missing values. In the process of creating the data set for the study, the removal of inconsistent data and the treatment of missing data was performed in parallel. In the survey data, the percentage of missing values across study variables were 0.91% for DOP and 1.16% for the variable Concept . These missing values were handled by imputing information from Cartão Continente databases. This process started with creating a new variable with the customer’s preferential store ( fave_store ). This new variable replaces the store location ( cod_loja ) presented in the survey, which only gives information about the last store the client visited and might not match the preferential one. This way, we can get a better history of the customer store preference. Afterwards, the missing values of the variables DOP and Concept were handled by matching the customer preferential store with the designated DOP and Concept imputed from Cartão Continente databases. In cases where there was no information about the variables, due to the store closing down or out-of-date location codes, the observations were removed (1.01% of the observations). The code in R in Appendices C.1 and C.2 exemplify the execution of creating the variable fave_store and imputing missing values of the variable DOP , respectively. The process for the variable concept was similar. 52 In Loyalty card data, there were several variables with missing values. This was already expectable since Note’s stores have a low penetration rate, meaning that many customers shop at Note but do not use their loyalty cards. As a consequence, there is no available information about the customer, their habits and transactions. As we know that the customers who were surveyed visited a Note store, the situations where there are missing values are equally important to be analysed. In the case of categorical variables, the missing values were categorized into a new segmentation - No Value. In the case of numerical variables the existence of missing values meant, for example, that the customer had no purchases in that period and these cases were replaced by zero. Variable Construction In order to get more significant variables to train the models with, we engineered new variables from already existing ones. This process is denominated Variable Construction. By adding derived variables, beside enriching the data, this process can potentially capture relevant and explicit relationships that would otherwise be implicit and difficult to comprehend. The first engineered variables were created to shorten the periods from which we were extracting the data. That is, we seek to analyze the Purchase Behaviour variables (4.2) considering periods close to the customer’s last transaction. With that, all variables were extracted for the Last 6 Months (L6M), the Last 3 Months (L3M) and the Last Month (LM) before the survey. So, each variable will be represented four times, one for each time period. For instance, each observation has the number of transactions of the previous 12 months (N Transactions L12M), the previous 6 months (N Transactions L6M), the previous 3 months (N Transactions L3M) and the previous month (N Transactions LM) of the survey. Moreover, to create more variability between the data, the mean, standard deviation, maximum and minimum of some of the Purchase Behaviour variables for the four time periods were also added as variables. In particular, for the variables Basket , Quantity , SKU , Price , Categories and Subcategories (see Appendix C.3). Table 4.4 illustrates an arbitrary example of some of these variables for a single observation (a row in the data set), which for an easier understanding, is displayed in a table divided by time period. For instance, for one observation, the variable Quantity Mean for the previous year (L12M) will be the number of products bought ( Quantity ) divided by the number of transactions of the previous year. The final data set can be consulted in Appendix A. 53 Table 4.4: An illustrative example of some Purchase Behaviour variables for one observation of the data set in different time periods. Time Period Quantity N SKU N Transactions Quantity Mean = Quantity/ N Transactions Quantity Max Quantity Min N SKU Mean = N SKU/ N Transactions … L12M 18 6 3 6 12 3 2 ... L6M 12 4 1 12 12 12 4 ... L3M 0 0 0 0 0 0 0 ... LM 0 0 0 0 0 0 0 ... One-Hot Encoding for categorical variables Although the CART decision tree algorithm handles both categorical and numerical variables, the partitioning algorithm tends to favour categorical predictors with many levels k. That is, the number of partitions grows exponentially in k, and the more choices we have, the more likely we can find a good one for the data at hand. That can lead to overfitting, and such variables should be avoided [28]. Thus, a complete search of the possible splits is only practical for categorical variables with few categories. Additionally, in [34] the authors found that the accuracy of the results of the random forest algorithm was improved by the use of the One-Hot encoding method. Therefore, as a matter of efficiency, the categorical variables were transformed into several variables through One-Hot encoding. An example of this transformation can be seen on Table 4.5. Table 4.5: Example of one-hot-encoding: variable DOP is transformed into 6 dummy variables Observation DOP Observation DOP_norte DOP_porto DOP_centro DOP_lisboa DOP_sul DOP_insco 1 porto 1 0 1 0 0 0 0 2 lisboa ⇒2 0 0 0 1 0 0 3 lisboa 3 0 0 0 1 0 0 4 centro 4 0 0 1 0 0 0 Training and Testing data set Training and test data sets are two different but important parts in machine learning. The training set is used for the algorithm to learn how to classify the customers. While, the testing set is kept isolated, to be used just at the end of the modelling procedure to estimate the performance of the chosen model, removing the overfitting effect, i.e. the increase in performance that the 54 algorithm has on the observations it has based its learning on. There are different methods for splitting the dataset. We chose to use a common one, where 70% of the data set was randomly chosen for training (n=9222), and the remaining 30% for testing (n=3953). Balancing data set Considering the Detractors the minority class (3.40%) and the Promoters the majority class (70.75%), with an imbalanced ratio of 20.82, the data set is extremely imbalanced Table 4.6 presents an overview of the imbalanced data set. The presented values were multiplied by a random factor due to data privacy issues. Table 4.6: Imbalanced data set overview. Observations Variables Classes Majority Class (Maj) Minority Class (Min) Imbalance ratio (R= NMaj /NMin) Data set 13175 371 {D,N,P} P (9321) D (448) 20.81 Directly training a ML model with an imbalanced data set can result in good performance for the majority class but poor performance for the minority class [61]. To handle the imbalance problem, we decided to apply several well known resampling approaches to the training set at each iteration, such as Random Oversampling (ROS), Random Undersampling (RUS) and SMOTE, and compare their results. These methods were applied as a way to achieve a balanced data set. This decision was motivated by the results in [74], in which it is shown that when AUC is used as performance measure, the best class distribution for learning tends to be near a balanced class distribution. Table 4.7 describes the distribution of the training set per class after each technique was applied. Table 4.7: Distribution per class of the training set after each technique. Techniques D N P Total Original 309 2379 6534 9222 ROS 6534 6534 6534 19602 RUS 309 309 309 927 SMOTE 3074 3073 3074 9221 55 These approaches were performed with the UBL package of R. The libraries used were RandOverClassif for ROS, RandUnderClassif for RUS and SmoteClassif for SMOTE. 56 Figure 5.2: OOB error rate vs. number of trees. Table 5.3: Comparison of the classification metrics for Random Forest model. Model AUC BRIER ACC macroS macroP macroF1 Original 0.52 0.21 0.71 0.34 0.49 0.28 ROS 0.54 0.24 0.62 0.35 0.49 0.34 RUS 0.53 0.31 0.36 0.37 0.35 0.29 SMOTE (HEOM) 0.55 0.26 0.56 0.36 0.35 0.35 SMOTE (HVDM) 0.55 0.26 0.56 0.36 0.36 0.36 measure of node impurity, the highest the impurity means that each node contains only observations of a single class. Assessing the mean decrease in Gini when the variable is omitted leads to an understanding of how important that variable is to the homogeneity of the nodes, therefore, the higher the value of mean decrease Gini, the greater the importance of the variable. The relative importance for the top 10 variables of the model with the SMOTE (HVDM) method is shown in Figure 5.3. 63 Figure 5.3: Relative importance of the top 10 variables. From Figure 5.3 we can note that the variable regarding the customer’s account longevity ( account_longevity ) contributes the most to the method’s accuracy. The age of the customer also ranks high in terms of relative importance. A few variables related to the store traffic also appear to have an impact on predicting the customer’s NPS, namely, the traffic on the weekends on the second (lunch), third (early afternoon) and first (morning) periods of the day, and during the week on the fourth (afternoon) and second (lunch) periods. These variables have a similar importance to the variables related to the customer’s purchase habits, particularly, the percentage of transactions in the third, second and fourth period of the day during the week. After the most relevant variables have been identified, the next step is to attempt to understand the nature of their dependence with the response variable [28]. Albeit the relative variable importance evaluates the overall impact of each variable in the method’s accuracy, it does not indicate the influence of the variables values. Hence, we proceed with a further analyse of the variables through a Partial Dependence Plot (PDP). A PDP illustrates the marginal effect of the selected variables on the response after integrating out the other variables [35]. Considering the example of the PDP of the variable Account Longevity , it illustrates what the impact would be in the response variable, all other variables being equal, of the amount of time a consumer has had the account. On another note, a PDP can have both negative and positive values in the y-axis. The negative values illustrate 64 that the class in question is less likely for that value of the independent variable (x-axis), according to the model, whereas positive values indicate that the class in question is more likely for that value of the independent variable. At last, zero implies no average impact on class probability. An analysis of the top three most important variables is detailed in Figure 5.4a for class Detractors and Figure 5.4b for the class Promoters , on account of these being the key classes that influence the NPS score (Equation 2.1). For the class Detractors , the PDP has negative values in the y-axis, meaning that the more negative the value, the less likely it is that that variable influences the response variable. Whilst for the Promoters , the y-axis has positive values, indicating that the more positive the values, the higher the likelihood of that variable influencing the response variable. By looking at the influence of the customer’s account longevity on the prediction as Detractors 5.4a (left), we can observe that the longer a customer has had the account, it is less likely to be classified as Detractor . Whereas, looking at the influence on the class Promoters (Figure 5.4b (left)), the longer the account longevity, the more likely it is to be predicted as a Promoter . This result is in line with the Promoters ’ characteristics which are typically very satisfied customers and loyal to the company and, therefore, long-term customers. The second most important variable represents the store traffic during the second period of the day on weekends. Analysing Figure 5.4a (centre) we can notice that the higher the store traffic in that period, the more chances of being predicted as a Detractor . In Figure 5.4b (centre) we can remark that the lower the store traffic, the more likely it is to be predicted as a Promoter . As observed in Figure 4.11 (right), the majority of transactions are made until the afternoon, and the stores tend to be busier during the first and third periods of the day (Figure 4.10 (right)). From that, we can deduce that the customers who buy in the second period of the day are most likely to have a less busy store and, as a consequence, a better buying experience, leaving them more satisfied and more likely to recommend the store. Therefore, the customers who shop during the second period of the day on weekends with low store traffic have a better chance of being predicted as Promoters and lower chance of being predicted as Detractors . Lastly, the PDPs for the variable Age (Figure 5.4a (right) and Figure 5.4b (right)), indicate that the older the customer, the bigger the probability of being predicted as Detractor , whereas the younger the customer, the bigger the probability of being predicted as a Promoter . 65 (a) Partial dependence plot for class D – variables Account Longevity , Store Traffic Weekends Period 2 and Age . (b) Partial dependence plot for class P – variables Account Longevity , Store Traffic Weekends Period 2 and Age . Figure 5.4: Partial Dependence plots for the classes Detractor (D) and Promoter (P) 5.3 Error Analysis Even though RF algorithms leverage the power of multiple DT for making decisions, the RF classifier still failed to reach AUC-measures higher than 0.55. To understand further the challenges of the task, an error analysis was performed on its results. An error analysis helps to convey insights on how to improve the model’s performance by diagnosing erroneous predictions, as well as identify if the model is behaving more erroneously for certain variables or classes. In this section the analysis is divided by NPS class, year, NPS score and misclassified Detractors. 66 5.3.1 By NPS Class We start this diagnosis by analysing the errors per NPS class. Table 5.4 shows the classification error rates per class for the final data set for the different resampling methods. Along with the error rates per class, the overall error rates, the OOB error rate for the train set and the test set error rate for the random forest classifier were also added. Table 5.4: Summary of error rates in training and testing data set. Model Train set Classification Error OOB Error Rate (%) Test set Classification Error Test set Error Rate (%) D N P D N P Original 1.00 1.00 0.00 29.27 1.00 0.99 0.00 29.42 ROS 0.00 0.09 0.18 9.14 0.94 0.85 0.17 37.67 RUS 0.55 0.77 0.69 66.88 0.46 0.72 0.67 63.93 SMOTE (HEOM) 0.04 0.41 0.39 28.04 0.97 0.57 0.37 44.57 SMOTE (HVDM) 0.03 0.39 0.37 26.24 0.97 0.57 0.36 43.74 The error rates in the original model reflect the importance of, not only analysing the overall error rates but also the errors per class. Especially in imbalance data sets, the overall error rate can be misleading towards the model’s performance. For instance, the original data set has an imbalance class distribution, reflecting a significant majority class ( Promoters ), so, as expected, for both the train and test set, the classifier predicts with practically no error the class Promoters , which results in a low overall error rate. However, it misclassifies almost every observation in the classes Passives and Detractors , reflecting the model’s poor performance for the minority classes. For the method ROS, albeit with low classification errors and OOB error rate (9.14%), the classification errors in the test set for the classes Detractors and Passives is very high, 0.94 and 0.85, respectively. The same situation can be observed for the method SMOTE, for both distances, where the error rates in the train set are low, but for the test set are very high for the minority class (97% for both methods). This difference in error rates in the train versus test data set can be explained by optimistic error rates in the train set, since the model is not tested on any observations that it has not already seen. By contrast, the method RUS presents higher error rates for both the train and test set. Regardless, it gives a more feasible variation between the train and test data set clas- 67 sification errors. We can conjecture that the high error rates in this method are due to the small amount of observations it has available, which, in consequence, worsens the predictions and the error rates. Lastly, one obvious conclusion drawn from the results in Table 5.4 is that, overall, in unseen data, the model cannot correctly classify the minority class, the Detractors . In the case of this classification problem, the RF model generates three probabilities, one for each NPS class. The predicted probabilities are pooled from different trees, and based on the majority vote in each sample, a class is predicted, namely, the class with higher predicted probability. For instance, if a given observation has a predictive probability of 0.2 for being a Detractor , 0.3 for Passive and 0.5 for Promoter , the observation would be classified as a Promoter . For a more detailed analysis, we decided to assess the precision rate for different thresholds of the predicted probabilities for each NPS class (Figure 5.5). For that, we used the predicted scores of the model with the RUS method. In each graphic is represented the distribution of the number of observations predicted in that NPS class, i.e., the True Positive (TP) and False Positive (FP) observations. The predicted probabilities of each observation were divided into 10 classes with a range of 0.1 (e.g., probability class 1 = [0,0.1[, probability class 2 = [0.2,0.3[, etc), creating different classes of probabilities, where the higher the class, the higher the predicted probability of an observation belonging to that particular NPS class. The precision rate is represented as a line, and corresponds to the percentage of observations correctly labeled as that particular class, i.e., the percentage of TP observations. In Figure 5.5a are represented the predicted probabilities of each observation predicted as a Detractor . By looking at the precision rate (orange line), we can see that the model’s precision rate is very low for every probability class, not even reaching 5%, and totally failing its prediction for the observations that have an higher predictive probability of being Detractors . With this we can conclude that the model has great difficulty in predicting the class Detractors . In the case of the class Passives (Figure 5.5b) we can observe that the precision rate is also low, and there is not much variability between the different thresholds, indicating the difficulty of the model in predicting this class as well. On the other hand, for the class Promoters (Figure 5.5c) we can observe that the precision rate increases as the probabilities classes get higher, despite a small decrease in class 7. Nevertheless, the tendency for the Promoters is that the higher the probability, the higher the precision of the model in predicting the observations as Promoters . This analysis corroborates what has been concluded before, that the model has difficulty in dis- 68 tinguish the minority classes, the Detractors , followed by the Passives , whilst having a low difficulty in predicting the Promoters . 5.3.2 By Year In a second stage, we decided to analyse the error per year. As mentioned in Section 4.1.1, the survey was conducted from september 2019 to december 2021, having 3 interrupted months in 2020. During that time the structure of the survey was also modified a few times. In order to assess if these modifications and discrepancies between the answers gathered throughout the years could influence the model’s performance, a random forest classifier with random undersampling (RUS) was applied to the final data set for each year. The results in Table 5.5 for the three models show that regardless of the year, the classifier has a high classification error, on both train and test sets, for the classes Detractors and Passives , and a low classification error for the class Promoters , which goes in accordance with the results previously analysed. Thereupon, one can conclude that the error does not improve with any particular year. Table 5.5: Summary of error rates in training and testing data set per year. Year Train set Classification Error OOB Error Rate (%) Test set Classification Error Test Set Error Rate (%) D N P D N P 2019 0.84 0.63 0.26 57.57% 0.99 0.74 0.33 68.17% 2020 0.88 0.67 0.21 58.83% 0.96 0.72 0.27 64.97% 2021 0.88 0.69 0.19 58.50% 0.97 0.72 0.25 64.40% 69 (a) (b) (c) Figure 5.5: Model’s precision for each predictive probability threshold per observation for the class (a) Detractor , (b) Passive and (c) Promoter . 70 5.3.3 By NPS Score The Net Promoter Score is measured in a scale from 0 to 10, where the customers that give out a score between 0 and 6 are classified as Detractors , 7 to 8 are Passives and 9 to 10 Promoters . As previously concluded the classifiers have much difficulty in predicting the class Detractor . And since this class is wider than the remaining ones, we sought to analyse if the model tends to misclassify the Detractors similarly for all scores. Or, if on the contrary, it tends to have worst performance in the class’s limits, in particular, for the higher scores close to the Passives scores. For this analysis the random forest classifier with the method RUS was used. In Figure 5.6 is represented the distribution of observations per NPS score for the Detractors , and the respective success rate (orange line). The first thing to note is that the model misclassifies every observation with scores 0 and 1. This can be explained by the small amount of observations in those scores, which impacts the model’s performance substantially. For the remainder scores, one can see that the success rate for the higher scores is much lower than for the middle scores. Applying the same analysis to the scores of the classes Passives and Promoters (Figure 5.7), it can be observed that the success rate is quite similar for all scores, not depicting the behaviour observed for the class Detractors . That being said, it can be concluded that for the class Detractors , the model has a bigger challenge in predicting the observations when the scores are 5 or 6. For a more in-depth review of such cases, we filtered the observations with a NPS score of 5 and 6 and analysed the answers from the survey. Along with the NPS score, some customers added a note about their rating, where a few stated that their score was intermediate and even high. Thenceforth we can surmise that the scores are highly subjective, and a score of 5 and 6 for some customers can imply a ’good’ score. This goes under what was observed in Figure 5.6, since some customers can be classified as Detractors but have a receptive attitude towards the store and its products, and so their overall behaviour can lead the model to misclassify them into another class. 5.3.4 Misclassified Detractors Lastly, we analysed the observations belonging to the class Detractors that were misclassified. Whilst answering to the survey, the customers who gave a NPS score below 7 (the Detractors ) were also asked to name a few reasons on why they would not be so willing to recommend a Note store. In a more superficial analysis, a visual representation of the words that appeared more often 71 Figure 5.6: The distribution of observations per NPS score for the class Detractors , and the respective success rate. Figure 5.7: The distribution of observations per NPS score for the classes Passives and Promoters , and the respective success rate. in the comments is represented in a word cloud in Figure 5.8. By analysing Figure 5.8 we can observe that the most relevant words are related to the service ( atendimento ), that was bad and slow; the waiting time ( tempo de espera ) that was long; the prices for being high ( preços elevados ) and the store’s limited range of products ( pouca variedade ). According to the definition in [22], these features are related to customer experience, since they originate from a set of interactions between the customer and the products and services provided by Note, and not necessarily with their loyalty. Yet, we know that positive experiences increase the 72 [10] P. Branco, L. Torgo, and R. P. Ribeiro. A survey of predictive modelling under imbalanced distributions. arXiv , 2015. [11] L. Breiman. Random forests. Machine learning , 45(1):5–32, 2001. [12] J. Brownlee. 4 types of classification tasks in machine learning, 2020. [13] J. Bughin, J. Doogan, and O. J. Vetvik. A new way to measure word-of-mouth marketing. McKinsey Quarterly , 2010. [14] N. Chawla. C4.5 and imbalanced data sets: Investigating the eect of sampling method, probabilistic estimate, and decision tree structure. In Proceedings of the ICML , volume 3, page 66, 2003. [15] N. V. Chawla, K. W. Bowyer, L. O. Hall, and W. P. Kegelmeyer. Smote: Synthetic minority over-sampling technique. Journal of Artificial Intelligence Research , 16:321–357, 2002. [16] N. V. Chawla, N. Japkowicz, and A. Kotcz. Editorial: Special issue on learning from imbalanced data sets. Association for Computing Machinery , 6(1):1–6, 2004. [17] J. A. Chevalier and D. Mayzlin. The effect of word of mouth on sales: Online book reviews. Journal of Marketing Research , 43(3):345–354. [18] R. De Oliveira, R. C. Fernandes Araújo, F. Barros, A. Segundo, R. Zampolo, W. Fonseca, V. Dmitriev, and F. Brasil. A system based on artificial neural networks for automatic classification of hydro-generator stator windings partial discharges. Journal of Microwaves, Optoelectronics and Electromagnetic Applications , 16:628–645, 2017. [19] G. Douzas, F. Bacao, J. Fonseca, and M. Khudinyan. Imbalanced learning in land cover classification: Improving minority classes’ prediction accuracy using the geometric smote algorithm. Remote Sensing , 11(24):3040, 2019. [20] T. Fawcett. An introduction to roc analysis. Pattern Recognition Letters , 27(8):861–874, 2006. [21] S. Garcia, J. Luengo, and F. Herrera. Data Preprocessing in Data Mining . Springer, 2015. 79 [22] C. Gentile, N. Spiller, and G. Noci. How to sustain the customer experience:: An overview of experience components that co-create value with the customer. European Management Journal , 25(5):395–410, 2007. [23] M. M. Ghiasi, S. Zendehboudi, and A. A. Mohsenipour. Decision tree-based diagnosis of coronary artery disease: Cart model. Computer Methods and Programs in Biomedicine , 192, 2020. [24] R. Goldschmidt and M. Passos. Data Mining: Um Guia Prático . Elsevier Editora Ltda., 2005. [25] M. Grandini, E. Bagli, and G. Visani. Metrics for multi-class classification: an overview. arXiv , 2020. [26] J. Han, M. Kamber, and J. Pei. Data Mining: Concepts and Techniques . Morgan Kaufmann, 2011. [27] D. J. Hand and R. J. Till. A simple generalisation of the area under the roc curve for multiple class classification problems. Machine Learning , 45:171–186, 2001. [28] T. Hastie, R. Tibshirani, and J. Friedman. The Elements of Statistical Learning . Springer, 2009. [29] N. Hill, G. Roche, and R. Allen. Customer Satisfaction: The customer experience through the customer’s eyes . Cogent Publishing, 2007. [30] U. R. Hodeghatta and U. Nayak. Business Analytics Using R - A Practical Approach . Apress, Berkeley, 2017. [31] M. B. Holbrook and E. C. Hirschman. The experiential aspects of consumption: Consumer fantasies, feelings, and fun. Journal of Consumer Research , 9(2):132–140, 1982. [32] M. Hossin and S. M.N. A review on evaluation metrics for data classification evaluations. International Journal of Data Mining Knowledge Management Process , 5(2):1–11, 2015. [33] J. Huang and C. X. Ling. Using auc and accuracy in evaluating learning algorithms. IEEE Transactions on Knowledge and Data Engineering , 17(3):299–310, 2005. 80 [34] A. Y. Hussein, P. Falcarin, and A. T. Sadiq. Enhancement performance of random forest algorithm via one hot encoding for iot ids. Periodicals of Engineering and Natural Sciences (PEN) , 9(33):579–591, 2021. [35] G. James, D. Witten, T. Hastie, and R. Tibshirani. An Introduction to Statistical Learning with Applications in R , volume 103. Springer, 2013. [36] D. R. Jeske, T. P. Callanan, and L. Guo. Identification of key drivers of net promoter score using a statistical classification model. [37] B. Jijo and A. Mohsin Abdulazeez. Classification based on decision tree algorithm for machine learning. Journal of Applied Science and Technology Trends , 2(1), 2021. [38] V. Kumar, V. Chattaraman, C. Neghina, B. Skiera, L. Aksoy, A. Buoye, and J. Henseler. Data‐driven services marketing in a connected world. Journal of Service Management , 24(3):330–352, 2013. [39] V. J. Lei, E. H. Kennedy, T. Luong, X. Chen, D. E. Polsky, K. G. Volpp, M. D. Neuman, J. H. Holmes, L. A. Fleisher, and A. S. Navathe. Model performance metrics in assessing the value of adding intraoperative data for death prediction: Applications to noncardiac surgery. Studies in Health Technology and Informatics , 264:223–227, 2019. [40] A. Liaw and M. Wiener. Classification and regression by randomforest. R News , 2(3):18–22, 2002. [41] G. S. Linoff and M. J. A. Berry. Data Mining Techniques: For Marketing, Sales, and Customer Relationship Management . Wiley, 2011. [42] M. R. Longadge, S. S. Dongre, and D. L. Malik. Class imbalance problem in data mining: Review. 2(1), 2013. [43] V. López, A. Fernández, and F. Herrera. On the importance of the validation technique for classification with imbalanced datasets: Addressing covariate shift when data is skewed. Information Sciences , 257:1–13, 2014. 81 [44] M. Madaan, A. Kumar, C. Keshri, R. Jain, and P. Nagrath. Loan default prediction using decision trees and random forest: A comparative study. IOP Conference Series: Materials Science and Engineering , 1022(1), 2021. [45] P. C. Mandal. Net promoter score: a conceptual analysis. International Journal of Management Concepts and Philosophy , 8(4):209–219, 2014. [46] R. G. Mantovani, T. Horváth, R. Cerri, S. B. Junior, J. Vanschoren, and A. C. P. d. L. F. de Carvalho. An empirical study on hyperparameter tuning of decision trees. arXiv , 2018. [47] I. Markoulidakis, I. Rallis, I. Georgoulas, G. Kopsiaftis, A. Doulamis, and N. Doulamis. A machine learning based classification method for customer experience survey analysis. Technologies , 8(4):76, 2020. [48] F. Martínez-Plumed, L. Contreras-Ochando, C. Ferri, J. H. Orallo, M. Kull, N. Lachiche, M. J. R. Quintana, and P. A. Flach. Crisp-dm twenty years later: From data mining processes to data science trajectories. IEEE Transactions on Knowledge and Data Engineering , 33(8):3048–3061, 2021. [49] G. G. Moisen. Classification and Regression Trees , volume 1. Academic Press, Oxford, 2008. [50] K. P. Murphy. Machine Learning: A Probabilistic Perspective . The MIT Press, 2012. [51] E. Ngai, L. Xiu, and D. Chau. Application of data mining techniques in customer relationship management: A literature review and classification. Expert Systems with Applications , 36(2):2592–2602, 2009. [52] P. Probst, M. N. Wright, and A.-L. Boulesteix. Hyperparameters and tuning strategies for random forest. WIREs Data Mining and Knowledge Discovery , 9(3), 2019. [53] J. R. Quinlan. Induction of decision trees. Machine learning , 1(1):81–106, 1986. [54] J. R. Quinlan. C4.5: Programs for Machine Learning . Morgan Kaufmann Publishers, 1993. [55] F. Reichheld and R. Markey. The Ultimate Question 2.0: How Net Promoter Companies Thrive in a Customer-Driven World . Harvard Business Review Press, 2011. 82 [56] F. F. Reichheld. The one number you need to grow. Harvard Business Review , 81(12):46–55, 2003. [57] L. Ren, H. Qiu, P. Wang, and P. M. C. Lin. Exploring customer experience with budget hotels: Dimensionality and satisfaction. International Journal of Hospitality Management , 52:13–23, 2016. [58] L. Rokach and O. Maimon. Data Mining with Decision Trees Theory and Applications . World Scientific, 2014. [59] G. Sanson, J. Welton, E. Vellone, A. Cocchieri, M. Maurici, M. Zega, R. Alvaro, and F. D’Agostino. Enhancing the performance of predictive models for hospital mortality by adding nursing data. International Journal of Medical Informatics , 125:79–85, 2019. [60] M. Schauerhuber, A. Zeileis, D. Meyer, and K. Hornik. Benchmarking open-source tree learners in r/rweka. Studies in Classification, Data Analysis, and Knowledge Organization. Springer, 2008. [61] F. Shakeel, A. S. Sabhitha, and S. Sharma. Exploratory review on class imbalance problem: An overview. In 2017 8th International Conference on Computing, Communication and Networking Technologies (ICCCNT) , pages 1–8. IEEE, 2017. [62] R. Sharda, D. Delen, and E. Turban. Business Intelligence and Analytics: Systems for Decision Support . Pearson Education, Inc., 2007. [63] C. Shearer. The crisp-dm model: The new blueprint for data mining. Journal of Data Warehousing , 5(4), 2000. [64] Á. Silva, P. Cortez, M. F. Santos, L. Gomes, and J. Neves. Rating organ failure via adverse events using data mining in the intensive care unit. Artificial intelligence in medicine , 43(3):179–193, 2008. [65] S. Singh and P. Gupta. Comparative study id3, cart and c4.5 decision tree algorithm: A survey. International Journal of Advanced Information Science and Technology , 27(27):81–106, 2014. 83 [66] M. Sridharan. Crisp-dm - a framework for data mining analysis. https:// thinkinsights.net/data-literacy/crisp-dm/, 2018. [67] C. Tantithamthavorn, S. McIntosh, A. E. Hassan, and K. Matsumoto. Automated parameter optimization of classification techniques for defect prediction models. 38th IEEE International Conference on Software Engineering. Association for Computing Machinery, 2016. [68] T. M. Therneau and E. J. Atkinson. An introduction to recursive partitioning using the rpart routines. Technical report, Technical report Mayo Foundation, 2022. [69] I. Tomek. Two modifications of cnn. IEEE Transactions on Systems, Man, and Cybernetics , SMC-6(11):769–772, 1976. [70] L. Tong, Y. Wang, F. Wen, and X. Li. The research of customer loyalty improvement in telecom industry based on nps data mining. China Communications , 14(11):260–268, 2017. [71] L. Torgo. Data Mining with R Learning with Case Studies . Chapman and Hall/CRC, 2nd edition, 2020. [72] B. Tuychiev. Comprehensive guide to multiclass classification metrics, 2021. [73] T. Waheed, R. B. Bonnell, S. O. Prasher, and E. Paulet. Measuring performance in precision agriculture: Cart — a decision tree approach. Agricultural Water Management , 84(1):173–185, 2006. [74] G. M. Weiss and F. Provost. Learning when training data are costly: The effect of class distribution on tree induction. Journal of Artificial Intelligence Research , 19:315–354, 2003. [75] D. R. Wilson and T. R. Martinez. Improved heterogeneous distance functions. Journal of Artificial Intelligence Research , 6:1–34, 1997. [76] I. H. Witten, E. Frank, and M. A. Hall. Data Mining: Practical Machine Learning Tools and Techniques . Morgan Kaufmann, 2011. [77] S. P. Yip and G. I. Webb. Empirical function attribute construction in classification learning. In Joint conference on artificial intelligence (AI’94) , pages 29–36, 1994. 84 [78] X. Zhou, P. Lu, Z. Zheng, D. Tolliver, and A. Keramati. Accident prediction accuracy assessment for highway-rail grade crossings using random forest algorithm compared with decision tree. Reliability Engineering System Safety , 200:106931, 2020. [79] R. Zhu, Y. Guo, and J.-H. Xue. Adjusting the imbalance ratio by the dimensionality of imbalanced data. Pattern Recognition Letters , 133:217–223, 2020. 85 Appendix A Variables of the Final Data set The following tables present, in more detail, the variables that were used to build the predictive models. These variables are divided into several categories: Customer Profile, Purchase Behaviour and Store Profile. A.1 Customer Profile Variables Table A.1: Predictive variables of the final data set - Customer Profile Name Description Variables Values Age Age age Account Longevity The number of years the customer has had the account account_longevity GenderF Inferred female behaviour genderF 0, 1 GenderM Inferred male behaviour genderM 0, 1 Slifestyle Lifestyle Segmentation slifestyle 1,2,3,4,5,6,7,8 Svcontinente Continente Value Segmentation svcontinente 1,2,3,4,5,6,7,8 Svnote Note Value Segmentation svnote 1,2,3,4,5,6,7,8,9 Slifestage Lifestage Segmentation slifestage 1,2,3,4,5,6 86 A.2 Purchase Behaviour Variables Table A.2: Predictive variables of the final data set - Purchase Behaviour (Part I) Name Description Variables Direct Discount Direct discount benefitted in sales and returns (%) sales_direct_disc, returns_direct_disc, sales_direct_disc_l6m, returns_direct_disc_l6m, sales_direct_disc_l3m, returns_direct_disc_l3m sales_direct_disc_lm, returns_direct_disc_lm Deferred Discount Deferred discount benefitted in sales and returns (%) sales_deferred_disc, returns_deferred_disc, sales_deferred_disc_l6m, returns_deferred_disc_l6m, sales_deferred_disc_l3m, returns_deferred_disc_l3m sales_deferred_disc_lm, returns_deferred_disc_lm Basket Sales basket: The gross amount spent in a given transaction Returns basket: The gross amount returned in a given transaction cesta_sales_media, cesta_sales_max,cesta_sales_min, cesta_sales_sd cesta_returns_media, cesta_returns_max, cesta_returns_min, cesta_returns_sd, cesta_sales_media_l6m, cesta_sales_max_l6m, cesta_sales_min_l6m, cesta_sales_sd_l6m cesta_returns_media_l6m, cesta_returns_max_l6m, cesta_returns_min_l6m, cesta_returns_sd_l6m, cesta_sales_media_l3m, cesta_sales_max_l3m, cesta_sales_min_l3m, cesta_sales_sd_l3m cesta_returns_media_l3m, cesta_returns_max_l3m, cesta_returns_min_l3m, cesta_returns_sd_l3m, cesta_sales_media_lm, cesta_sales_max_lm, cesta_sales_min_lm, cesta_sales_sd_lm, cesta_returns_media_lm, cesta_returns_max_lm, cesta_returns_min_lm, cesta_returns_sd_lm Quantity Number of items bought qty_sales_media, qty_sales_max, qty_sales_min, qty_sales_sd, qty_sales_total, qty_returns_media, qty_returns_max, qty_returns_min, qty_returns_sd, qty_returns_total, qty_sales_media_l6m, qty_sales_max_l6m, qty_sales_min_l6m, qty_sales_sd_l6m, qty_sales_total_l6m qty_returns_media_l6m, qty_returns_max_l6m, qty_returns_min_l6m, qty_returns_sd_l6m, qty_returns_total_l6m qty_sales_media_l3m, qty_sales_max_l3m, qty_sales_min_l3m, qty_sales_sd_l3m, qty_sales_total_l3m qty_returns_media_l3m, qty_returns_max_l3m, qty_returns_min_l3m, qty_returns_sd_l3m, qty_returns_total_l3m qty_sales_media_lm , qty_sales_max_lm , qty_sales_min_lm, qty_sales_sd_lm, qty_sales_total, qty_returns_media_lm, qty_returns_max_lm, qty_returns_min_lm, qty_returns_sd_lm, qty_returns_total_lm 87 Table A.3: Predictive variables of the final data set - Purchase Behaviour (Part II) Name Description Variables SKU Number of SKUs (SKU=product identifier) n_sku_total, n_sku_md, n_sku_max, n_sku_min ,n_sku_sd n_sku_total, n_sku_md, n_sku_max, n_sku_min ,n_sku_sd n_sku_total_l3m, n_sku_md_l3m, n_sku_max_l3m, n_sku_min_l3m ,n_sku_sd_l3m n_sku_total_lm, n_sku_md_lm, n_sku_max_lm, n_sku_min_lm ,n_sku_sd_lm Price Price of the product Maximum Price: preco_max_sales_md, preco_max_sales_sd, preco_max_sales_min, preco_max_sales_max preco_max_returns_md, preco_max_returns_sd, preco_max_returns_min, preco_max_returns_max, preco_max_sales_md_l6m, preco_max_sales_sd_l6m, preco_max_sales_min_l6m, preco_max_sales_max_l6m preco_max_returns_md_l6m, preco_max_returns_sd_l6m, preco_max_returns_min_l6m, preco_max_returns_max_l6m preco_max_sales_md_l3m, preco_max_sales_sd_l3m, preco_max_sales_min_l3m, preco_max_sales_max_l3m preco_max_returns_md_l3m, preco_max_returns_sd_l3m, preco_max_returns_min_l3m, preco_max_returns_max_l3m Minimum Price: preco_min_sales_md, preco_min_sales_sd, preco_min_sales_min, preco_min_sales_max preco_min_returns_md, preco_min_returns_sd, preco_min_returns_min, preco_min_returns_max (...) Average Price: preco_medio_sales_md, preco_medio_sales_sd, preco_medio_sales_max, preco_medio_sales_min preco_medio_returns_md, preco_medio_returns_sd, preco_medio_returns_max, preco_medio_returns_min(...) Standard Deviation Price: preco_sd_sales_md, preco_sd_sales_sd, preco_sd_sales_max, preco_sd_sales_min preco_sd_returns_md, preco_sd_returns_sd, preco_sd_returns_max, preco_sd_returns_min (...) Subcategory Number of subcategories of the product n_subcat_total, n_subcat_md, n_subcat_max, n_subcat_min, n_subcat_sd 88 Figure C.4: Extraction and variable construction of some the variables of Purchase Behaviour - Part II 95