scieee AI-readable full text Open interactive document viewer

Development of a software system that supports the creation of an uncertainty index in the supply chain, using Machine Learning techniques

Gomes, Joana Isabel Afonso

Abstract

The ongoing digitization of contemporary industries has propelled the need for research and innovation, particularly in Supply Chain (SC) management. Ensuring optimal production processes entails maintaining consistent material availability, highlighting the critical role of Supply Chain Management (SCM) in achieving a balanced cost-benefit ratio. Integration of Machine Learning (ML) has become pivotal in SC decision-making, leveraging vast datasets and technological advancements. This dissertation delves into the intersection of SCM, and ML, offering insights into their relationship for enhancing operational efficiency and informed decision-making in dynamic and competitive environments. By analyzing the challenges posed by uncertainty in SC operations and exploring various ML techniques, this study aims to provide practical solutions for addressing contemporary SC management challenges.

Full text

Universidade do Minho Escola de Engenharia Departamento de Informática Joana Isabel Afonso Gomes Development of a software system that supports the creation of an uncertainty index in the supply chain, using Machine Learning techniques April 2024 Universidade do Minho Escola de Engenharia Departamento de Informática Joana Isabel Afonso Gomes Development of a software system that supports the creation of an uncertainty index in the supply chain, using Machine Learning techniques Master dissertation Integrated Master’s in Informatics Engineering Dissertation supervised by Rui Manuel Ribeiro Castro Mendes April 2024 COPYRIGHT AND TERMS OF USE FOR THIRD PARTY WORK This dissertation reports on academic work that can be used by third parties as long as the internationally accepted standards and good practices are respected concerning copyright and related rights. This work can thereafter be used under the terms established in the license below. Readers needing authorization conditions not provided for in the indicated licensing should contact the author through the RepositóriUM of the University of Minho. LICENSE GRANTED TO USERS OF THIS WORK: CC BY https://creativecommons.org/licenses/by/4.0/ ACKNOWLEDGEMENTS I would like to take this opportunity to express my heartfelt gratitude to all those who have been instrumental in supporting and encouraging me throughout this journey. To all the members of the DIABO project team who provided invaluable guidance during my internship and work at Bosch, with a special acknowledgment to my project supervisors Eng. Tiago Martins and Eng. Luís Marques, I am incredibly thankful for your assistance throughout the development of my project. Special thanks to Professor Rui Mendes for graciously accepting my request to be my project supervisor and for offering valuable suggestions and constructive criticism throughout the investigation presented in this report. To my family members, whose unwavering support has been a constant throughout my academic career, I extend my deepest appreciation. To my colleagues and friends, your support, comfort, and assistance have been invaluable along this path. To Marco, for consistently believing in me and providing encouragement. To all those individuals I may not have mentioned but who, in various ways, contributed to this journey, my sincere gratitude. a STATEMENT OF INTEGRITY I hereby declare having conducted this academic work with integrity. I confirm that I have not used plagiarism or any form of undue use of information or falsification of results along the process leading to its elaboration. I further declare that I have fully acknowledged the Code of Ethical Conduct of the University of Minho. b ABSTRACT The ongoing digitization of contemporary industries has propelled the need for research and innovation, particularly in Supply Chain (SC) management. Ensuring optimal production processes entails maintaining consistent material availability, highlighting the critical role of Supply Chain Management (SCM) in achieving a balanced cost-benefit ratio. Integration of Machine Learning (ML) has become pivotal in SC decision-making, leveraging vast datasets and technological advancements. This dissertation delves into the intersection of SCM, and ML, offering insights into their relationship for enhancing operational efficiency and informed decision-making in dynamic and competitive environments. By analyzing the challenges posed by uncertainty in SC operations and exploring various ML techniques, this study aims to provide practical solutions for addressing contemporary SC management challenges. K E Y W O R D S supply chain management, machine learning, decision-making, risk management, data visualization, optimization, inventory management, SC operations. c RESUMO A contínua digitalização das indústrias contemporâneas impulsionou a necessidade de pesquisa e inovação, especialmente na gestão da Cadeia de Abastecimento (CA). Garantir processos de produção ótimos envolve manter uma disponibilidade consistente de materiais, destacando o papel crítico da Gestão da Cadeia de Abastecimento (GCA) na obtenção de um equilíbrio entre custo e benefício. A integração de Aprendizagem Automática (AA) tornou-se fundamental na tomada de decisões da CA, aproveitando vastos conjuntos de dados e avanços tecnológicos. Esta dissertação explora a interseção entre GCA e AA, proporcionando uma compreensão aprofundada da sua relação para aprimorar a eficiência operacional e a tomada de decisões informadas em ambientes dinâmicos e competitivos. Ao analisar os desafios apresentados pela incerteza nas operações da CA e explorar diversas técnicas de AA, este estudo visa fornecer soluções práticas para enfrentar os desafios contemporâneos da gestão da CA. PA L AV R A S -CHAVE gestão da cadeia de abastecimento, aprendizagem automática, tomada de decisão, gestão de riscos, visualização de dados, otimização, gestão de inventário, operações da cadeia de abastecimento. d CONTENTS Contents iii I INTRODUCTORY MATERIAL 1INTRODUCTION 4 1.1 Contextualization 4 1.2 Motivation 4 1.2.1 DIABO Project: Conceptualization and Architecture 5 1.3 Objectives 6 1.4 Document Structure 6 2S TAT E O F T H E A R T 8 2.1 Supply Chain Management 8 2.2 Uncertainty in the Supply Chain 10 2.2.1 Uncertainty Indexes 11 2.3 Reducing and Responding to Supply Chain Uncertainty 13 2.4 Machine Learning Background 13 2.5 Machine Learning Techniques in Supply Chain Management 14 2.6 Approach analysis of possible models 17 2.6.1 LASSO Regression 17 2.6.2 Decision Tree Regression 18 2.6.3 Random Forest Regression 18 II C O R E O F T H E D I S S E R TAT I O N 3SOLUTION DESIGN AND DEVELOPMENT 21 3.1 Load and adjust dataset 22 3.2 Up-sample Daily 23 3.3 Transformations 23 3.4 Downsample 24 3.5 Model Parameters Configuration 25 3.6 Lags on selected columns 25 3.7 Initial Considerations and Strategy Outline for Forecasting 27 4MODELS IMPLEMENTATION 30 4.1 Lasso Regression 30 4.1.1 Approach Analysis 30 iii C O N T E N T S iv 4.1.2 Optimization of Transformations Code 35 4.1.3 Optimization of the dataset creation 36 4.1.4 Analyze of the Lags 37 4.1.5 Other optimizations 37 4.1.6 Model Re-evaluation on the Complete Dataset 38 4.1.7 Strategizing the Execution of Rolling Window Methodology and Model Re-evaluation 38 4.1.8 Methodological Overview 40 4.1.9 Code Refactoring 41 4.2 Decision Tree Regression 44 4.2.1 Enriching Model Assessment With New Error Metrics 44 4.2.2 Transitioning to PySpark 45 4.2.3 Exploring the Growing Window Methodology in Decision Tree Regression 45 4.2.4 Hyperparameter Adjustments 46 4.2.5 Analyzing Execution Times: Observations, Testing, and Logging 47 4.3 Random Forest Regression 48 4.3.1 PySpark Implementation and Analysis Across Various Cross-Correlation Thresholds 48 4.3.2 Comparative Analysis with Decision Tree Model 49 4.3.3 Analysis of Average Mean Absolute Percentage Error (MAPE) Behavior with Increasing Horizons: Fixed Number of Trees vs. Dynamic 50 5RESULTS 52 5.1 Lasso Regression 52 5.1.1 First Results 52 5.1.2 Refined Feature Set: Only the Lags 56 5.1.3 Optimizing Convergence: Iterative Refinement 58 5.1.4 Rectification: Accurate Handling of Daily Up-Sampled Data in Cross-Correlation Analysis 58 5.1.5 Comparative Analysis with Varied Column Counts 58 5.1.6 Validating Code Integrity with Selective Column Analysis 59 5.1.7 Analyzing Monthly Downsampled Versions with Varying Cross-Correlation Thresholds 60 5.2 Decision Tree Regression 63 5.2.1 First Results 63 5.2.2 Evaluating Model Predictions and Analyzing Errors 63 5.2.3 Testing with a new dataset 65 5.2.4 Change Hardcoded Test Window Size 68 5.2.5 Rectifying Data Interpolation and Exploring With More Indicators 70 5.2.6 Performance Analysis of the Enhanced Model 71 5.2.7 Exploring atypical results 72 5.3 Random Forest 73 5.3.1 Model Evaluation with Cross-correlation (CC) Threshold Set at 1.0 73 5.3.2 Model Evaluation with Parameters Obtained at H=1 75 ACRONYMS AI Artificial Intelligence. x,5,13,14,15 CC Cross-correlation. iv,vi,vii,x,25,40,48,49,56,58,59,60,61,62,63,70,72,73,75 DIABO Data Intelligence & Analytics for Business Operations. vi,x,4,5,6 LT Lead Time. vii,x,11,15,16,21,58,59,60,63,72,73,74 MAE Mean Absolute Error. vi,x,31,32,33,34,38,44,45,50,56,57,59,62 MAPE Mean Absolute Percentage Error. iv,vii,viii,x,44,45,49,50,64,65,71,72,88,90,93 ML Machine Learning. vi,x,4,6,7,8,13,14,15,16,17,30,31,32,38,39,45,78,79 MSE Mean Squared Error. x,67 NAN Not a Number. vi,x,28,29,37,41,42,70 RMSE Root Mean Square Error. x,73,76,77 SAP System Applications and Products in Data Processing. x,5 SC Supply Chain. x,4,5,6,8,9,10,11,12,13,14,15,16,21,78 SCM Supply Chain Management. vi,x,4,6,8,9,10,11,13,14,15,16,78,79 xi Part I I N T R O D U C T O R Y M AT E R I A L 1 INTRODUCTION 1.1 CONTEXTUALIZATION The contemporary industry is presently undergoing a significant transformation as a result of the digitization of the production process. In the contemporary landscape of intense competition, the significance of research and system innovation cannot be overstated. In these given situations, the significance and necessity of new process solutions that effectively aid in the management of Supply Chains within enterprises are underscored. In order to ensure the optimal operation of the production process, it is imperative for the Supply Chain (SC) to ensure the consistent availability of necessary materials. The implementation of SCM is crucial for ensuring the uninterrupted functioning of the industrial process. Nevertheless, it is imperative to maximize the ratio between cost and benefit. The exponential growth of diverse technological advancements, along with the accumulation of extensive data from several origins, has posed novel complexities for organizational management across various hierarchical levels, specifically within the domain of SC. The integration of ML has become an integral component within the array of technologies utilized in SC decisionmaking processes, enabling organizations to leverage the expanding reservoir of available data. 1.2 M OT I VAT I O N This dissertation was written as part of a required internship at Bosch in the Automotive Electronics Logistics division in Braga, Portugal (AE/LOG-Brg) . The internship was integrated into the DIABO project. The goal of the dissertation is to provide decision-making support regarding the safety stock levels that are to be defined. Figure 1: Bosch Car Multimedia and DIABO project logos. The key emphasis of the DIABO project centers on SC risk management, particularly within the operational part depicted in Figure 2. 4 1.2. Motivation 5 Figure 2: Operational area of the DIABO project. Scope: AE Plants (P45, P72 and POE SAP systems) The reasons that led to the creation of the project (and, as a consequence, the focus of this dissertation) are as follows: • The presence of frequent interruptions in SC operations and the requirement to implement security techniques; •The current method of risk management is knowledge-based and static; • The security parameters of System Applications and Products in Data Processing (SAP) have a significant influence on inventory and service levels; •Potential benefits of using an Artificial Intelligence (AI) method in the context of controlling SC risk. 1.2.1 DIABO Project: Conceptualization and Architecture Figure 3: DIABO Project Conceptualization. 1.3. Objectives 6 Figure 4: DIABO Project Architecture. 1.3 OBJECTIVES The objective of this project is to develop and enhance data visualization generated from models utilizing supervised or unsupervised ML methodologies. The system is designed with the intention of being scalable and adaptable to effectively cater to the many departments and branches inside the corporation. Regarding the goals outlined in the work plan, the focus lies on achieving a thorough optimization of the SC, with particular attention given to the management of inventory and risk in both the upstream and downstream segments of the chain. 1.4 DOCUMENT STRUCTURE The chapters that make up this document’s structure outline the key procedures followed in creating the proposed solution. • Chapter 1 (Introduction)provides a succinct description of the setting, along with the project’s motivation and research goals. It contextualizes the research within the realm of SCM and outlines the objectives pursued throughout the study. • Chapter 2 (State of the Art)gives a general viewpoint on SCM, emphasizing the challenges posed by uncertainty in SCs. It explores various techniques employed to address uncertainty and provides background knowledge on ML techniques used in SCM and it delves into the analysis of possible ML models. • Chapter 3 (Solution Design and Development)details the process of designing and developing the proposed solution. It covers steps such as dataset loading and adjustment, data transformations, model parameter configuration, and strategic considerations for forecasting. • Chapter 4 (Models Implementation)presents the implementation details of the ML models considered in the study and it discusses the approaches taken, optimizations applied, and methodologies employed for each model. 1.4. Document Structure 7 • Chapter 5 (Results)provides a comprehensive analysis of the results obtained from implementing the ML models. It includes detailed discussions on the performance of each model, insights gained from experimentation, and comparative analyses between different approaches. • Chapter 6 (Conclusions)presents the conclusions drawn from the study’s findings and outlines potential areas for future research and development in the field. •The Appendices contain supporting figures, listings, and additional material relevant to the study. 2 S TAT E O F T H E A R T This chapter intends to present a review of the literature on the issue of uncertainty in Supply Chain Management, its importance and associated problems, while at the same time confronting this with the use of ML techniques with the intent to monitor and predict situations regarding this uncertainty and estimate supply variation. In this context, the initial goal of this dissertation is to look at the literature on the use of ML in company SC functions. It will be analyzed how ML techniques may be integrated into the suite of tools accessible to SSC decision-makers in order to take advantage of the growing volume of data available, using tools that are specifically designed for this type of processing. In light of this, it’ll focus, on the one hand, on clarifying the importance of creating an uncertainty index in the SC, and, on the other hand, why the importance of use of ML techniques on this matter. This comprehends the application of ML algorithms to special freights demand and supply variation estimation, as well as usage of external indicators as inputs to these ML algorithms. 2.1 SUPPLY CHAIN MANAGEMENT SCM refers to the control of resources, information, and money along the SC, from suppliers to component manufacturers to final assemblers to distribution (warehouses and retailers), and finally to the end user (Silver,1998), being a huge topic that spans numerous areas of study and employs a variety of quantitative and qualitative methods. Good supplier management does not equate to good SCM without a parallel effort to control the other components of product delivery. Firms that operate in international environments deal with a variety of suppliers and consumers and managing inventory in innovational ways is necessary. A good management of SC has the ability to improve preparedness while lowering risk, as well as lower maintenance costs while increasing performance. The literature on SCM discusses a variety of SC redesign strategies that can be used to reduce SC uncertainty and, as a result, improve its performance. There has been an increased interest in the topic of SCM over the last decade as a means of improving the strength of SCs, and it is quickly becoming recognized as critical to maintaining competitive advantage. Getting relevant insights from existing data could play a major role in helping decision-making within firms. Organizations are employing the most accurate and robust inventory strategies to maintain the balance between service, cost, and produce value, by leveraging SC design as a continuous process. Companies should be able to examine what SCM can accomplish for them and determine the implications of combining a SC view with one or more suppliers and/or customers. The desire is to propose qualitative research methods for examining SCs and determining effective chain redesign solutions. 8 2.1. Supply Chain Management 9 The ideal answer to the inventory question is to optimize it regularly based on a reliable projection. The inventory represents demand as well as the uncertainties of both demand and supply. According to de Leeuw (2000), some requirements must be satisfied to avoid experiencing uncertainty and thus ineffectiveness (not fulfilling objectives). • To manage the SC in the appropriate direction, the management system should have a goal and related performance indicators; • To forecast future system states, one must have knowledge of the environment and the current condition of the SC; • There should be sufficient information processing capacity to process data on the environment and the state of the SC; • To lead the controlled system in the appropriate direction, one must be able to calculate the impact of various options. This requires a system model that illustrates the connections between design factors and performance measures; • There should be a sufficient number of possible control actions. Each environment - SC state combination requires one or more different control actions to manage the system in the direction of the objectives. In terms of logistics deployment and expenditures, this inventory management system represents significant cost savings. It facilitates enhanced supply chain management, enabling companies to predict volumes, anticipate trends, and identify potential reversal periods by leveraging stock, sales data, and other external statistical information. This proactive approach empowers companies to take timely actions, such as adjusting stock levels or repackaging products, in anticipation of forthcoming shifts in demand. There are different roles in SC activities, such as suppliers, manufacturers, logistics or other service providers. The collaboration between those businesses must be structured and supervised. This is where SCM comes into play, with the main goal of meeting consumer demand promptly by organizing efficient product flows from point of origin to point of consumption. However, managers need two-way information and data flow throughout the SC in order to make the best decisions based on demand development or early problem detection. David Anderson (1997) proposed seven key principles of SCM to assist managers in deciding how to proceed, and they are still in use today, despite the fact that they are more than two decades old. The relevance of coordination efforts is emphasized by these ideas. 2.2. Uncertainty in the Supply Chain 10 Figure 5: Seven key principles of SCM, scheme based on David Anderson (1997). 2.2 UNCERTAINTY IN THE SUPPLY CHAIN The presence of uncertainty prompts the decision to create safety reserver in time, capacity, or inventory to avoid poor chain performance. Sources of uncertainty are the characteristics of the system that cause uncertainty for a particular decision maker. Therefore, one of the reasons companies keep inventories is to protect themselves against the unpredictability of future demand, which comes in the form of safety stocks. Higher levels of demand and forecast uncertainty result in the holding of more inventory, which has a negative influence on inventory turnover and profitability (Md. Erfanul Hoque and Banitalebi,2021). "Those companies which cope best with uncertainty are most likely to produce internationally competitive bottom-line performance" (Mason-Jones and Towill,1998). In SCM,SC uncertainty refers to situations in which the decision-maker is unsure what to do because of lack of transparency in the SC or the consequences of possible actions. He can either be unclear about the objectives, lack information about (or understanding of) the SC or its environment, lack information processing capabilities, be unable to accurately predict the impact of possible control actions on SC behavior, or lack effective control actions (non-controllability). All this poses decision-making challenges. The identification of sources of uncertainty in SC decision-making processes is a fundamental driver for chain redesign. It is necessary to regularly analyze why inventory is out of sync with the SC in order to create a good optimization model. Trying to figure out why these things happen would highlight the uncertainty that the optimisation model has to deal with. This uncertainty refers to changes in the SC’s balance and profitability as a result of prospective and unpredictable events, requiring a response to re-establish the balance. An unexpected order, a supplier’s late delivery, or the failure of essential production equipment are all examples of these events. 2.2. Uncertainty in the Supply Chain 11 The result of demand uncertainty is increased cost, most typically in the form of excess inventory, excess manufacturing capacity, or the utilization of faster and more expensive goods transportation. The firms usually aim to achieve a SC balance in which inventory, transportation, and SC / capacity expenses are kept to a minimum while still providing the level of service expected by customers (Lead Time and precision). Demand is difficult to predict for a variety of reasons, including causal variables, events, and irregular demand. Some of them may be anticipated, but there may be unforeseeable circumstances that drastically alter demand for products. To find successful chain redesign solutions for an existing SC, one should concentrate on identifying and managing the sources of uncertainty in decision-making processes that obstruct optimal chain performance. 2.2.1 Uncertainty Indexes The way SC experts collect and accumulate identified sets of indices has an impact on how uncertainty is perceived. In other words, variations in the orientation process of assembling affect the relative relevance of distinct uncertainty indices. Since the first relevant entries of literature on SCM, supply, process, and demand uncertainties are known to have a significant impact on industrial production (Wilding,1998). "The more uncertainty related to a process, the more waste there will be in the process" (G.,1995). The major questions (relevant indices) that represent SC uncertainty are: What will my customers order? How many products should we have in stock? Will the supplier deliver the requested goods on time and according to the demanded specifications? (Jack G.A.J. van der Vorst,2002) Will the product demand be unexpected? Is it probable that client orders may change? What kind of pressure will there be to deliver on time? (Christopher M. Durugbo,2020). These questions are linked to fluctuations in supplier performance and distribution variations, given the unpredictability of demand. The following section provides examples of the origins of uncertainty indices in the SC and categorizes them based on their types. Demand uncertainty - Unpredictable changes in demand quality, quantity, and timeliness encountered across the SC (Davis,1993), as well as distribution variances due to customer order distribution delay time, cause demand (customer and distribution) uncertainty. This relates to the discrepancy between actual and predicted demand (forecast error) (van der Vorst and Beulens,2002). - Rate of new product introduction; - Unexpected product demand; - Different sales channels; - Dharing demand forecast with customer; - Variety in distribution channels; - Changes in distribution channels; - Changes in product life-cycle; - Product variety; - Changes in customer orders. Supply uncertainty - Supplier performance variability and inconsistency cause supply (delivery) uncertainty, resulting in late, poor, or defective deliveries (Davis,1993). Machine breakdowns, manufacturing downtimes, quality and yield issues, order-entry errors, forecast inaccuracies, or logistical issues all contribute to it (van der Vorst and Beulens, 2002). 2.6. Approach analysis of possible models 18 Regression of this kind is particularly useful for feature selection and automatic variable removal. It applies a penalty to regression coefficients, encouraging some to become zero, effectively removing less relevant variables and simplifying the model. It also excels when dealing with models featuring significant inter-feature correlations, promoting a sparse model by constraining coefficient sums. 2.6.2 Decision Tree Regression Decision Tree Regression aims to establish uncomplicated decision rules based on data features to create a predictive model for a target variable. This approach is widely favored in supervised learning due to its simplicity and effectiveness. It can seamlessly handle both continuous and categorical data, making it versatile for various applications. However, it’s worth noting that the computational cost of building Decision Tree Regression models increases logarithmically as the training data volume grows (Myles et al.,2004). Figure 6: Decision Tree Regression representation; https://python-course.eu/machine-learning/decision-trees-in-python 2.6.3 Random Forest Regression Random Forest Regression is designed to enhance the predictive capabilities of Decision Tree models by leveraging the power of ensemble learning. This method builds multiple decision trees during training and merges their predictions to improve overall accuracy and robustness. The Random Forest model inherits the simplicity and effectiveness of Decision Trees while addressing some of their limitations. Like Decision Tree Regression, Random Forest Regression can handle both continuous and categorical data, providing versatility across various applications. It mitigates overfitting issues present in individual decision trees, resulting in a more robust and generalizable predictive model (Dimitriadou and Gregoriou,2023). 2.6. Approach analysis of possible models 19 Figure 7: Random Forest Regression representation (https://medium.com/a-comprehensive-guide-to-random-forest-regression) By embracing the Random Forest approach, this regression model aims to deliver improved accuracy and performance, particularly in scenarios where decision trees might fall short. Part II C O R E O F T H E D I S S E R TA T I O N 3 SOLUTION DESIGN AND DEVELOPMENT During the implementation and analysis phase, a predefined set of steps was meticulously followed, taking various factors into account to ensure the ideal execution of the model. Throughout the implementation process, it was frequently found necessary to revisit and refine the approach, occasionally retracing steps to enhance the accuracy and precision of the forecasting. With this in consideration, an analytical process focused on Unconditional Forecasting of the LT Index as the objective was initiated. In the context of the SC and logistics, the term Lead Time (LT) refers to the period that must pass between the point at which an order or request is initiated and the point at which the goods or services in question are delivered before it can be considered to have been satisfactorily processed. Because it helps businesses efficiently supply future demand without suffering stockouts or disruptions, maintaining acceptable inventory levels is a vital part of both inventory management and production planning. This enables businesses to maintain suitable inventory levels. The process of making a forecast for the LT Index without applying any particular conditions or constraints is typically referred to as "Unconditional Forecasting." In practice, this entails generating a prediction without taking into account any external factors or specific criteria that might have an effect on the total amount of time required for the LT. This could be contrasted with the idea of "conditional forecasting," which refers to the practice of creating projections based on specific circumstances, events, or criteria. Therefore, the approach started with a "Unconditional Forecasting of LT Index," producing projections or estimates regarding LTs in the context of a SC without taking into account any particular conditions or restrictions, thus offering a baseline forecast for LTs. The following is how the sequence of events during this phase was first conceived of and planned. 1. Loading and Adjusting Dataset At the project’s outset, the decision was made to select and compile the dataset of historical data pertinent to the forecasting task. Pre-processing the data was necessary to ensure it was in a format suitable for analysis. 2. Up-sampling Daily There was a requirement to up-sample the data to a daily level to standardize the data frequency. This aimed to enable reliable analysis by producing regular data intervals. 3. Transformations The data transformation strategy included fundamental statistical transformations like VARIATION (%), MOVING AVERAGE, and STANDARD DEVIATION. These transformations were conceived as a vital part of the initial data processing steps, aimed at gaining critical insights into the data’s behavior and variability. They were considered instrumental in shaping the subsequent feature engineering process, reflecting the vision conceived for the project’s early phases. 21 3.1. Load and adjust dataset 22 4. Down-sampling Selection The importance of selecting a suitable down-sampling frequency for the model’s output was acknowledged. Options included monthly, quarterly, semiannually, annually, or maintaining daily data, depending on the specific forecasting task. 5. Model Parameters Configuration Critical parameters for the Lasso Regression model were configured. This encompassed setting a correlation threshold, determining the maximum lag for inclusion in the model, and defining the forecasting horizon, all tailored to the project’s requirements. 6. Lags on Selected Columns To streamline the model and enhance performance, lags were selectively applied to specific columns in the dataset. 3.1 L O A D A N D A D J U S T DATA S E T Apache Spark was instrumental in handling the loading of the datasets. Spark stands out as a distributed computing framework, specifically designed for processing and analyzing large-scale datasets. Its distributed architecture allows for parallel processing across a cluster of machines, enabling the efficient handling of substantial data volumes. This capability substantially improves performance and minimizes processing times, a crucial factor when dealing with extensive datasets. Furthermore, Spark provides an extensive set of libraries and tools designed for diverse data operations, including data manipulation, transformation, and analysis. This comprehensive suite of functionalities streamlines the data loading process and seamlessly transitions into subsequent data pre-processing and feature engineering steps. spark = SparkSession.builder.appName("UnconditionalForescasting1").getOrCreate() series = spark.read.csv(CSV_FILES_BASE_DIR + "data_analise.csv",sep=’;’, header = True).registerTempTable("data") dataFrame = spark.sql("select *from data") pd.set_option(’display.max_rows’, 500) pd.set_option(’display.max_columns’, 500) Listing 3.1: Load original Dataset using Spark Figure 8: Partial original dataset loaded. In the process of data preparation and pre-processing, two key adjustments were made to ensure data compatibility and consistency: date format and CSV file values. To facilitate time-based analysis and standardize date formatting, the date column was designated as the index. This adjustment simplifies time series analysis, allowing for easier trend identification and temporal exploration. 3.2. Up-sample Daily 23 Additionally, transformations were applied to ensure that numerical operations and analyses could be executed smoothly, rendering the data well-suited for a wide array of analytical tasks. These and other adjustments were essential steps in preparing the data for meaningful analysis and modeling, ensuring that the data was in a consistent and usable format for a wide range of operations. 3.2 U P -SAMPLE DAILY I then commenced the procedure of increasing the sampling rate of the initial dataset to a daily frequency. Considering different methods for this up-sampling process, including techniques such as splines, polynomial interpolation, and linear interpolation, I ultimately opted for linear interpolation. Linear interpolation is chosen for its simplicity and effectiveness in filling gaps or creating intermediate data points between existing data, especially when the underlying data exhibits linear trends or relationships. def daily(): dFP = adjustCSV() upsampled = dFP.resample(’1D’) interpolated = upsampled.interpolate(method=’linear’) return interpolated Listing 3.2: Function to upsample daily The interpolate method with the linear parameter in Listing 3.2 estimates the values of missing data points by linearly interpolating between neighboring data points, ensuring that the up-sampled dataset maintains a coherent and continuous progression. This approach is well-suited for maintaining a smooth transition in the data while enhancing its granularity, effectively avoiding abrupt changes. Figure 9: Partial daily up-sampled dataset 3.3 TRANSFORMATIONS In order to augment the analysis of data and get a deeper understanding of the dataset’s patterns, a series of methodologies were devised to compute essential statistical measures across several temporal intervals, encompassing DAILY, MONTHLY, QUARTERLY, SEMIANNUAL, and ANNUAL periods. These methodologies facilitate the extraction of useful insights and patterns from the data, thereby offering a comprehensive perspective on its variability and trends. 3.4. Downsample 24 Regarding the selection of transformations, PERCENTAGE VARIATION,MOVING AVERAGE and STANDARD DEVIATION were specifically chosen. These metrics offer diverse perspectives on data behavior, each contributing valuable insights to our analytical approach. The concept of VARIATION (%) was chosen for its ability to quantify variability within a dataset, measuring how data points deviate from the mean or average value. Its sensitivity to changes in data values makes it valuable for detecting fluctuations or volatility, and it finds application in various domains, including finance and quality control, where it aids in assessing risk and uncertainty associated with data. MOVING AVERAGE was incorporated to effectively smooth out noise and short-term fluctuations in time series data, thereby revealing underlying trends or patterns. By calculating moving averages over different time periods, we gain the capability to identify both short-term and long-term trends, which are essential for decision-making and forecasting. STANDARD DEVIATION, a fundamental metric, was integrated to quantify the dispersion of data points around the mean. A higher standard deviation indicates greater dispersion, which is crucial for risk assessment, ensuring the consistency and reliability of processes. By integrating all three components, one can get a holistic comprehension of the dataset, facilitating the identification of patterns, evaluation of risks, and informed decision-making across many analytical contexts. In my data analysis, I conducted calculations for VARIATION (%) and STANDARD DEVIATION across diverse time frames, encompassing daily, monthly, quarterly, semiannual, and annual intervals. However, I deliberately limited the computation of Moving Averages to longer-term intervals. This choice was made to facilitate a comprehensive analysis while acknowledging the intrinsic characteristics of daily data, which often exhibits pronounced volatility, leading to the introduction of undue variability in the analysis, a recognized aspect of data analytics. Given this tendency, daily moving averages may not consistently align with the overarching research objective, which is primarily centered on identifying enduring, longer-term trends and facilitating the generation of reliable forecasts. Hence, the decision to focus on the selected intervals was rooted in the goal of minimizing the impact of short-term fluctuations and noise, thus enabling a more robust exploration of sustained data patterns. The code for illustrative examples of functions for transformations ( DAILY VARIATION (%), MONTHLY MOVING AVERAGE and QUARTERLY STANDARD DEVIATION ) can be found in Listing A.1 (Appendix A). There is also an illustrative dataset with the applied transformations featured in Figure 78 (Appendix B). 3.4 DOWNSAMPLE The selection of the downsampling frequency holds significant importance due to various factors. The analysis is impacted by the level of detail and the timeframes that are taken into account. The decision is made by considering the research or analytical objectives. The implementation of algorithms for downsampling serves as a practical method for transforming data. The system ensures that data may be efficiently modified to align with the analytical needs, providing flexibility and diversity in the analysis process. By offering various periods for analysis, data patterns and trends can be examined across both short-term and longterm intervals, thereby augmenting the applicability of the analysis to their particular objectives. The inherent adaptability of this methodology guarantees that the examination of data is not constrained by a predetermined frequency, but rather may be precisely adjusted to provide solutions to inquiries or tackle obstacles within a wide range of temporal contexts. 3.5. Model Parameters Configuration 25 A set of functions has been developed to facilitate the calculation of downsamples at various intervals. These functions are crucial for enabling the transformation of data into the desired timeframe, whether it be DAILY,MONTHLY, QUARTERLY,SEMIANNUAL, or ANNUAL (refer to example in Listing A.3 within Appendix A). These functions provide the flexibility to adapt the data to different analytical requirements. 3.5 MODEL PARAMETERS CONFIGURATION Prior to the execution of the model, it is essential to define the specific parameters that will guide the analysis. These parameters include the Correlation Threshold, Maximum Lag, and Horizon. Each of these parameters plays a distinct role in shaping the model’s behavior and its ability to uncover meaningful insights from the data. •CORRELATION THRESHOLD This parameter defines the level of correlation that data features must exhibit to be considered for analysis. This will prove to be advantageous, for example, in the context of generating lags, which should be based on the CC values of the columns, only selecting those that exceed a predetermined threshold. •MAXIMUM LAG The Maximum Lag parameter determines the extent to which past data points are considered when making predictions. •HORIZON The Horizon parameter sets the timeframe for forecasting future data points. The Maximum Lag parameter typically defines how many past data points are considered when making predictions. It essentially sets a limit on how far back in time the model can look to inform its predictions. On the other hand, the Horizon parameter sets the time frame for forecasting future data points. It determines how far into the future the model will make predictions. If the Horizon were set to be greater than the Maximum Lag, it would essentially mean that the model is attempting to predict data points further into the future than it is considering historical data. This would result in a logical inconsistency, as it would be like predicting events in the future without considering the relevant historical context. Thus, by ensuring that the Horizon is not greater than the Maximum Lag, the model functions inside a coherent framework, generating predictions grounded in a plausible historical context. In the scenario where we are dealing with a data frame that has been down-sampled on a monthly basis, setting the Horizon parameter to 12 aligns with the typical yearly forecasting cycle, allowing the model to capture seasonal trends and patterns. Similarly, configuring the Maximum Lag parameter to 12 ensures that the model considers a full year of historical data when making predictions, providing sufficient context for accurate forecasting. Additionally, setting the CC Threshold parameter to 0.6 strikes a balance between including a significant number of correlated features for analysis while filtering out noise and irrelevant variables, thereby optimizing the model’s predictive performance. 3.6 LAGS ON SELECTED COLUMNS The rationale for the choice to exclusively build lags on specific columns is motivated by the desire for enhanced computational efficiency, the optimization of feature selection, and the recognition of the significance of capturing temporal dependencies in time series data. The implementation of this focused strategy guarantees that the analysis 3.6. Lags on selected columns 26 is conducted in a manner that optimizes the utilization of resources and is in accordance with the intended analytical goals. As a result, the overall quality of the outcomes and forecasts is improved. When confronted with a significant volume of data, it is crucial to prioritize computational efficiency. The computational load can be greatly reduced by selectively computing cross-correlation values and thereafter generating lags exclusively on chosen columns. This methodology guarantees the use of computational resources in a strategic manner, prioritizing the analysis of data relationships that are most pertinent. Furthermore, the process of identifying columns that exhibit cross-correlation values surpassing a predetermined threshold contributes to the selection of relevant features. This process effectively reduces redundancy and noise in the data by selecting just the columns that demonstrate significant associations. This concise arrangement of columns is more inclined to encompass significant information for your study. The selection of columns on which to generate lags holds particular significance in the context of time series analysis. Temporal dependencies are frequently present in time series data, when the current observations are influenced by previous values. The inclusion of delays on specific columns enables the capturing of temporal relationships, which play a vital role in achieving precise predictions and forecasts. The objective is to prioritize the salient elements of the data analysis while reducing the incorporation of extraneous or less impactful characteristics. This methodology improves the comprehensibility and efficacy of one’s models and predictions. The original implementation of the function responsible for identifying the columns that meet a specific correlation threshold can be found in Listing A.2 (Appendix A). If downsampling has been performed before, the data is subsequently resampled to a daily frequency. The function responsible for the final up-sampling to a daily frequency, as well as the initial functions used to construct a dataset with lagged values only for columns that surpass a certain threshold, can be found in Listing A.4 and Listing A.5, correspondingly (Appendix A). Figure 10: Example excerpt of a dataframe with the application of lags. 3.7. Initial Considerations and Strategy Outline for Forecasting 27 Methods were developed to visually represent columns that above a specified threshold, as well as to enable the selection of any column and display its corresponding graphic. To accomplish this, I worked with pyplot, a data visualization tool that is a sub-module of Matplotlib, a Python library renowned for its ability to generate static, animated, and interactive visualizations. Figure 11: Examples of charts of columns exceeding the correlation threshold. Figure 12: Example of graphic from a selected column. 3.7 INITIAL CONSIDERATIONS AND STRATEGY OUTLINE FOR FORECASTING In accordance with the insights detailed in Model Parameters Configuration, the Horizon parameter plays a pivotal role in delineating the temporal scope for predicting future data points. The horizon essentially signifies the duration into the future that the model is poised to forecast. As illustrated in Figure 13, representing my inaugural conceptualization of the implementation, the devised strategy revolves around optimizing the model’s testing phase to closely approximate real values. Considering a horizon of 12, H=1 involves predictions for all 12 horizons, H=2 involves predictions from the 2nd to the 12th horizon, H=3 involves predictions from the 3rd to the 12th horizon, and so forth. This approach ensures a comprehensive examination of predictive capabilities across varying time frames, contributing to the model’s adaptability and refined accuracy. 4.1. Lasso Regression 34 Figure 18: Graphic with Traning, Testing and Prediction Figure 19: Graphic with only Testing and Prediction Subsequently, I conducted experiments using different horizons to assess the disparities in the MAE values. Horizon MAE 1 0.4497671270262664 3 0.4894198199245601 5 0.47276506833665355 10 0.496082129589138 12 0.5010544256586384 Table 1: Testing with different horizons As expected, shorter horizons result in lower MAE values compared to longer horizons. A shorter forecasting horizon means the model has to make predictions for a smaller number of time steps, which generally results in more accurate forecasts. These observations align with the fundamental characteristics of time series forecasting. Longer forecasting horizons pose a greater challenge due to the increasing complexity of underlying patterns and influences as we project further into the future. This increased complexity can lead to higher prediction errors, which is a common phenomenon in forecasting tasks. 4.1. Lasso Regression 35 As previously mentioned, the primary objective at this stage is to focus on fine-tuning the hyper-parameters of the model. The aim is experimenting with different hyper-parameter configurations, adjusting the model’s settings, and refining its predictive capabilities so to systematically optimize these parameters, in an effort to reduce prediction errors. 4.1.2 Optimization of Transformations Code Returning to the Transformations step, I aimed to optimize the code for enhanced efficiency. I initiated this process by optimizing functions and objects that were being invoked unnecessarily. Following that, I proceeded with the optimization of the function responsible for creating the table containing the original columns and all the applied transformations. For that I used the joblib’s library Parallel function. The joblib Parallel function is a valuable tool used to parallelize tasks and leverage the available computational resources efficiently. It allows for the simultaneous execution of multiple tasks, taking advantage of multi-core processors to accelerate operations. I used it to speed up the creation of the transformation table and improve and make the code more time-efficient. def optimAddTransfColumn(): num_cores = multiprocessing.cpu_count() dfL = daily() cols= dfL.columns columns = list(cols) inputs = columns results = Parallel(n_jobs=num_cores,verbose=50)(delayed(addTransfColumns)(c,dfL) for cin columns) return results Listing 4.2: Function to optimize the creation of transformations columns The N_JOBS parameter specifies the number of CPU cores to use for parallel execution. It was set to the number of CPU cores available on my system, as determined by MULTIPROCESSING.CPU_COUNT, , which resulted in 12 cores (the multiprocessing library is a Python module that provides functionality for concurrent and parallel processing). Using all available cores maximizes parallel processing, enabling the code to use full computational power, speeding up the process. The Parallel function is employed to concurrently execute the function on each column within the DataFrame. This parallel execution is advantageous for tasks that are independent across columns, resulting in substantial improvements in processing speed and efficiency. I conducted tests using an initial small dataset comprising 24 columns and measured the time required for the execution of the Indicators main function before and after optimization. •Prior to optimization of the Indicators main function: 19:00 MIN •Following optimization (average value): 04:40 MIN For the specific input dataset mentioned, the optimization of the main function led to a notable improvement of 75.3% in terms of execution time efficiency. I attempted to parallelize the code of the individual transformations functions, but this approach proved inefficient in loops as the parallelization overhead resulted in slower execution compared to the sequential code, which ran relatively faster. 4.1. Lasso Regression 36 Subsequently, I explored optimization possibilities by transitioning certain data structures from lists to dictionaries, with a focus on tasks where efficient key-based lookups were crucial. After conducting multiple tests, it became evident that the improvement was minimal, primarily because of the overhead associated with creating and utilizing dictionaries. As an example, below is an average of test results, which involved running the Daily Variation (%) function 20 times for each type of optimization. ATTEMPT 1 ATTEMPT 2 ATTEMPT 3 LIST 0.6619928 0.6619928 0.6676641 DICT 0.6662411 0.6080100 0.6797099 Table 2: Optimization test to compare the efficiency of using Lists versus Dictionaries The improvement from using dictionaries over lists was not noticeable and the overall performance differences between them were minimal. The likely reason for this insignificant improvement is that the overhead introduced by dictionary operations, such as key lookups, negated the potential benefits of using dictionaries. The practicality of dictionaries, in this case, may not have outweighed the additional processing time they required, making the effort to switch to dictionaries less valuable. Therefore, optimizing further with dictionaries didn’t lead to substantial gains, as evidenced by the marginal differences between the results. From this stage onward, the objective is to optimize the process using actual values and a indicators dataset as a representative example. For the complete dataset, initially comprising 5539 rows and 545 columns, the execution times for applying all the indicator columns were as follows: • 1 ST ATTEMPT: 98.41686 MINUTES ≈ 1HOUR AND 38 MINUTES • 2 ND ATTEMPT: 98.41686 MINUTES ≈ 1HOUR AND 38 MINUTES • 3 RD ATTEMPT: 86.91672 MINUTES ≈ 1HOUR AND 26 MINUTES ≈1HOUR AND 30 MINUTES Upon the incorporation of all indicators, the dataset dimensions expanded to 5539 rows and 7630 columns. 4.1.3 Optimization of the dataset creation In my initial approach to manage and process the data, I leveraged the versatile capabilities of the pandas library. Specifically, I utilized the TOPANDAS() function, which facilitated the seamless extraction of data from the Excel files where all my indicator data resided. Pandas provided an excellent environment for conducting data operations and transformations, allowing me to work with the data efficiently and effectively. However, as the dataset size expanded, performance issues became increasingly evident. The TOPANDAS() function, which initially provided a viable solution, began to exhibit progressively slower behavior. As a result, it became imperative to explore alternative strategies to handle larger datasets efficiently, ensuring that the computational processes would remain robust and responsive. The OPTIMTOPANDAS() function was created to address these concerns and enhance the efficiency of handling larger datasets, targeting the scalability of the operations. 4.1. Lasso Regression 37 def _map_to_pandas(rdds): return [pd.DataFrame(list(rdds))] def optimToPandas(df, n_partitions=None): if n_partitions is not None: df = df.repartition(n_partitions) df_pand = df.rdd.mapPartitions(_map_to_pandas).collect() df_pand = pd.concat(df_pand) df_pand.columns = df.columns return df_pand Listing 4.3: Optimized version of toPandas() function This function is designed to capitalize on the distributed nature of Spark, mapping each partition of the Spark DataFrame toaPandas DataFrame, thereby distributing the computation across multiple partitions. The flexibility to specify the number of partitions ( N_PARTITIONS ) for the re-partitioning of the DataFrame introduces a level of parallelism, optimizing the distribution of data across partitions for more effective processing. The results are then collected, and the Pandas DataFrame from each partition are concatenated into a unified Pandas DataFrame. The column names are appropriately assigned to align with the original DataFrame, ensuring seamless integration and consistency. By adopting this approach, the OPTIMTOPANDAS function endeavors to strike a balance between Spark’s distributed capabilities and Pandas’ ease of use, aiming to enhance the overall performance and responsiveness when working with substantial datasets. 4.1.4 Analyze of the Lags Functions were previously introduced to generate graphical representations for columns above a given threshold and to display graphic representations for any column among the several indicator columns, as discussed in the Lags on selected columns subsection. These functions now operate with remarkable efficiency when dealing with the larger dataset and the addition of a significant number of indicator columns. In the context of the input dataset, with 7630 columns down sampled to a monthly frequency, employing a crosscorrelation threshold of 0.6, alongside Maximum Lag and Horizon both set at 12, a total of 449 columns surpassed the threshold. 4.1.5 Other optimizations Within the previously developed code for Lasso Regression, a noteworthy optimization was introduced when addressing the removal of rows containing NAN values. This optimization led to a substantial enhancement in the code’s execution speed, demonstrating its remarkable effectiveness, particularly in handling a dataset of considerable volume. def removeNaN(df): columnsAllNaN = df.columns[df.isnull().all()].tolist() dfWoNaN = df.drop(columns=columnsAllNaN) dfWoNaN2 = dfWoNaN.dropna(inplace=False) return dfWoNaN2 Listing 4.4: Function to remove NAN values optimized 4.1. Lasso Regression 38 4.1.6 Model Re-evaluation on the Complete Dataset In the computation of the MAE and the predictions using Lasso Regression, it is apparent that the process is time-consuming due to the creation of the model and calculation of parameters for a substantial dataset. Specifically, for the specified parameters, the entire procedure took 1 hour and 37 minutes. The model successfully determined the optimal alpha value (0.000054), and the resulting MAE was 0.56117952197748. Figure 20: Graphic with Traning, Testing and Prediction Figure 21: Graphic with only Testing and Prediction 4.1.7 Strategizing the Execution of Rolling Window Methodology and Model Re-evaluation In the realm of dataset analysis in ML, the concept of a ROLLING WINDOW serves as a method for segmenting a dataset into successive and non-overlapping sections or windows. This technique is predominantly utilized in the analysis of time series data, where its primary purpose is to facilitate the calculation of statistics or features within these distinct temporal segments. The fundamental principles of a Rolling Window are as follows: • WINDOW SIZE: A predetermined window size is established to dictate the number of data points or time steps included in each window. 4.1. Lasso Regression 39 • SEQUENTIAL PROGRESSION: The process initiates at the dataset’s beginning, where the first window is formed by selecting data points that fall within the defined window size. Subsequently, the window is shifted forward one step at a time, and this process is reiterated until the entire dataset has been processed. • OVERLAPPING OR NON-OVERLAPPING: Depending on the specific needs and objectives of the analysis, the windows can either partially overlap, sharing some data points, or be entirely non-overlapping and independent as they traverse through the dataset. The adoption of a Rolling Window carries several advantages for dataset analysis: • EXTRACTION OF TIME-SERIES PATTERNS: In scenarios involving time series data, this approach enables the capture of patterns, trends, or temporal behaviors over designated time-frames. • TRAINING AND TESTING DATA SEGMENTATION: The Rolling Window method is instrumental for splitting data into training and testing subsets while maintaining the chronological sequence. This temporal integrity is critical for the assessment and validation of ML models. • ADAPTABILITY TO VARIABLE-LENGTH SEQUENCES: The Rolling Window technique exhibits flexibility and can be applied to sequences of varying lengths, effectively accommodating the inherent time-based intricacies of the data. Figure 22: Rolling Window scheme (https://stackoverflow.com/). The decision to utilize a Rolling Window in this context is to effectively capture temporal patterns and trends that are inherent in the dataset. This method enables the calculation of lag values, cross-correlations, or other relevant statistics within each Rolling Window, hence increasing the amount of information in the dataset for predictive modeling. Tests were initially conducted with fixed training and testing sizes to assess, analyze, and document the timings for future comparisons with the timings obtained using the Rolling Window method. The prediction part, which will involve progressively fewer rows on the forthcoming Rolling Window implementation, exhibits exceptional execution speed, as demonstrated by the recorded times below. 4.1. Lasso Regression 40 Figure 23: Prediction times for fixed Training and Testing times Hence, for predictions involving the total number of rows in this test version (which will be fewer in the final version), the process takes merely 0.07 seconds. Conversely, the model fitting process, which will involve more rows in each iteration in the final version, demands a considerably extended duration. In one of the tests, a single fit alone consumes 2 minutes and 8 seconds. By extrapolation, assuming a fixed training size (which is set to increase with each iteration, though linearly for simplification), it would require approximately 35 hours and 39 minutes to complete in this test version. Hence, the workflow needs optimization, primarily due to the extended duration of the fitting phase. 4.1.8 Methodological Overview The DataFrame was trimmed down to include only the top 5 indicators with the highest Cross-correlation (CC) values, serving as the test dataset for the Lasso Regression analysis (cf. Figure 24). Figure 24: Dataset trimmed to top 5 indicators. In each iteration of this newly adapted approach, the following steps will be executed: 1. SELECT THE TOP 5INDICATORS WITH THE HIGHEST CROSS-CORRELATION VALUES IN THE TRAINING DATA THAT EXCEED THE THRESHOLD. 4.1. Lasso Regression 41 2. APPLY LAG TRANSFORMATIONS TO THESE SELECTED INDICATORS. 3. CONSTRAIN THE NUMBER OF LAGS PER HORIZON. 4. FIT 5. PREDICT Figure 25 depicts the dataset before running the Lasso function, after removing the NAN rows. Figure 25: Dataset post-removal of NAN rows before Lasso Regression analysis. The prevailing methodology encompasses engagement with the static iteration, entailing a comparative analysis of temporal performance between the sequential and parallelized versions. Subsequently, the research advances to a subsequent stage wherein the Training and Testing components undergo modifications to synchronize with the extant versions. Due to the constraint that the selection of indicators meeting the cross-correlation criterion can only be carried out using the Training Data, a restructuring of the code has been implemented at this stage. 4.1.9 Code Refactoring Prior to the execution of the Lasso function, the dataset, as illustrated in Figure 25, comprises 2000 rows and 7657 columns. As it was discussed in Methodological Overview, the subsequent steps involve the identification of the foremost five elements within the training data that surpass the predefined threshold. Subsequently, these selected elements undergo a process of lag incorporation, with the ensuing stage entailing the imposition of constraints on the number of lags per given time horizon. 4.1. Lasso Regression 42 Figure 26: Dataset after integrating lag values. In the subsequent steps outlined in Methodological Overview, the process involves redefining the Last Training Index position within the updated DataFrame. This DataFrame incorporates the new lag values and excludes rows with NAN values. This step is crucial for incorporating the latest information into the model training (Cf. Listing A.6, Appendix A). Following the adjustment of the Last Training Index, the initial Training and Testing components are redefined to maintain the consistency of the model evaluation process (Cf. Listing A.7,Appendix A). Accordingly, the initial step involves the instantiating of the model, which instantiating is achieved through the creation of model_lasso using the LassoCV algorithm, configured with a cross-validation parameter (CV = 5), maximum number of iterations (MAX_ITER = 10000), and a fixed random state (RANDOM_STATE = 0) . This configuration, as stated before, ensures robust model fitting with an emphasis on regularization. model_lasso = LassoCV(cv=5, max_iter=10000, random_state=0) Listing 4.5: Lasso Regression Model. Following this, the iterative process ensues, comprising the stages of fitting the model, generating predictions, and interactively reformulating the training and testing datasets. This iterative procedure is essential for refining the model’s parameters and ensuring its adaptability to the evolving dataset. Listing A.8 (Appendix A) represents the implementation of this iterative process, initially hard-coded for the daily version: It is noteworthy that in the described approach, if, in the last iteration of the loop, the Last Training Index is less than the last index of the table, the final segment is disregarded. Previously, the iteration was performed for each row in X_TEST, and predictions were generated for the respective row. In the updated version, this row now corresponds to the position at the onset of the testing phase, as indicated by the blue segment in Figure 27. 4.1. Lasso Regression 43 Figure 27: Initial sketch outlining the Rolling Window implementation, structured in a monthly fashion. 4.3. Random Forest Regression 50 When compared to the Decision Tree values, the average MAPE demonstrates notable improvement, maintaining stability and showing minimal increase across various horizons. Figure 32: Comparison of Average MAE values between Decision Tree and Random Forest. As observed in Figure 32,the average MAPE for H=1 decreases by 0.3615% in the implementation of Random Forest Regression, and similarly, it experiences a notable decrease of 11.1571% for H=12, transitioning from 16.9951% to 5.380%. The dummy dataset was processed utilizing a constant number of trees (numTrees) set to 1500 within the model. This decision was driven by the need to explore the impact of a large ensemble of trees on the behavior of average MAPE values across various forecasting horizons. By selecting a substantial number of trees, the study aimed to assess the effectiveness of the Random Forest model in handling increasing horizons and to investigate any discernible trends in MAPE values. 4.3.3 Analysis of Average MAPE Behavior with Increasing Horizons: Fixed Number of Trees vs. Dynamic Adummy dataset, employed strategically as previously for analyses and testing scenarios, underwent processing utilizing a constant number of trees (set to 500). Opting for 500 trees aimed to strike a balance between computational efficiency and predictive accuracy, ensuring the model’s capacity to effectively capture underlying data patterns while remaining tractable for analysis. This step was undertaken to investigate the behavior of average MAPE values concerning the escalation of horizons. The primary objective was to document and analyze whether the trend observed was predominantly incremental. The outcomes for both the dynamic number of trees and the fixed number of trees set at 500 are presented in Figure 84 and Figure 85, respectively (Appendix B). In both versions, employing the dynamic approach for choosing the number of trees and utilizing a fixed setting with NUMTREES = 500 on the dummy dataset, the Average MAPE consistently exhibits an upward trajectory without notable fluctuations. This stands in contrast to previous observations with the Decision Tree model on the dummy dataset, where minimal fluctuations were noted. 4.3. Random Forest Regression 51 (a) DYNAMIC (b) HARD-CODED (500) Figure 33: Comparison of Results: Dynamic vs. Fixed Number of Trees Implementations. With these findings, a parallel conclusion can be drawn for the Random Forest model, akin to the observations made for the Decision Tree model. The initially unexpected fluctuations seem to be linked to the inherent characteristics of the shared dummy dataset. Figure 34 compares the values obtained from testing with the dummy dataset between the Decision Tree and Random Forest model. (a) DECISION TREE (b) RANDOM FOREST Figure 34: Comparison of results with the dummy dataset: Decision Tree vs. Random Forest Model. In making a comparison between the Decision Tree Regression model and the Random Forest model, specifically tailored for our substantially larger dataset compared to the dummy one, the results exhibit significant improvement and consistency (cf. Figure 35). However, a notable concern persists regarding the pronounced fluctuations observed between horizons. Addressing and understanding the root cause of these accentuated fluctuations remains a pivotal challenge in enhancing the overall performance and reliability of the models. (a) DECISION TREE (b) RANDOM FOREST Figure 35: Comparison of results with the complete dataset: Decision Tree vs. Random Forest Model. 5 RESULTS 5.1 LASSO REGRESSION 5.1.1 First Results In the initial iteration, the size of the predictions array matches the size of the data array for comparison, resulting in a graphic plot that is appropriately scaled. However, as the iteration progresses to H = 2 and H = 3, as depicted in Figure 37 and Figure 38 respectively, the sizes of the arrays diminish to 26 and 12. This necessitates an adaptation of the scale to ensure an accurate representation and analysis of the plotted results. In Figure 36, the plotting results for the initial iteration (H = 1) depict the matching sizes of the predictions and data arrays, ensuring a properly scaled graphic plot for accurate comparison. Figure 36: Plotting First Iteration (H=1). Figure 37 illustrates the plotting for iteration H=2 with different scales, demonstrating the challenges posed by the reduced array sizes. These differing scales reflect the need to accommodate the evolving data dimensions and ensure that the plotted results remain meaningful and interpretable despite the changing array sizes. Figure 37: Plotting for iteration H=2 with different scales. 52 5.1. Lasso Regression 53 Similarly, in Figure 38, the plotting for iteration H=2 with two different scales further emphasizes the importance of scale adaptation in maintaining the integrity of the graphical representation. These variations in scale underscore the iterative nature of the methodology adjustments and the critical role of scale alignment in facilitating accurate analysis and decision-making. Figure 38: Plotting for iteration H=2 with two different scales. At this stage, a critical reevaluation of a pivotal aspect has prompted a reassessment and subsequent refinement in the methodology. The focal point of this adjustment revolves around the concept of "jumps" as illustrated in Figure 27, denoting the lines disregarded in a Rolling Window model with Lasso regression due to varying horizons. The "jump" occurrs solely at the commencement of the process. For instance, in the daily case, there is a skip of 30 rows for h=1, 60 rows for h=2, 90 rows for h=3, and so forth. Following this initial "jump", the subsequent progression was intended to proceed on a row-by-row basis. However, it was identified that this sequential transition was not effectively implemented in the existing code. Consequently, the primary objective at this phase is the reformation of the code to align with the updated "jump" parameters. Specifically, the adjustments seek to rectify the issue where, following the initial "jump", the subsequent progression was not adhering to the intended row-by-row transition. This necessitates a refinement to ensure that the revised code accurately encapsulates the nuanced dynamics of the research model. Additionally, a parallel consideration involves the recalibration of the interior loop’s stop criteria, disregarding any prior modifications introduced for jumps of 30 rows. The overarching aim is to enhance the precision and fidelity of the iterative process, ensuring that it faithfully adheres to the intended research specifications. 5.1. Lasso Regression 54 EXECUTING FOR 3HORIZONS (a) H = 1. (b) H = 2. (c) H = 3. Figure 40: All three H’s. The elapsed time for three iterations (H=1, H=2, H=3) is approximately 3.17 minutes. 5.1. Lasso Regression 55 (a) H = 4. (b) H = 5. (c) H = 6. (d) H = 7. (e) H = 8. (f) H = 9. (g) H = 10. (h) H = 11. (i) H = 12. 5.1. Lasso Regression 56 Figure 42: All twelve H’s. The examination of the MAE reveals a discernible upward trend with the increasing forecasting horizon, up to a certain point. 5.1.2 Refined Feature Set: Only the Lags In this refinement process, the systematic removal of original columns leaves only the essential lag variables in the dataset. This purposeful reduction simplifies the feature set, concentrating on the intrinsic temporal dependencies within the data. The subsequent testing phase strategically retains the top 5 columns surpassing the CC threshold the most. This selective inclusion ensures direct relevance to the underlying dynamics of the data while simultaneously reducing dimensionality. This approach, driven by the pursuit of heightened model interpretability and efficiency, strikes a delicate balance between complexity and predictive accuracy. The decision to keep only the most influential columns optimizes the model for superior performance during testing, aligning seamlessly with the overarching objective of capturing and leveraging temporal dependencies to enhance forecasting The operations commence with the following initial DataFrame during the first iteration, when H = 1. Figure 43: Initial DataFrame in the first iteration (H=1). 5.1. Lasso Regression 57 The subsequent images delineate the outcomes for a version encompassing three distinct horizons. (a) H=1 (b) H=2 (c) H=3 (d) All three Hs Figure 44: Outcomes of the approach across three horizons. While attempting to execute a version with 12 horizons, an obstacle arose during the fourth iteration, manifesting as the output ’Objective did not converge. You might want to increase the number of iterations.’ In response, the MAX_ITER parameter was modified, transitioning from an initial value of 10,000 to an increased threshold of 40,000, while retaining the CV and RANDOM_STATE parameters from the LassoCV algorithm. model_lasso = LassoCV(cv=5, max_iter=40000, random_state=0) Listing 5.1: Lasso Regression Model. Figure 45: Iterating for the 12 horizons. By the seventh iteration, a recurrence of the request to augment the number of iterations surfaced. Similar to the version with the original columns, the error progression exhibited an ascending trend until H = 6, subsequently giving way to fluctuations. The MAE reached a visibly elevated level. In light of these observations, the subsequent strategy to enhance the model involves a further increase in the number of iterations, setting it to 100 000, with a keen eye on evaluating the resultant impact on the model’s performance. 5.1. Lasso Regression 58 5.1.3 Optimizing Convergence: Iterative Refinement Upon increasing the number of iterations to 100,000 for all 12 horizons, the model demonstrated successful convergence without any warnings. However, the error pattern displayed a distinct trend, escalating until H = 5 before transitioning into a fluctuating phase. This outcome contrasts with the previous scenario where fluctuations commenced only at H = 6, indicating a nuanced impact of the enhanced iteration count on the model’s performance dynamics. Figure 46: Iterating for 12 horizons after increasing the number of iterations to 100,000. 5.1.4 Rectification: Accurate Handling of Daily Up-Sampled Data in Cross-Correlation Analysis When addressing a bug identified during the previous analysis, a significant correction has been implemented. The execution of the Listing A.2 (Appendix A) function was erroneously considering the input data as monthly if the global variable period was defined as such, while the testing involved daily up-sampled data. This resulted in a substantial undercount of columns surpassing the CC threshold of 0.6, impacting the comprehensiveness of the analysis. In this testing phase the corrected version of the code is being employed, ensuring accurate consideration of the daily up-sampled nature of the testing data. The evaluation proceeds by initially running the analysis for the top 100 columns that exceed the threshold. Subsequently, the comprehensive analysis is extended to encompass all columns surpassing the threshold, with a focus on values derived solely from the Training data. This corrective measure is anticipated to yield more accurate and representative results aligned with the intended methodology. 5.1.5 Comparative Analysis with Varied Column Counts After identifying the top 100 columns that most consistently surpass the threshold, detailed in Figure 79 (Appendix B), I proceeded to generate lag columns for these variables. In the iteration corresponding to H = 1, the resulting DataFrame encompasses 304 columns. This count comprises the initial 100 columns selected, multiplied by 3, representing their respective lags, and includes the LT column along with its three lag counterparts. During the execution for H = 3, the longest iteration, namely H = 1, the initial attempt took approximately 35 minutes, followed by a reduced time of 33 minutes in the subsequent trial. The primary contributor to the extended running time is evidently the fitting process of the models. 5.1. Lasso Regression 59 Figure 47: Plotting longest iteration (H=1). An observable irregularity emerges a little after row 1750 and persists for a considerable duration. The current objective is to ascertain the cause or significance of this anomaly since this particular segment noticeably contributes to a substantial growth in MAE. At this juncture, a pivotal adjustment was made in the manual calculation of the MAE. It was discovered that, inadvertently, a maximum absolute error was being computed instead of the intended Mean Absolute Error (MAE) In addition to correcting this fundamental calculation, several minor bugs in the code were rectified. Despite these corrections, a challenge persists in elucidating the sudden discrepancy observed in the prediction values. After a thorough analysis of the original dataset, it became evident that this discrepancy is attributed to variations in the original values themselves. Importantly, it was determined that the irregularity is not rooted in a malfunction within the code but rather stems from inherent disparities in the underlying data. 5.1.6 Validating Code Integrity with Selective Column Analysis The exploration revealed three distinctive columns that consistently surpassed the threshold even when elevated to 0.75. These columns correspond to various Moving Average transformations of the LT variable. Remarkably, both the MONTHLY and QUARTERLY MOVING AVERAGES continue to exceed the threshold at 0.90, with the MONTHLY MOVING AVERAGE even surpassing it at an elevated threshold of 0.99. With this discovery, the idea emerged to further validate the code’s integrity by conducting a focused analysis. The plan is to run the code exclusively with these three columns, isolating them from the broader dataset. The objective is to meticulously examine the results, ensuring the absence of irregularities or anomalous peaks and confirming the robustness of the code under these specific conditions. I therefore prepared the code to run exclusively with the columns that exceed the 0.75 CC threshold, which are the aforementioned three columns. 5.2. Decision Tree Regression 66 While the dynamic calculation of the testing window size enables adaptability to changing data patterns, for experimental purposes, the code was adjusted to enforce a fixed testing window size, specifically set at WINDOWS_TEST_SIZE = 5. This modification aimed to standardize the testing window size for experimental consistency and control, creating a stable and reproducible experimental setup and establishing a consistent reference point for evaluating the model’s performance under controlled conditions. The Training percentage was changed from 0.5 to 0.6 and the testing percentage from 0.3 to 0.2, to allocate a larger portion of the dataset for training the model, potentially leading to a more robust and informed model (cf. Figure 60). (a) H=1. (b) H=2. (c) H=3. (d) H=4. (e) H=5. (f) H=6. (g) H=7. (h) H=8. (i) H=9. 5.2. Decision Tree Regression 67 (a) H=10. (b) H=11. (c) H=12. Figure 60: Enforcing a fixed testing window size and adjusting training and testing percentages. In my next testing round (cf. Figure 63), the WINDOWS_TEST_SIZE was kept at 5 and adjusted the data split ratios. I increased the training percentage to 0.7, set the sub test percentage to 0.1, and maintained the testing percentage at 0.2. This breakdown means that 70% of the data is allocated for training the model, 10% is reserved for sub testing (an intermediate evaluation during the growing window iterations), and the remaining 20% is set aside for the final testing phase. The new DecisionTreeRegressionModel output log, associated with a larger set of columns, results in a model of depth 2 with 7 nodes. The Mean Squared Error (MSE) for this model during training is higher at 4.3042. The MSE is a metric that measures the average squared difference between the actual and predicted values. A higher MSE indicates greater dispersion of errors, suggesting less accuracy in the model’s predictions. [DecisionTreeRegressionModel (uid=DecisionTreeRegressor_467022069b13) of depth 2 with 7 nodes, [2, 50, 5, 0], 4.304211311607155] Listing 5.3: DecisionTreeRegressionModel output log in 5.2.3. In contrast, the model in subsection 5.2.2, derived from working with only 38 columns, yields a Decision Tree model with a depth of 5 and 21 nodes and the MSE achieved during training is notably lower at 0.0504. A lower MSE signifies that the model’s predictions closely align with the actual values, indicating higher accuracy. (a) H=1; TRAINING TIME = 9 MIN 12 SEC. (b) H=2; TRAINING TIME = 8 MIN 55 SEC.(c) H=3; TRAINING TIME = 7 MIN 24 SEC. 5.2. Decision Tree Regression 68 (a) H=4; TRAINING TIME = 6 MIN 30 SEC.(b) H=5; TRAINING TIME = 6 MIN 27 SEC. (c) H=6; TRAINING TIME = 5 MIN 20 SEC.(d) H=7; TRAINING TIME = 4 MIN 45 SEC. (e) H=8; TRAINING TIME = 3 MIN 49 SEC.(f) H=9; TRAINING TIME = 3 MIN 27 SEC. (g) H=10; TRAINING TIME = 2 MIN 54 SEC.(h) H=11; TRAINING TIME = 1 MIN 56 SEC. (i) H=12; TRAINING TIME = 1 MIN 32 SEC. Figure 63: Comparative analysis of Decision Tree models with larger column sets and adjustment in data split ratios. 5.2.4 Change Hardcoded Test Window Size In a new analysis of this dataset (cf. Figure 65), all parameters remained unchanged, with the the exception of the hard-coded size of the WINDOWS_TEST_SIZE, which was modified to 1. This adjustment was made to refine the granularity of the testing process. By reducing the window size to 1, each test instance now corresponds to a single data point, offering a more granular and focused evaluation of the model’s performance. 5.2. Decision Tree Regression 69 (a) H=1; TRAINING TIME = 29 MIN 56 SEC. (b) H=2; TRAINING TIME = 24 MIN 22 SEC.(c) H=3; TRAINING TIME = 21 MIN 28 SEC. (d) H=4; TRAINING TIME = 19 MIN 57 SEC.(e) H=5; TRAINING TIME = 19 MIN 33 SEC. (f) H=6; TRAINING TIME = 16 MIN 52 SEC.(g) H=7; TRAINING TIME = 16 MIN 17 SEC. (h) H=8; TRAINING TIME = 12 MIN 14 SEC.(i) H=9; TRAINING TIME = 8 MIN 4SEC. (j) H=10; TRAINING TIME = 8 MIN.(k) H=11; TRAINING TIME = 4 MIN 39 SEC. (l) H=12; TRAINING TIME = 3 MIN 21 SEC. Figure 65: Analysis with WINDOWS_TEST_SIZE hard-coded as 1. 5.2. Decision Tree Regression 70 5.2.5 Rectifying Data Interpolation and Exploring With More Indicators Upon analyzing the results, it was conceived that a potential issue might lie in the data interpolation process. Subsequent investigation revealed that the interpolation was not occurring at the intended moment, resulting in a substantially smaller input dataset size. This discrepancy in the interpolation process could significantly impact the model’s performance, prompting a reevaluation and adjustment to ensure accurate and timely data interpolation. Utilizing the full dataset containing 15,638 indicators, the CC threshold was set at 0.6, resulting in 194 columns surpassing it. The initial iteration for 12 horizons (H = 1) involved working with 2,329 columns, including all lag columns. The distribution percentages for training, sub-testing, and testing remained consistent with those outlined in 5.2.3. The input dataset commences in January 2009 but, following the creation of lags and the subsequent removal of NAN values, initiates from January 2010, concluding in June 2022, encompassing twelve and a half years. The variable WINDOWS_TEST_SIZE comes back from a static, hard-coded configuration to a dynamic setting. [DecisionTreeRegressionModel (uid=DecisionTreeRegressor_d8eac5b0f6c0) of depth 5 with 31 nodes, [5, 50, 5, 0], 0.9024807032486574] Listing 5.4: DecisionTreeRegressionModel output log in subsection 5.2.5. (a) H=1 (b) H=2. (c) H=3. (d) H=4. (e) H=5. (f) H=6. (g) H=7. 5.2. Decision Tree Regression 71 (a) H=8. (b) H=9. (c) H=10. (d) H=11. (e) H=12. Figure 68: Reinstating the dynamic setting for WINDOWS_TEST_SIZE and running for the full dataset. 5.2.6 Performance Analysis of the Enhanced Model The statistical analysis and conclusions derived from testing the new dataset, spanning January 2010 to June 2022, offer crucial insights into the model’s performance. The strategic use of a 0.6 threshold effectively narrowed down the feature set to 194 columns, enhancing the model’s focus and relevance from the original 15,638. The division of the dataset into training (70%), sub-testing (10%), and testing (20%) proportions provides a robust foundation for evaluating the model’s efficacy. The computed MAPE metrics, wherein I registered the minimum and maximum values for some key indicators, reveal a comprehensive understanding of the model’s predictive capabilities. 1. AVERAGE MAPE • The minimum average MAPE of 4.7948 underscores the model’s ability to, on average, make predictions with a relatively low percentage deviation from actual values. • Simultaneously, the maximum average MAPE of 10.4198, while higher, reflects a reasonable level of accuracy in the model’s average predictions, providing confidence in its overall performance. 2. MINIMUM MAPE • Achieving a minimum min. MAPE of 0.02 highlights instances where the model excelled in producing remarkably accurate individual predictions. • The maximum min. MAPE of 0.712, although higher, still indicates the model’s capacity to maintain relatively low percentage deviations in its most accurate predictions. 5.2. Decision Tree Regression 72 3. MAXIMUM MAPE • The minimum max. MAPE of 18.297 points to situations where the model faced challenges, resulting in higher percentage deviations in specific predictions. • At the same time, the maximum max. MAPE of 23.871, while representing more significant challenges, demonstrates the model’s adaptability in handling a range of scenarios. These positive aspects of the computed metrics reinforce the model’s effectiveness, showcasing its ability to deliver accurate predictions, even in more challenging instances. The comprehensive evaluation provides a solid foundation for further refinement and improvement, contributing to the ongoing enhancement of predictive accuracy. 5.2.7 Exploring atypical results Upon recognizing identical outcomes in horizons 6 and 7, a thorough investigation was initiated to identify the root cause. The examination focused on potential issues arising from the creation of lags or any factors associated with the input dataset for the Training function. In an attempt to isolate potential issues, an additional test was conducted with a CC threshold of 1.0, allowing only the LT column to pass. This step aimed to uncover any underlying patterns or anomalies that might elucidate the consistent results observed in horizons 6 and 7. (a) H=6, CC THRESHOLD 1.0 (b) H=7, CC THRESHOLD 1.0 Figure 70: Test with a CC threshold of 1.0 to reveal underlying anomalies that may contribute to the results in horizons 6 and 7. Based on the tests conducted in the previous images, it can be deduced that the inconsistency observed in the earlier reported results is attributed to the repetition of input data. Conducting additional tests, the number of windows was adjusted to 20, and the threshold was set to 0.7, accompanied by refinements to the interpolation function. The model was run for multiple horizons with these parameters on the full dataset, and Figure 80 (Appendix B) illustrates a clear comparison between predictions and MAPE values for each window in iterations 6 and 7. Notably, there are no issues detected for these two horizons, with distinct and discernible values. Additionally, experiments were performed using a dummy dataset featuring the same dates with random values to assess the model’s behavior (cf. Figure 81,Appendix B). Despite minor discrepancies, the generation and utilization of the dummy dataset indicate a trend where the average MAPE increases as the lags approach only the 12th lag. 5.3. Random Forest 73 5.3 RANDOM FOREST 5.3.1 Model Evaluation with CC Threshold Set at 1.0 The Random Forest model was tested with a CC threshold set at 1.0, considering only the LT column, as detailed in Figure 83 (Appendix B). A new approach was introduced, utilizing Root Mean Square Error (RMSE) as an alternative error metric. RMSE, calculated as the square root of the average of squared differences between predicted and observed values, offers a straightforward measure of model performance, particularly in capturing the magnitude of errors. Its advantages include sensitivity to larger errors and simplicity of interpretation. During the assessment focused solely on the LT column, a deviation was identified in horizons 7 and 8. Figure 71: Identification of Deviation in Horizons 7 and 8. To further investigate, the next step involves testing the LT column with consistent parameters across all iterations - eliminating dynamic parameter selection by the model. This will help determine if the error consistently increases with each iteration, as expected. Therefore, I standardized the parameters with the following values: MAXDEPTH as 10, MAXBINS as 50, MININSTANCESPERNODE as 20, SUBSAMPLINGRATE as 1, and NUMTREES as 500. 5.3. Random Forest 74 Figure 72: Exploring Consistent Parameters: Testing the LT Column with Fixed Parameters Across Iterations. Figure 72 illustrate the outcomes when running the model exclusively for Lead Time lags, with all parameters held constant. As anticipated, the results demonstrate an increase in error values with more horizons (higher values of H). This observation supports the conclusion that the fluctuations in error values observed previously are attributed to variations in parameter choices during model execution. A comparison between the results of the model using randomly selected fixed parameters and the dynamic version, where the code autonomously selects the best parameters, reveals that, despite fluctuations, error values are generally improved for most initial horizons (refer to Figure 73). (a) FIXED PARAMETERS. (b) DYNAMIC CHOICE OF PARAMETERS. Figure 73: Comparing model results: Randomly selected fixed parameters vs. Dynamic Version. Efficiency in parameter selection tends to decline with reduced data availability (higher values of H). As noted in previous conclusions, predictions become less accurate with an increase in H, reflecting the model’s reduced data to work with. 5.3. Random Forest 75 Considering this, there is a hypothesis to run the model for all horizons with parameters chosen by the code for H=1. This will be explored in the following section, setting the CC threshold as 0.6 (as tested and documented earlier) to assess potential improvements in results. 5.3.2 Model Evaluation with Parameters Obtained at H=1 The parameters dynamically chosen by the model for H=1 were documented as follows: MAXDEPTH as 10, MAXBINS as 100, MININSTANCESPERNODE as 5, SUBSAMPLINGRATE as 1, and NUMTREES as 500. The outcomes of running the model with these parameters are presented in Figures 74 and 75. Figure 74: Results of Model Evaluation with Parameters Obtained at H=1. Figure 75: RMSE Values for Model Evaluation with Parameters Obtained at H=1. BIBLIOGRAPHY 82 Benabbou Loubna Mahraz Mohamed-Iliasse and Berrado Abdelaziz. Is Machine Learning Revolutionizing Supply Chain? 2020. R. Mason-Jones and D.R. Towill. Shrinking the supply chain uncertainty circle. 1998. Srimantoorao S. Appadoo Ruppa K. Thulasiram Md. Erfanul Hoque, Aerambamoorthy Thavaneswaran and Behrouz Banitalebi. A Novel Dynamic Demand Forecasting Model for Resilient Supply Chains using Machine Learning. 2021. Elena-Adriana MINASTIREANU and Gabriela MESNITA. Light GBM Machine Learning Algorithm to Online Click Fraud Detection. 2016. Javier M. Moguerza and Alberto Muñoz. Support Vector Machines with Applications. 2006. Anthony J. Myles, Robert N. Feudale, Yang Liu, and Nathaniel A. Woody. An Introduction to Decision Tree Modeling. 2004. Sundaravalli Narayanaswami. Urban transportation: innovations in infrastructure planning and development. 2017. Razvan Pascanu, Tomas Mikolov, and Yoshua Bengio. Properties and Training in Recurrent Neural Networks. 2017. S. Raschka and V. Mirjalili. Python Machine Learning. 2017. Dr G.Naga Rama Devi Sandhya Makkar, Vijender Kumar Solanki. Applications of Machine Learning Techniques in Supply Chain Optimization. 2020. Pyke D. F. Peterson R. Silver, E. A. Inventory Management and Production Planning and Scheduling. 1998. Supply & Demand Chain Executive. How to apply machine learning in supply chain planning. URL https://www.sdcexec.com/ software-technology/emerging-technologies/article/21603093/ toolsgroup-how-to-apply-machine-learning-in-supply-chain-planning. Rong Tang, Yuting Zhao, and Huilong Lin. Spatio-Temporal Variation Characteristics of Aboveground Biomass in the Headwater of the Yellow River Based on Machine Learning. 2021. Samir Touzani, Jessica Granderson, and Samuel Fernandes. Gradient boosting machine for modeling the energy consumption of commercial buildings. 2018. Jack G.A.J. van der Vorst and Adrie J.M. Beulens. Identifying sources of uncertainty to generate supply chain redesign strategies. 2002. Leo R. Vijayasarathy. Establishing a transport operation focused uncertainty model for the supply chain. 2008. Leo R. Vijayasarathy. An investigation of moderators of the link between technology use in the supply chain and supply chain performance. 2010. Richard Wilding. The supply chain complexity triangle: Uncertainty generation in the supply chain. 1998. Part III A P P E N D I C E S A LISTINGS def dailyVariation(column): day = daily() lista = day[column] variation = [] variation.append("") if(lista[1]): b4 = 0 count = 1 for lin lista[1:]: listNew = [] listNew.append(lista[b4]) listNew.append(lista[count]) variation.append(statistics.variation(listNew)) b4=b4+1 count=count+1 return variation def monthlyMAv(column): day = daily() lista = day[column] mav = [] if(lista[30]): index = 0 while(index<29): mav.append("") index=index+1 window_size = 30 numbers_series = pd.Series(lista) windows = numbers_series.rolling(window_size) moving_averages = windows.mean() moving_averages_list = moving_averages.tolist() final_list = moving_averages_list[window_size - 1:] result = mav + final_list else: for lin lista: mav.append("") result = mav return result def quarterlyStd(column): day = daily() lista = day[column] std = [] if(lista[120]): index = 0 while(index<=119): std.append("") index=index+1 b4 = 0 count = 119 for lin lista[120:]: listNew = [] for cin lista[b4:count]: listNew.append(c) std.append(statistics.stdev(listNew)) b4=b4+1 count=count+1 else: for lin lista: std.append("") return std Listing A.1: Ilustrative examples of functions for transformations: Variation (%) daily + Moving Average monthly + Standard Deviation quarterly. def getColsWLag(arg): # Dataframe without Lead Time dfWo = dataWoLT2() # Dataframe with Lead Time dfLT = dataWoLT() global period global corrThreshold listAbv = [] ccf_outputs = [] ccf_outputs_all = [] for col in dfWo: backwards = smt.ccf(dfLT[’Lead Time ’],dfLT[col], adjusted= False) forwards = smt.ccf(dfLT[’Lead Time ’],dfLT[col], adjusted= False) ccf_output = np.r_[backwards, forwards] listInd = [] if period == ’Daily’: for iin ccf_output[:365]: # print(i) if i > corrThreshold: listInd.append(i) if period == ’Monthly’: for iin ccf_output[:12]: if i > corrThreshold: listInd.append(i) if period == ’Quarterly’: for iin ccf_output[:4]: if i > corrThreshold: listInd.append(i) if period == ’Semiannual’: for iin ccf_output[:2]: if i > corrThreshold: listInd.append(i) if period == ’Annual’: for iin ccf_output[:1]: if i > corrThreshold: listInd.append(i) if len(listInd)>0 : listAbv.append(col) ccf_outputs.append(tuple((ccf_output, col))) ccf_outputs_all.append(tuple((ccf_output, col))) # ccf_outputs is the list with the cc of the columns that exceed the threeshold # ccf_outputs_all is the list with the cc of all columns (all indexes) return ccf_outputs, ccf_outputs_all, listAbv 84 85 Listing A.2: First implementation of identifying columns that meet a specified correlation threshold. def monthly(choice): interpolated = retDataFrame2() dowsampled_month = interpolated.resample(’1M’) monthly = downsampled_month.mean() monthly.index = pd.to_datetime(monthly.index, format =’%Y-%m-%d’).strftime(’%Y-%m’) if choice==1: display(monthly) return monthly Listing A.3: Function for Monthly Downsample. def upsampleFinalDaily(): if(period==’Daily’): interpolated = daily2() if(period==’Monthly’): dUFD = monthly(0) index = dUFD.index dUFD.index = pd.to_datetime(dUFD.index, format=’%Y-%m’, errors=’coerce’) dUFD.index = pd.to_datetime(dUFD.index, format=’%Y-%m-%d’, errors=’coerce’) upsampled = dUFD.resample(’1D’) interpolated = upsampled.interpolate(method=’linear’) if(period==’Quarterly’): dUFD = quarterly(0) upsampled = dUFD.resample(’1D’) interpolated = upsampled.interpolate(method=’linear’) if(period==’Semiannual’): dUFD = semiannual(0) upsampled = dUFD.resample(’1D’) interpolated = upsampled.interpolate(method=’linear’) if(period==’Annual’): dUFD = quarterly(0) upsampled = dUFD.resample(’1D’) interpolated = upsampled.interpolate(method=’linear’) return interpolated Listing A.4: Final upsampling to a daily frequency. def addLagColumns(): dfF = upsampleFinalDaily() cols = dfF.columns colsWLag = getColsWLag(0)[2] index = 0 for cin cols: # Insert daily indicator columns colValues = dfF[c].to_numpy() dfF.insert(index, c + "", colValues , True) index=index+1 if (c in colsWLag): count=1 while(count<=12): shft = count *30 new_col = dfF[c].shift(shft) if(count == 1): dfF.insert(index, "LAG 1 MONTH - " + c, new_col, True) else: dfF.insert(index, "LAG " +str(count)+ " MONTHS- "+ c, new_col, True) index=index+1 count=count+1 count=1 for cin cols: dfF = dfF.iloc[: , :-1] return dfF Listing A.5: First implementation of lags only on selected columns. nrRowsBefore = len(result.index) resultNaN = removeNaN(result) nrRowsAfter = len(resultNaN.index) dfRows = nrRowsBefore - nrRowsAfter newLTI = lti - difRows Listing A.6: Update last training index position in new DataFrame with new lags and NaN-removed rows. X = resultNaN.iloc[:,1:] y = resultNaN[’Lead Time’] nrCols = len(X.columns) nrRows = len(X.index) X_new = np.array(X.values.tolist()) X_train = X_new[:newLTI+1] X_test = X_new[newLTI+1:] y_train = y[:newLTI+1] y_test = y[newLTI+1:] 86 y_train_arr = np.array(y_train) Listing A.7: Adjusting the initial training and testing segments. \begin{lstlisting}[language=Python, caption=Fit, Predict, and Reformulate for Each Iteration., label={lst:fitpredictandreformulate}] while(ltiWithJump <= lastAllIndex): ### *** ### Fit ### *** model_lasso.fit(X_train, y_train_arr.ravel()) ### *** ### Predict ### *** row = X_test[0] yhat = model_lasso.predict([row]) yhatList.append(yhat) ### *** ### Reformulate Training and Testing ### *** newLTI = newLTI + jump ltiWithJump = ltiJump + jump X_train = X_new[:newLTI+1] X_test = X_new[ltiWithJump:] y_train = y[:newLTI+1] y_test = y[ltiWithJump+1:] y_train_arr = np.array(y_train) Listing A.8: Fit B SUPPORTING FIGURES Figure 78: Application of Transformations to an original dataset. Figure 79: The top 100 columns exceeding the specified threshold. 87 88 Figure 80: Comparison of predictions, MAPE values and other metrics for each window in iterations 6 and 7 on the full dataset. 89 Figure 81: Execution of Decision Tree on a dummy dataset with random values. 90 Figure 82: Predictions and MAPE values documented for the entire dataset across all iterations. 91 Figure 83: Random Forest Model Testing with a CC Threshold of 1.0.